#! /bin/sh
# ipchains-packetlog-report --- pretty-print kernel ipchains syslog messages

# Copyright (C) 1999 Noah S. Friedman

# Author: Noah Friedman <friedman@splode.com>
# Created: 1999-12-29

# $Id: ipchains-packetlog-report,v 2.1 1999/12/29 19:58:01 friedman Exp $

# 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; either version 2, or (at your option)
# any later version.
#
# 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.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, you can either send email to this
# program's maintainer or write to: The Free Software Foundation,
# Inc.; 59 Temple Place, Suite 330; Boston, MA 02111-1307, USA.

# Commentary:
# Code:

exec ${PERL-perl} -x -S $0 ${1+"$@"}
#!perl

sub protobynumber ($)
{
  my $proto = getprotobynumber ($_[0]);
  return ($proto || $_[0]);
}

# Args: port (int), proto (string, e.g. "tcp" or "udp")
sub servbyport ($$)
{
  my $serv = getservbyport ($_[0], $_[1]);
  return ($serv || $_[0]);
}

sub hostbyaddr ($)
{
  use Socket;
  my $name = gethostbyaddr (inet_aton ($_[0]), AF_INET);
  return ($name || $_[0]);
}

sub getproto ($)
{
  my $proto = $_[0];
  $proto =~ s/^PROTO=//o;
  getprotobynumber ($proto);
}

sub main
{
  while (<>)
    {
      next unless (/kernel: Packet log:/o);
      chop;
      my @toks = split (/[ \t:]+/o, $_);

      # Discard "hostname kernel: Packet log:"
      splice (@toks, 5, 4);

      my @date    = splice (@toks, 0, 5);
      my $ipchain = shift @toks;
      my $action  = shift @toks;
      my $iface   = shift @toks;
      my $proto   = getproto      (shift @toks);
      my $srcaddr = hostbyaddr    (shift @toks);
      my $srcport = servbyport    (shift @toks, $proto);
      my $dstaddr = hostbyaddr    (shift @toks);
      my $dstport = servbyport    (shift @toks, $proto);
      my $packlen = shift @toks;
      my $tos     = shift @toks;
      my $ipid    = shift @toks;
      my $frag    = shift @toks;
      my $ttl     = shift @toks;
      my $synp    = ($toks[0] eq 'SYN' ? 1 : 0);

      printf ("%s %s %s:%s:%s %s %s %s PROTO=%s %s:%s %s:%s\n",
              @date, $ipchain, $action, $iface, $proto,
              $srcaddr, $srcport, $dstaddr, $dstport);
    }

  exit (0);
}

main;

# ipchains-packetlog-report ends here
