#!/usr/bin/perl

# Copyright (C) 2000, Jean-Sebastien Morisset <jsmoriss@jsm-mv.dyndns.org>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation <http://www.gnu.org/copyleft/gpl.txt>.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

# fwhits - analyse hits on ipchains rules.
#
# Start a new log file and run rc.firewall in debug mode. After gathering
# a good sample, run fwhits on this log file. The report will show which 
# rules were hit most often. For best performance, these rules should be 
# top-most.

use Socket;

%HOSTS={};

$intlen=6;
$numlen=4;
$barlen=130 - $intlen - $numlen - 3;

open(LOG, "< $ARGV[0]") || die "Unable to open log file for reading!";
while(<LOG>) {
	$i++;
	$fields = split(/[ \t\n]+/, $_);
	$rulenum = $_[$fields -1];
	next if ($rulenum !~ /^\(#[0-9]+\)$/ || $_[6] ne "log:");
	$rulenum =~ s/[\(\)#]//g;
	$rulenum = sprintf("%03s", $rulenum);
	$interface = $_[7];
	$interface = "fwd" if ($interface eq "forward");

	$key = "$interface $rulenum";
	$SCAN{$key}++;
	$max = $SCAN{$key} if ($max < $SCAN{$key});
}
close(LOG);

$ratio = $max/$barlen;

printf("\n%-${intlen}s %-${numlen}s %-s\n", "Chain", "Rule", "Hits");
printf("%s %s %s\n", "-" x $intlen, "-" x $numlen, "-" x $barlen);

foreach $key (sort keys(%SCAN)){
	($interface, $rulenum)=split(' ', $key);
	print "\n" if ($interface ne $lastint);
	$lastint = $interface;
	$bars = $SCAN{$key}/$ratio;

	printf("%${intlen}s %-${numlen}s ", $interface, $rulenum);
	$bars = $bars - length($SCAN{$key});
	print "*" x $bars;
	print $SCAN{$key}, "\n";
}
print "\n";

