#!/usr/bin/env python                                                                                       
# -*- coding: utf-8 -*-                                                                                     

#***************************************************************************
#*                                                                         *
#*   This program is free software; you can redistribute it and/or modify  *
#*   it under the terms of the GNU General Public License as published by  *
#*   the Free Software Foundation; either version 2 of the License, or     *
#*   (at your option) any later version.                                   *
#*                                                                         *
#***************************************************************************

""" 
    Written by Robert Penz <robert@penz.name>                                
"""                                                                          

import re
import sys
import time

# Beispiel
#Jul 26 15:24:53 mail courieresmtpd: error,relay=::ffff:189.87.47.237,from=<autopilots40502017@outertech.com>,to=<autopilots40502017@outertech.com>: 511 http://www.spamhaus.org/query/bl?ip=189.87.47.237
regex = re.compile(r'^.*courieresmtpd: error,relay=::ffff:(?P<ip>[^,]+),from=.*: 511 http://.*$')

iptablesRecentFilename = "/proc/net/ipt_recent/spammer"

# Print usage message and exit
def usage(*args):             
    sys.stdout = sys.stderr   
    print __doc__             
    print 50*"-"              
    for msg in args: print msg
    sys.exit(2)    

def tail_f(file, interval = 1.0):
    """ returns any new line """
    while True:
        where = file.tell()
        line = file.readline()
        if not line:
            time.sleep(interval)
            file.seek(where)
        else:
            yield line

def watch4spammers(filename):
    """ looks in the courier logfile if a mail has been bounced to an DNS RBL check if so
        add the IP to the iptables blocklist
    """
    for line in tail_f(open(filename)):
        found = regex.match(line)
        if found:
            #print found.group("ip")
            add2iptables(found.group("ip"))           

def add2iptables(ip):
    """ adds the provided IP to the iptableslist """
    open(iptablesRecentFilename, "a").write("+%s\n" % ip)

# Main program: parse command line and start processing                                                           
def main():                                                                                                       
    watch4spammers(sys.argv[1])
    
if __name__ == '__main__':
    main()
