#!/usr/bin/perl

use Socket;

%HOSTS={};

$logfile="$ARGV[0]"; shift;
$sourcelen=60;
$targetlen=30;
$myname=`uname -n`; chop $myname;

foreach $myint (@ARGV) {
	$num++;
	$myip=`/sbin/ifconfig $myint|sed -n 's/^.*inet addr:\\([0-9\\.]*\\) .*\$/\\1/p'`; chop ($myip);
	$myint[$num]="${myint}:${myip}";
	$not_from[$num]="${myip}:3";
	$not_to[$num]="${myip}:113 ${myip}:0";
}

printheaders();

open(LOG, "< $logfile") || die "Unable to open log file for reading!";
while(<LOG>) {
	if ( ( !  /.*Packet log.*REJECT.*/gi ) &&
	     ( !  /.*Packet log.*DENY.*/gi )
	   ) { next ; }

	@fields = split(" ", $_);
	next if (! $fields[14]) ;

	($host, $port) = split(':', $fields[12]);
	($shost, $sport) = split(':', $fields[11]);

	$sport =~ s/ //gi;

	$skipit=0;
	foreach $all_filters (@not_from) {
		foreach $filter (split(' ', $all_filters)) {
			if ("${shost}:${sport}" eq "${filter}") { $skipit=1; }
		}
	}
	foreach $all_filters (@not_to) {
		foreach $filter (split(' ', $all_filters)) {
			if ("${host}:${port}" eq "${filter}") { $skipit=1; }
		}
	}
	next if ($skipit > 0 ) ;

	$name=resolv($host);
	$sname = resolv($shost);

	foreach $filter (@myint) {
		($myint, $myip) = split(':', $filter);
		if ($host eq $myip) { $name = "${myint}-${myname}"; }
		if ($shost eq $myip) { $sname = "${myint}-${myname}"; }
	}

	$xproto = getservbyport($port,'tcp'); 
	$xproto = $port if ( $xproto =~ /^$/ );

	$sxproto = getservbyport($sport, 'tcp'); 
	$sxproto = $sport if ( $sxproto =~ /^$/ );

	printf("%3s %2s %-9s ", $fields[0], $fields[1], $fields[2]);
	printf("%-${sourcelen}s ", "${sname} (${sxproto})");
	printf("%-${targetlen}s\n", "${name} (${xproto})");
}
close(LOG);
1;


sub resolv # resolv the hostname and cache the result
{
	local $mname,$miaddr,$mhost;
	$mhost=shift;

  	$miaddr = inet_aton($mhost); # or whatever address
    if (! $HOSTS{$mhost} ) {
    	$mname  = gethostbyaddr($miaddr, AF_INET);
    	if ( $mname =~ /^$/ ) {
			$mname=$mhost;
		}
		$HOSTS{$mhost}=$mname;
	}   
	return $HOSTS{$mhost}
}

sub printheaders{
	printf("\n%-16s %-${sourcelen}s %-${targetlen}s\n","DATE", "FROM", "TO");
	print "=" x 130;
	print "\n";
}
