#!/opt/local/bin/perl

# calculates statistics for the ASSP maillog file
# (c) John Hanna 2003 under the terms of the GPL
#
# Thanks to R.Toth for his suggestions

$con=$bs=$dns=$dbs=$ndbs=$local=$white=$whiteadd=$badattach=$spamad=$spamlover=
 $connects=$relayblks=$mok=$dnsc=$dmok=$ndmok=0;

while(<>) {
 if(/Connected: /) {
  $con++;
  next;
 }
 if( /bayesian spam/i ){
  $bs++;
  if($dns) {$dbs++} else {$ndbs++}
 }
 $local++ if / (127\.0\.0\.1|10\.|169\.254\.|172\.16\.|192\.168\.).* local or wh/;
 $white++ if /whitelisted/;
 $whiteadd++ if /whitelist addition/;
 $badattach++ if /bad attachment/;
 $spamad++ if /spam address/;
 $spamlover++ if /rcpt to only spamlovers/;	# So we can see just how much is passing thru
 $relayblks++ if /relay attempt blocked/;	# Got 'em... and dropped them like a stone...
 if( /message ok/ ) {
  $mok++;
  if($dns) {$dmok++} else {$ndmok++}
 }
 ($dns)=/(dnsbl hit)/;
 $dnsc++ if $dns;
 $d{$1}++ if /^(\S+)/;
}
@d=keys %d;
$days=@d;
die "No data found\n" unless $days;
$spams=$spamad + $bs + $badattach;
$tot=$mok + $spams + $white;
$nonspam=$mok + $white;
$white-=$local;
open(F,"<whitelist"); {local $/="\n"; my $n=0; $n++ while(<F>); $numwhite=$n-1;}
printf "As of ".localtime()." the mail logfile shows:
$con proxy / smtp connections
$relayblks were dropped for attempted relays (%.1f%% of total).

$tot messages, $spams were spam (%.1f%%) in $days days
 for %.1f messages per day or %.1f spams per day
$whiteadd additions to / verifications of the whitelist (%.1f per day)
$bs were judged spam by the bayesian filter (%.1f%% of spam)
$spamad were to spam addresses (%.1f%% of spam)
$badattach were rejected for executable attachments (%.1g%% of spam)
$local were sent from local clients (%.1f%% of nonspam)
$white were from whitelisted addresses (%.1f%% of nonspam)
$spamlover messages were passed to SPAMLOVERs
$mok were ok after a bayesian check (%.1f%% of nonspam)
$numwhite addresses are on the whitelist

$dnsc hits on the blacklist
$dbs resulted in spam (%.1f%% of Bayesian spam, %.1f%% of blacklist hits)
$dmok resulted in non-spam (%.3f%% of blacklist hits)
",
p($relayblks,$con),

p($spams,$tot),
p($tot,$days)/100, p($spams,$days)/100,
p($whiteadd,$days)/100,
p($bs,$spams),
p($spamad,$spams),
p($badattach,$spams),
p($local,$nonspam),
p($white,$nonspam),
p($mok,$nonspam),

p($dbs,$bs), p($dbs,$dnsc),
p($dmok,$dnsc)
;

# return percent and not die if denominator is 0
sub p {my ($a,$b)=@_; my $p=$b? $a/$b*100:0; $p;}
