#! /usr/bin/perl

use strict;
use Net::hostent;
use Socket;

my($CACHEFILE) = "dnscache";

my(%COLOR) = ("137", "blue",
	      "138", "blue",
	      "139", "blue");

my(%Reject);
my(%DNScache);
my($month, $day, $time, $host, $message);
my(%P, $i, $key, $value);

&CacheRead;

while (<>) {
    next if (! / kernel: iptables: /);
    ($month, $day, $time, $host, $message) = split(/\s+/, $_, 5);

    $message =~ s/^kernel: iptables: //;

    undef %P;
    foreach $i (split(/\s+/, $message)) {
	($key, $value) = ($i =~ /^(\S+)=(\S*)/);
	$P{$key} = $value;
    }

    if ($P{"PROTO"} ne "ICMP") {
	if ($COLOR{$P{"DPT"}}) {
	    printf '<font color="%s">', $COLOR{$P{"DPT"}};
	}
	printf("%s %2d %s %-4s %s(%s):%s > %s:%s",
	       $month, $day, $time,
	       $P{"PROTO"},
	       &Lookup($P{"SRC"}), $P{"SRC"}, $P{"SPT"},
	       $P{"DST"}, $P{"DPT"});
	if ($COLOR{$P{"DPT"}}) {
	    printf '</font>';
	}
	print "\n";
    }
    else {
	print '<font color="green">';
	printf("%s %2d %s %-4s %s(%s):%s > %s",
	       $month, $day, $time,
	       $P{"PROTO"},
	       &Lookup($P{"SRC"}), $P{"SRC"}, $P{"TYPE"},
	       $P{"DST"});
	print '</font>';
	print "\n";
    }	
}

&CacheWrite;

exit 0;

sub Lookup
{
    my($ip) = @_;
    my($host, $h);

    if ($DNScache{$ip}) {
	$host = $DNScache{$ip};
	if ($host eq "none") {
	    $host = "";
	}
    }
    else {
	if ($h = gethost($ip)) {
	    $host = $h->name;
	    $DNScache{$ip} = $host;
	}
	else {
	    $DNScache{$ip} = "none";
	    $host = "";
	}
    }

    return $host;
}

sub CacheRead
{
    local($_);

    if (open(IN, $CACHEFILE)) {
	while (<IN>) {
	    chomp;
	    split;
	    $DNScache{$_[0]} = $_[1];
	}
	close(IN);
    }
}

sub CacheWrite
{
    local($_);

    if (open(OUT, "> $CACHEFILE")) {
	foreach $_ (keys(%DNScache)) {
	    print OUT "$_ $DNScache{$_}\n";
	}
	close(OUT);
    }
}
