#!/usr/local/bin/perl
# Makes a Fifo called /var/adm/popauther reads from that Fifo all POP
# sessions from Syslog.  Puts the IPs in /var/spool/popauth/
# with version 1.3-3 of syslog you can add an entry in your /etc/syslog.conf
# local0.info                                     |/var/adm/popauther
# which will cause all local0 syslog messages of priority info or greater to 
# be inputted into the fifo.
#
$fifo = "/var/adm/popauther";
$popauthspool = "/var/spool/popauth/";
$poppersyslog = "/var/log/log.popper";
$watcherlog = "/var/log/popauth.watcher.log";
$popwatcherpidfile = "/var/run/popauth.watcher.pid";
$hourstoallow = 0.5;

while(1) {
    unless( -p $fifo) {
	unlink $fifo;
	system("mkfifo -m 644 $fifo") && die "Can't mkfifo $fifo: $!";
    }
    open(FIFO, "< $fifo");
    open(LOG,">>$watcherlog") || die("Can't open $watcherlog");
    print LOG "\n$date Starting log for popauth.watcher at pid $$\n";
    select(LOG);
    $| = 1;
    select(STDOUT);
    $| = 1;
    $SIG{'INT'} = 'handler';
    $SIG{'QUIT'} = 'handler';
    $SIG{'KILL'} = 'handler';
    open(PID,">$popwatcherpidfile");
    print PID "$$\n";
    close(PID);
    while($line = <FIFO>) {
# The following regular expression has to be changed to work with what ever
# POP daemon you use.  The following expression is for CuciPopper.
	if($line =~ /^([A-Za-z]+\s+\d+\s\d+\:\d+\:\d+)\s\w+\scucipop\[\d+\]\:\s([a-z0-9]{2,8})\s(\d+\.\d+\.\d+\.\d+).+$/) {
	    $tstamp = $1;
	    $user = $2;
	    $ip = $3;
	    if( $user !~ /authenti/ && $user !~ /lost/ ) {
		print LOG "$tstamp $user authenticating relaying for $ip\n" ;
		$file = ">".$popauthspool.$ip;
		if( -f $popauthspool.$ip ) {
		    system("mv /etc/mail/popauth /etc/mail/popauth-old");
		    opendir(DIR, $popauthspool);
		    @dir = readdir(DIR);
		    closedir(DIR);
		    open(POPAUTH, ">/etc/mail/popauth");
		    foreach $file (@dir) {
			if($file !~ /^\./) {
			    print POPAUTH "$file\tOK\n";
			}
		    }
		    close POPAUTH;
		    sleep 5;
		    system("cat /etc/mail/popauth | makemap dbm /etc/mail/popauth");
		}
		open(TEMP,$file);
		close(TEMP);
	    }
	}
	$time = time - (60 * 60 * $hourstoallow);
	opendir(DIR2,$popauthspool);
	@dir2 = readdir(DIR2);
	closedir(DIR2);
	foreach $file (@dir2) {
	    if( $file !~ /^\./) {
		$mtime = (stat($popauthspool.$file))[8];
		if( $mtime < $time ) {
		    print LOG "removing authentication for relay from $file\n";
		    unlink($popauthspool.$file);
		}
	    }
	}
    }
    close(LOG);
}
exit(1);

sub handler {
    local($sig) = @_;
    close(POPPER);
    close(LOG);
    exit(0);
}
