#!/usr/local/bin/perl
# Change the following for your system:
 
$popauthspool = "/var/spool/popauth";
$poppersyslog = "/var/log/pop.log";
$watcherlog = "/var/log/popwatch.log";
$popwatcherpidfile = "/etc/popwatch.pid";
$popwatchoutfile = "/etc/tcp/tcp.smtp.filter";
$TAIL = "/usr/local/bin/tail";
$date = `/usr/local/bin/date`; chop($date);

# make database of IPs seen so far

@ips = `ls $popauthspool`;
#print @ips;
foreach $ip (@ips) {chop($ip);
   $ipok{$ip} = "OK";
}
 
# now watch log file and add new IPs as encountered
# performance buglet: this will also add IPs in the local range as well
# as travellers, but it's probably not worth the effort to filter them
# out since each IP will be added a maximum of once per day.

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);
 
open(POPPER,"$TAIL -f $poppersyslog |") || die("Can't $TAIL -f $poppersyslog");
while(<POPPER>) {
   if(/^([A-Za-z]+\s+\d+\s+\d+\:\d+\:\d+).+POP login for \"(.+)\".+\s(\d+\.\d+\.\d+.\d+).*$/) {
       $time   = $1;
       $user   = $2;
       $ip     = $3;
       if ($ipok{$ip} eq ":") {
#          print LOG "$time $user $ip $ipok{$ip} already exists\n";
       } else {
          print LOG "$time $user $ip $ipok{$ip}\n";
          $ipok{$ip} = "OK";
          open(TEMP,"> $popauthspool/$ip");
          close(TEMP);
 
         open (OUT,">$popwatchoutfile");
         foreach $key (keys %ipok) {
            print OUT "$key:allow,RELAYCLIENT=//\n";
         }
         close (OUT);
 
         # $rc = system ("cd /etc/tcp ; /etc/makemap hash pophash.junk < pophash.tmp");
         # $rc = system ("mv /etc/tcp/pophash.junk.db /etc/mail/pophash.db");
	$rc = system ("cd /etc/tcp ; cat $popwatchoutfile tcp.smtp | /usr/local/bin/tcprules tcp.smtp.cdb tcp.smtp.cdb.$$");
       }
   }
}
close(POPPER);
close(LOG);
exit(1);

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