#!/usr/bin/perl

#########################################################################
# Racoon Ipsec VPN IKE daemon log tracer/ parser			           #
# Author: Pavel Mracek mrak(at)mrak(dot)cz                              #
# Version: 0.1                                                          #
#########################################################################
#
# 	Use:
#	 	tail -f -n 1800 /var/log/racoon|racoon_log_trace.pl 'search string'
#
#
#########################################################################
# This file may be distributed under the terms of the GNU General   #
# Public License.                           #
#########################################################################



##
## Pouziti: 
print "----------- Pozor: pri delsim behu zere prislis mnoho RAM ---------------'\n";
print "Use: tail -f -n 800 /var/log/racoon|$0 'search string'\n";
##
##
#        \033[0-8;30-37;40-47m
#	     efect,text,background
@colours= ( 
	"\033[31m",
	"\033[32m",
	"\033[33m",
	"\033[34m",
	"\033[35;47m",
	"\033[36;40m",
	"\033[37;40m",
	"\033[1;31m",
	"\033[1;32;1;40m",
	"\033[1;33;1;40m",
	"\033[1;34m",
	"\033[1;35m",
	"\033[1;36;40m",
	"\033[1;37;40m");
$ColourIndex=0;

$search=join(' ',@ARGV);

sub Parse{
  my ($line)=@_;
  my ($id)='';
  my ($next)='';
	# IPsec-SA expired: ESP/Tunnel 217.11.254.48[0]->80.188.188.71[0] spi=4281394874(0xff30e6ba)
	# IPsec-SA established: ESP/Tunnel 217.11.254.48[500]->80.188.188.71[500] spi=866640679(0x33a7e327) 
  if($line =~ /spi[=:]([\da-f]+)/){
        $id=$1;
  }
  return($id,$next);
}

sub GetColour{
    if( $ColourIndex>scalar(@colours)){
	$ColourIndex=0;
    }
    $ColourIndex++;
    return $colours[$ColourIndex-1];
}

while(defined($line = <STDIN>)){
  my ($spi,$NextId, $Print);
  ($spi, $NextId) = Parse($line);
  if(!$spi){ next;}
  # print "SPI: $spi \t\tnext: $NextId \n";

  if($NextId){
	$KnownId{$spi}{'line'} .= $KnownId{$NextId}{'line'} if(exists($KnownId{$NextId}{'line'}));	#keep prev. lines
	$KnownId{$NextId}=$KnownId{$spi};
  }
  if(exists($KnownId{$spi})){
	$KnownId{$spi}{'line'} .= $line;
  }else{
	$KnownId{$spi}{'line'} = $line;
  }
  if(KeySearch($line)){ 
	$KnownId{$spi}{'printable'} = 1;
	if(!exists($KnownId{$spi}{'colour'})){
		$KnownId{$spi}{'colour'} = GetColour();
	}
  }
  if($KnownId{$spi}{'printable'}){
	chomp($KnownId{$spi}{'line'});
	print $KnownId{$spi}{'colour'}.$KnownId{$spi}{'line'}."\033[0m\n";
	$KnownId{$spi}{'line'}='';
  }
}

sub KeySearch($){
  if($line =~ /$search/){
	return 1;
  }
  return 0;
}


1;
