#!/usr/bin/perl

########################################################################
#
# UDP Server Front End
#
# This script is designed to run as an automatic service, and collect
# all UDP packets and send them an appropriately named file.
#
# Version 1.5 8 March 2002
# (c) Intersect Alliance Pty Ltd
#
# Released under the terms of the GNU Public Licence
#
########################################################################
# Modified by Fredy Schaller- Added signal handler to close files on
#                             termination, and fixed a '!=' vs 'ne' bug.
########################################################################

use IO::Socket;
use POSIX;
use constant MAXBYTES => scalar 64000;

# Set signal handler to terminate this server.
$SIG{INT}=\&myhandler;
$SIG{TERM}=\&myhandler;

# This call ensures that any writes to STDOUT or FILE are not buffered.
$|=1;

# Change this value only with EXTREME care. See below.
$ServerPort = "6161";

# Location for writing audit data.
$Location="/var/log/audit";

# Initiate the socket parameters. Local port is set to 6161 on UDP.
# This should only be changed with EXTREME care, since any change
# in port number or host, will require a change to all the clients.

$socket = IO::Socket::INET->new(LocalPort       => $ServerPort,
                                Type            => SOCK_DGRAM,
                                Proto           => 'udp')
        or die "Cannot open socket\n";

$openfile="";

while(1) {

        if ($socket->recv($datain, MAXBYTES))
        {
                $temp=$datain;
                ($host,$audittype)=split(/\t/,$datain);
                ($sec,$min,$hour,$mday,$mon,$year)=localtime(time);
                $year+=1900;
                $mon+=1;
                if($mon<10)  { $mon = "0" . $mon; }
                if($mday<10) { $mday = "0" . $mday; }
                $datetime=$year.$mon.$mday;

                $filename="$datetime.$host.$audittype";
                if($filename ne $openfile) {
                        close(OUTPUT);
                        if(!open(OUTPUT,">>$Location/$datetime-$host-$audittype")) {
                                print "Cannot open audit output file $Location/$datetime-$host-$audittype.\n";
                        }
                        $openfile=$filename;
                }
                print OUTPUT $datain . "\n";
        }
        else
        {
           print "Error condition from the UDP Server Front End \n";
        }
}

# The signal handler to terminate this server
sub myhandler{
        $socket->close();
        close(OUTPUT);
        print "auditserver.pl: terminated\n";
        exit 0;
}
