#!/usr/bin/perl
#
# This Perl script reads mail logs and submits to a BLD daemon anything
# that looks like a "user unknown" Postfix log line 
#
# Olivier Beyssac <obld@r14.freenix.org>
#
# Contributors:
#  Tim Bynum <tjbynum@timsplace.org>
#

use IO::Socket;
use strict;

my $bld_host = "localhost";
my $bld_port = "2905";

sub bld_submit($$$$)
{
    my ($host, $port, $ip, $debug) = @_;

    my $sd = IO::Socket::INET->new(PeerHost => $host, PeerPort => $port)
	|| return undef;

    my $buf;
    return if (sysread($sd, $buf, 1024) <= 0);
    print "BLD: $buf" if ($debug);
    syswrite($sd, "ip=$ip\r\n");
    print "YOU: ip=$ip\r\n" if ($debug);
    return if (sysread($sd, $buf, 1024) <= 0);
    print "BLD: $buf" if ($debug);

    close($sd);
}

my $debug;

if ($#ARGV == 0 && $ARGV[0] eq "-d") {
	$debug = 1;
}

while (<STDIN>) {
    if (/postfix\/smtp[^:]+:[^:]+: reject: RCPT from [^\[]+\[([^\]]+)\]: .* User unknown/) {
	bld_submit($bld_host, $bld_port, $1, $debug);
    }
}
