#!/usr/bin/perl -w

#
# LARD - based on code from syslog-snarf.pl - by
#
# The author disclaims all copyrights and releases this document into
# the public domain.
#
# Lard is a syslogd-like loggin daemon that can rotate logfiles,
# trigger commands on specific messages and perform regex matching.
#
# see `man lard` and `man lard.conf` for more information, or
# issue `lard -h`.
#

use strict;

use Socket;
use IO::Socket;
use IO::Select;

use Sys::Hostname;

use Getopt::Std;
use Date::Parse;
use POSIX qw(strftime setsid);

use vars qw(@rules %option %opts %sockets $mark_timeout %kmsg_buffer);

# define some globals
my $VERSION = "0.1.9";
my $stampfile = "/var/state/lard";
my $id = $0;
$id =~ s/.*\///;
my $pidfile = "/var/run/$id.pid";
my $pid;

# to match PRI header plus remaining fields
my $PRI_data_re = qr/^ < (\d{1,3}) > (.*) /x;

# to decode remaining data past the priority into TIMESTAMP, HOSTNAME,
# and MSG fields
my $HEADER_MSG_re_syslog_ng = qr/^ ((	# match HEADER, TIMESTAMP for reference
	(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)	# Month
	(?:[ ][ ]\d|[ ]\d\d) # day of month, '	5' or ' 10'
	[ ] \d\d:\d\d:\d\d)  # timestamp
	[ ] ([\w@.:-]+)      # HOSTNAME host|IPv4|IPv6 (syslog-ng prefixes foo@?)
	)                    # close match on HEADER
	[ ] (.*)             # MSG data
/x;
my $HEADER_MSG_re_solaris = qr/^ ((
	(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)	# Month
	(?:[ ][ ]\d|[ ]\d\d) # day of month, '	5' or ' 10'
	[ ] \d\d:\d\d:\d\d)  # timestamp
	)                    # close match on HEADER
	[ ] (.*)             # MSG data
/x;

# see strftime man page for allowed fields here
my $timestamp_template = "%b %e %H:%M:%S";

# this is a custom template based on contents of %message hash for each
# log entry
my $message_template = '%{TIMESTAMP} %{HOSTNAME} %{MSG}\n';

# syslog.h code->name mappings for better output
my %syslog_priorities = (
	0 => 'emerg',
	1 => 'alert',
	2 => 'crit',
	3 => 'err',
	4 => 'warn',
	5 => 'notice',
	6 => 'info',
	7 => 'debug'
);
my $pri_mask_full = ((2<<8) - 2);

# TODO some vendors (notably Apple) have fiddled with these to add
# NETINFO and similar... support this by reading these defintions
# from a file?
my %syslog_facilities = (
	0  => 'kern',
	1  => 'user',
	2  => 'mail',
	3  => 'daemon',
	4  => 'auth',
	5  => 'syslog',
	6  => 'lpr',
	7  => 'news',
	8  => 'uucp',
	9  => 'cron',
	10 => 'authpriv',
	11 => 'ftp',
	16 => 'local0',
	17 => 'local1',
	18 => 'local2',
	19 => 'local3',
	20 => 'local4',
	21 => 'local5',
	22 => 'local6',
	23 => 'local7'
);
my $fac_mask_full = ((2<<24) - 2);

# generate reverse hashes for speedy lookups
my %syslog_facilities_rv;
my %syslog_priorities_rv;
for my $key (keys %syslog_facilities) {
	$syslog_facilities_rv{$syslog_facilities{$key}} = $key;
}
for my $key (keys %syslog_priorities) {
	$syslog_priorities_rv{$syslog_priorities{$key}} = $key;
}

# some global base-level functions
sub debug {
	my $msg = shift;
	if ( $opts{'d'} ) {
		print STDERR $msg;
	}
}


# set the mark timeout to a decent default (20 mintes):
$option{'mark'} = 1200;

# parse command-line options
getopts 'dfhKnrs:v', \%opts;

print_help() if exists $opts{'h'};

print "$VERSION\n" and exit if exists $opts{'v'};

if ( exists $opts{'d'} ) {
	$opts{'n'} = 1;
}

&parse_config();

# start up the syslog server
local *PID;
if (exists $opts{'s'}) {
	# send a rotate signal and quit
	open (PID, "$pidfile") or die "error: could not find pid";
	my $daemon;
	$daemon = (<PID>);
	close (PID);
	debug "Attempting to send signal 10 to PID $daemon\n";
	kill (10, $daemon) or die "error: could not send signal USR1 to process $daemon";
	exit 0;
}

$| = 1;												# autoflush output

my $select = IO::Select->new();
&get_inputs;

# fork into the background unless we don't want that
if ($opts{'n'}) {
	&write_pid($$);
} else {
	if ($pid = fork) {
		# write the proper PID:
		&write_pid($pid);
		# and exit after!
		exit;
  	} else {
		# disown stdin/stdout so errors don't end up on the terminal
		open STDIN, '/dev/null' or die "Can't read /dev/null: $!";
		open STDOUT, '>/dev/null' or die "Can't write to /dev/null: $!";
		open STDERR, '>&STDOUT' or die "Can't dup stdout: $!";
		setsid or die "Can't start a new session: $!";
	}
}

# now we know for sure:
$id .= "\[$$\]";

# send out a syslog.notice that we have just started
debug "$id: Started, version $VERSION\n";
send_local ('notice', "$id: Started, version $VERSION");

# and add the signal hook:
$SIG{'USR1'} = \&catch_rotate_signal;
$SIG{'TERM'} = \&end;
$SIG{'INT'} = \&end;
$SIG{'HUP'} = \&reload;
$SIG{'ALRM'} = \&mark;
# ignore CHLD exiting to kill off zombies
$SIG{'CHLD'} = 'IGNORE';

# start mark-ing timer
alarm $option{'mark'};

# main program loop
while(1) {
	debug "Entering main program loop\n";
	# handle messages as usual
	while (my @ready = $select->can_read) {
		foreach my $sock (@ready) {
			read_message_from_socket ($sock);
		}
	}
}


# add signal handler to trigger rotation
sub catch_rotate_signal {
	debug "Received rotation request signal (USR1)\n";
	send_local ('notice', "$id: Received rotation request signal (USR1)");
	rotate_all();
}


sub write_pid {
	my $p = shift;
	# normal daemon startup
	if (-e "$pidfile") {
		die "error: another instance of $id is running";
	}
	open (PID, ">$pidfile") or die "error: could not open \"$pidfile\" for writing";
	print PID $p . "\n";
	close (PID);
}


sub reload {
	debug "Received restart request signal (HUP)\n";
	send_local ('notice', "$id: Received restart request signal (HUP)");
	&close_handles;
	undef @rules;
	&parse_config;
	&get_inputs;
}


sub end {
	# send out a syslog.notice that we are exiting, but only for
	debug "$id: Shutting down\n";
	($pid) or send_local ( 'notice', "$id: Shutting down");
	unlink ("$pidfile") if not exists $opts{'s'};
	&close_handles;
	exit 0;
}


sub mark {
	&write_raw_message('kern', 'info', '-- MARK --' );
	alarm $option{'mark'};
}


END {
	if ((-e $pidfile) && (! $pid)) {
		unlink ("$pidfile") if not exists $opts{'s'};
	}
}


sub get_inputs {
	my $handle;
	if ($opts{'r'}) {
		$handle = &get_remote_socket;
		$select->add($handle);
		$sockets{fileno($handle)} = 'remote';
		debug "Added remote reception socket\n";
	}

	$handle = &get_local_socket;
	$select->add($handle);
	$sockets{fileno($handle)} = 'local';
	debug "Added local reception socket\n";

	if ((-f '/proc/kmsg') && (! $opts{'K'})) {
		$handle = &get_kmsg_socket;
		$select->add($handle);
		$sockets{fileno($handle)} = 'kmsg';
		debug "Added kernel message socket\n";
	}
}


sub close_handles {
	close $_ foreach $select->handles;
	debug "Closed all sockets\n";
	$select->remove ( $select->handles );
	undef %sockets;
}


sub get_remote_socket {
	# check for remote reception listen address
	my $sock;
	my @bind;
	my $port = 514;
	if ($option{'listen'}) {
		(@bind) = ('LocalAddr', (split(/:/, $option{'listen'}))[0]);
		for ($option{'listen'}) {
			/:/ && do {
				$port = ((split(/:/, $option{'listen'}))[1])
			};
		}
	}

	$sock = IO::Socket::INET->new(
		Proto     => 'udp',
		LocalPort => $port,
		@bind
	  )
	  or die "error: could not start server: errno=$@\n";
	return $sock;
}


sub get_local_socket() {
	# listen on socket
	my $sock;
	my $socketfile;
	if ($option{'socket'}) {
		debug "Using special socket " . $option{'socket'} . "\n";
		$socketfile = $option{'socket'};
	} else {
		$socketfile = '/dev/log';
	}
	if (-e $socketfile) {
		unlink $socketfile or die "error: cannot get socket \"$socketfile\"";
	}
	$sock = IO::Socket::UNIX->new(
		Local   => "$socketfile",
		Type    => SOCK_DGRAM,
		Listen  => 0
	 )
	 or die "error: could not start server: errno=$@\n";
	chmod 0666, "$socketfile";
	return $sock
}


sub get_kmsg_socket() {
	# listen on /proc/kmsg
	my $handle;
	my $socketfile = '/proc/kmsg';
	if (! -e $socketfile) {
		die "error: cannot get socket \"$socketfile\"";
	}
	open ($handle, $socketfile ) or die "error: cannot open \"/proc/kmsg\"";
	return $handle;
}


sub send_local {
	# send a message to ourselves locally, so it can be parsed and passed
	# through our ruleset
	write_raw_message ('syslog', shift, shift);
}


sub write_raw_message {
	my $fac = shift;
	my $pri = shift;
	my $fac_code = $syslog_facilities_rv{$fac};
	my $pri_code = $syslog_priorities_rv{$pri};
	my $pri_tuple = $fac_code * 8 + $pri_code;
	debug "write_raw_message: $fac, $pri\n";
	write_message({
	    'PRI' => "$pri_tuple",
		'facility' => $fac,
		'facility_code' => $fac_code,
		'priority' => $pri,
		'priority_code' => $pri_code,
		'MSG' => shift,
		'TIME' => time,
		'HOSTNAME' => hostname()
	  });
}


sub send_remote {
	# send a message to a specific loghost
	my $host = shift;
	my $port = 514;
	my %message = %{ shift() };
	debug "Sending message to remote host \"$host\": ". $message{'MSG'} . "\n";
	$host = (split(/:/, $host))[0];
	for ($host) {
		/:/ && do {
			$port = (split(/:/, $host))[1];
		};
	}
	local *SOCKET;
	socket(SOCKET, PF_INET, SOCK_DGRAM, getprotobyname("udp")) or die "socket: $!";
	send(SOCKET, "<" . $message{'PRI'} . ">" . $message{'MSG'} . "\n", 0, sockaddr_in($port, inet_aton($host)));
}


sub unquote {
	# remove "" quotes from a string
	my $word = shift;
	$word =~ s/^"(.*)"$/$1/;
	return $word;
}


sub format_message {
	my $template = shift;
	my %message = %{ shift() };
	
	# converts '\n' and similar to actual character
	( my $output = $template ) =~ s/(\\.)/qq!"$1"!/eeg;

	# replaces %{foo} keys from %message hash with values for log entry
	$output =~ s/%{(\w+)}/$message{$1}||''/eg;
	return $output;
}


sub parse_config {
	my @words;

	# read and parse rules from the config file
	local *CONF;
	my $conf = "/etc/lard.conf";
	$conf = $opts{'f'} if exists $opts{'f'};
	debug "Processing config file \"$conf\"\n";
	open(CONF, "$conf") or die "error: cannot open configuration file \"$opts{'f'}\"";
	while (<CONF>) {
		s/#.*$//g;
		for (m/(\x22[^\x22]+\x22|\x27[^\x27]+\x27|\x60[^\x60]+\x60|[0-9a-zA-Z\x21\x23-\x26\x2a-\x3a\x3c-\x7a\x7c\x7e\x7f]+|\x28|\x29|\x7b|\x7d|\x3b)/g) {
			push @words, $_;
		}
	}
	close (CONF);

	my %rule;
	my @filters;
	my @matches;
	undef %rule;
	undef @filters;
	undef @matches;
	# while ($word = shift @words) {
	while ( local $_ = shift @words ) {
		/^(?:file|pipe|command|host)$/ && do {
			/^pipe$/ && do {
				die "error: \"pipe\" rule not implemented yet";
			};
			if (%rule) {
				debug "Finished rule.\n";
				# store last rule if it exists
				if ( @filters ) { $rule{'filter'} = [ @filters ]; };
				if ( @matches ) { $rule{'match'} = [ @matches ]; };
				push @rules, {%rule};
				undef %rule;
				undef @filters;
				undef @matches;
			}
			# create a new rule
			debug "Started new $_ rule: \"$words[0]\"\n";
			$rule{$_} = unquote ( shift @words );
			next;
		};
		debug "  Processing keyword: $_\n";
		/^(?:mark|socket|domain|listen|log|timeformat|format|keep|rotate|compress|filter|match|post)$/ && do {
			if (! %rule) {
				/^(?:filter|match|log|post)$/ && do {
					die "error: \"$_\" keyword may only be used in rules";
				};
				debug "Changing global value for $_: \"" . $words[0] . "\"\n";
				$option{$_} = unquote ( shift @words );
			} else {
				/^(?:socket|listen|mark)$/ && do {
					die "error: \"$_\" keyword may not be used in rules";
				};
				# filter/match criteria
				/^filter$/ && do {
					my $f = unquote ( shift @words ) ;
					debug "    adding $_ : \"$f\"\n";
					push @filters, $f ;
					next;
				};
				/^match$/ && do {
					my $f = unquote ( shift @words ) ;
					debug "    adding $_ : \"$f\"\n";
					push @matches, $f ;
					next;
				};
				debug "    adding $_: \"$words[0]\"\n";
				$rule{$_} = unquote ( shift @words );
				# create binary mask for facility.priority
				/^log$/ && do {
					# set the default mask to full
					my ( $fac, $pri ) = split ( /\./, $rule{$_} );
					# facility
					if ( $fac eq '*' ) {
						$rule{'fac_mask'} = $fac_mask_full;
					} else {
						for my $fac_item ( split ( /\,/, $fac ) ) {
							# if negated, deduct the prio from the mask
							if ( substr($fac_item, 0, 1) eq '!' ) {
								if (! $rule{'fac_mask'}) {
									$rule{'fac_mask'} = $fac_mask_full;
								}
								if (exists $syslog_facilities_rv{substr($fac_item, 1)}) {
									$rule{'fac_mask'} &= ( $fac_mask_full - ( 2<<$syslog_facilities_rv{substr($fac_item, 1)} ) );
								} else {
									die "error: illegal facility name \"$fac_item\"";
								}
							} else {
								# else add it to it
								if (exists $syslog_facilities_rv{$fac_item}) {
									$rule{'fac_mask'} |= ( 2<<$syslog_facilities_rv{$fac_item} );
								} else {
									die "error: illegal facility name \"$fac_item\"";
								}
							}
						}
					}
					# priority
					if ( $pri eq '*' ) {
						$rule{'pri_mask'} = $pri_mask_full;
					} else {
						for my $pri_item ( split ( /,/, $pri ) ) {
							# if negated, deduct the prio from the mask
							if ( substr($pri_item, 0, 1) eq '!' ) {
								if (! $rule{'pri_mask'} ) {
									$rule{'pri_mask'} = $pri_mask_full;
								}
								if (exists $syslog_priorities_rv{substr($pri_item, 1)}) {
									$rule{'pri_mask'} &= ( $pri_mask_full - ( 2<<$syslog_priorities_rv{substr($pri_item, 1)} ) );
								} else {
									die "error: illegal priority name \"$pri_item\"";
								}
							} else {
								# else add it to it
								if (exists $syslog_priorities_rv{$pri_item}) {
									$rule{'pri_mask'} |= ( 2<<$syslog_priorities_rv{$pri_item} );
								} else {
									die "error: illegal priority name \"$pri_item\"";
								}
							}
						}
					}
				}
			}
			next;
		}
	}

	# add the last rule in case it's there
	if (%rule) {
		debug "Finished rule.\n";
		if ( @filters ) { $rule{'filter'} = [ @filters ]; };
		if ( @matches ) { $rule{'match'} = [ @matches ]; };
		push @rules, {%rule};
	}
	debug "Finished processing config file.\n";
}


sub get_timestamp {
	my $file = shift;
	local *STAMP;
	if (open (STAMP, $stampfile)) {
		while (<STAMP>) {
			/^$file .*$/ && do {
				$_ =~ s/$file //;
				chomp;
				close (STAMP);
				return $_;
			};
		}	
		close (STAMP);
		# fallback: record the time for a file missing a timestamp:
		write_timestamp($file);
		return time;
	} else {
		write_timestamp($file);
		return time;
	}
}


sub write_timestamp {
	my $file = shift;
	debug "Setting timestamp for \"$file\"\n";
	my @lines;
	local *STAMP;
	if (open (STAMP, "$stampfile")) {
		while (<STAMP>) {
			/^$file .*$/ || do {
				push @lines, $_;
			};
		}
		close (STAMP);
		open (STAMP, ">$stampfile");
		for my $line (@lines) {
			print STAMP "$line";
		}
		print STAMP "$file" . " " . time . "\n";
		close (STAMP);
	} else {
		open (STAMP, ">$stampfile") or die "error: cannot create timestamp file \"$stampfile\"";
		print STAMP "$file" . " " . time . "\n";
		close (STAMP);
	}
}


sub rotate_all {
	# check to see if we can rotate logfiles now
	my ($keep, $rotate, $compress, $post);
	my @posts = ();
	for my $rule (@rules) {
		if ((${$rule}{'file'}) && (-f ${$rule}{'file'}) && (${$rule}{'file'} ne "=")) {
			# it's a logfile rule -> recover the rotation params
			if (${$rule}{'keep'}) {
				$keep = ${$rule}{'keep'};
			} elsif ($option{'keep'}) {
				$keep = $option{'keep'};
			} else {
				$keep = 4;
			}
			if (${$rule}{'rotate'}) {
				$rotate = ${$rule}{'rotate'};
			} elsif ($option{'rotate'}) {
				$rotate = $option{'rotate'};
			} else {
				$rotate = "weekly";
			}
			if (${$rule}{'compress'}) {
				$compress = ${$rule}{'compress'};
			} elsif ($option{'compress'}) {
				$compress = $option{'compress'};
			} else {
				$compress = "none";
			}
			if (${$rule}{'post'}) {
				$post = ${$rule}{'post'};
			} else {
				$post = "";
			}

			my $ctime = get_timestamp(${$rule}{'file'});
			for ($rotate) {
				/^(?:hourly|daily|weekly|monthly)$/ && do {
					if (
							(($rotate eq "hourly") && ($ctime < (time - 3600))) ||
							(($rotate eq "daily") && ($ctime < (time - 80640))) ||
							(($rotate eq "weekly") && ($ctime < (time - 564480))) ||
							(($rotate eq "monthly") && ($ctime < (time - 2452262))) ) {
						rotate_file (${$rule}{'file'}, $keep, $compress);
						if (( $post ne "" ) && ( ! grep( /^$post\$/, @posts) )) {
							push @posts, $post;
						}
						write_timestamp(${$rule}{'file'});
					}
					next;
				};
				/^(?:\d+[KMG]|\d+)$/ && do {
					$rotate =~ s/K$/000/;
					$rotate =~ s/M$/000000/;
					$rotate =~ s/G$/000000000/;
					if (((stat(${$rule}{'file'}))[7]) >= $rotate) {
						rotate_file (${$rule}{'file'}, $keep, $compress);
						if (( $post ne "" ) && ( ! grep( /^$post\$/, @posts) )) {
							push @posts, $post;
						}
					}
					next;
				};
			}
		}
	}
	# run all 'post' commands
	foreach $post (@posts) {
		if (( $post ne "" ) && (fork == 0)) {
			exec("$post");
		}
	}
}


sub rotate_file {
	# takes a filename as argument #1
	# numer of rotations as #2
	# compression method as #3
	my $file = shift;
	my $keep = shift;
	my $compress = shift;
	
	debug "Rotating \"$file\": ($keep, $compress)\n";
	send_local ('debug', "$id: Rotating $file");

	my $suffix;
	if ($compress eq "bzip2") {
		$suffix = ".bz2";
	} elsif ($compress eq "gzip") {
		$suffix = ".gz";
	} else {
		$suffix = "";
	}

	for ( my $num = $keep; $num > 0 ; $num-- ) {
		# move old files up
		if ( -f "$file." . $num . "$suffix" ) {
			if ($num == $keep) {
				# delete the oldest if it's the last one to keep
				debug "Removing \"$file.$num.$suffix\"\n";
				unlink "$file." . $num . "$suffix";
			} else {
				# move them up
				debug "Moving \"$file.$num.$suffix\" to \"$file." . ($num+1) . ".$suffix\"\n";
				rename "$file." . $num . "$suffix", "$file." . ($num+1) . "$suffix";
			}
		}
	}
	# now move the current one
	if ( -f "$file" ) {
		if ($keep == 0) {
			debug "Removing \"$file\"\n";
			unlink ("$file");
		} else {
			debug "Moving \"$file\" to \"$file.1\"\n";
			rename "$file", "$file.1";
		}
		# and compress it
		if (( $compress ne "none" ) && (fork == 0)) {
			debug "Executing \"$compress $file.1\"\n";
			exec("$compress $file.1");
		}
	}
}


# this is the incoming message handler
sub read_message_from_socket {
	my $sock = shift;
	my %message = ();

	my $max_msg_len	= 5000;
	if ($sockets{fileno($sock)} eq 'remote' ) {
		debug "Received a new message from remote socket\n";
		# use the recv() method for INET sockets:
		$sock->recv($message{'raw'}, $max_msg_len);
		$message{'peerhost'} = gethostbyaddr($sock->peeraddr, AF_INET)
		  || $sock->peerhost;
		$message{'peerport'} = $sock->peerport;
	} else {
		debug "Received a new message from local socket\n";
		# max message length for incoming data ([RFC 3164] limits this to 1024
		# by default, though things might not follow the standards)
		sysread($sock, $message{'raw'}, $max_msg_len) or die "error: cannot read from socket";
		$message{'peerhost'} = hostname();
	}

	if ($sockets{fileno($sock)} eq 'kmsg' ) {
		# append message to what's in buffer
		if (defined(%kmsg_buffer)) {
			debug "  appended message to kmsg buffer";
			$message{'raw'} = $kmsg_buffer{'raw'} . $message{'raw'};
		}

		# if message is \n terminated, clear buffer and print
		if ($message{'raw'} =~ m/\n$/) {
			undef(%kmsg_buffer);
		# else, clear message and hold buffer, don't print
		} else {
			debug "  unterminated kmsg, buffering";
			return;
		}
	}

	# tag with the current time:
	$message{'time_recv'} = time;
	
	# see [RFC 3164] for syslog message format details
	$message{'length'} = length( $message{'raw'} );

	if ( $message{'length'} == 0 ) {
		debug "message was empty, discarded\n";
		next;
	}

	my $header_msg = '';

	if (!( $message{'raw'} =~ m/$PRI_data_re/o )) {
		debug "  inserting default priority/facility\n";
		$message{'PRI'} = "<7>";
		$header_msg = $message{'raw'};
	} else {
		( $message{'PRI'}, $header_msg ) = ( $1, $2 );
	}

	# decode facility/priority (see [RFC 2234] for PRI part values
	$message{'priority_code'} = $message{'PRI'} % 8;
	if ( exists $syslog_priorities{ $message{'priority_code'} } ) {
		$message{'priority'} = $message{'priority_code'};
		$message{'priority'} = $syslog_priorities{ $message{'priority_code'} };
	}
	$message{'facility_code'} = int( $message{'PRI'} / 8 );
	if ( exists $syslog_facilities{ $message{'facility_code'} } ) {
		$message{'facility'} = $syslog_facilities{ $message{'facility_code'} };
	}

	# TODO is syslog-ng adding \n to the data already?
	chomp $header_msg;
	if ( $header_msg =~ m/$HEADER_MSG_re_solaris/o ) {
		debug "  looks like a generic syslog message\n";
		(
		 $message{'HEADER'},	 $message{'TIME'},
		 $message{'HOSTNAME'}, $message{'MSG'}
		)
		 = ( $1, str2time ($2), $message{'peerhost'}, $3 );
		# solaris' syslogd passes the fac.pri tuple, get rid if it:
		$message{'MSG'} =~ s/ $message{'facility'}\.$message{'priority'}// ;
	} elsif ( $header_msg =~ m/$HEADER_MSG_re_syslog_ng/o ) {
		debug "  looks like a syslog-ng message\n";
		(
			$message{'HEADER'},	 $message{'TIME'},
			$message{'HOSTNAME'}, $message{'MSG'}
		)
		 = ( $1, str2time ($2), $3, $4 );
	} else {
		debug "  looks like a headerless syslog message\n";
		(
		 $message{'HEADER'},	 $message{'TIME'},
		 $message{'HOSTNAME'}, $message{'MSG'}
		)
		 = ( '', time , $message{'peerhost'}, $header_msg );
	}

	write_message(\%message);
}


sub match {
	# apply match rules to $output
	my $output = shift();
	my %rule = %{ shift() };
	# always match when no match rule is present
	if ( ! defined $rule{'match'} ) {
		return 1;
	};
	my @matches = @{ $rule{'match'} } ;
	# return true on first match
	foreach my $match ( @matches ) {
		for ( $output ) {
			m/$match/ && do {
				debug "    Applied match $match\n";
				return 1;
			}
		}
	}
	# return false if nothing matched.
	return 0;
}


sub filter {
	# apply filter rules to $output: true == passes filters
	my $output = shift();
	my %rule = %{ shift() };
	# always filter when no filter rule is present
	if ( ! defined $rule{'filter'} ) {
		return 1;
	};
	my @filters = @{ $rule{'filter'} } ;
	# return true on first filter
	foreach my $filter ( @filters ) {
		for ( $output ) {
			m/$filter/ && do {
				debug "    Applied filter $filter\n";
				return 0;
			}
		}
	}
	# return true if no filter matches
	return 1;

}


sub write_message {
	# delay -- MARK -- messages
	alarm $option{'mark'};
	# write a message hash to the appropriate logfiles
	my %message = %{ shift() };

	debug "    hostname: \"$message{'HOSTNAME'}\"\n";
	debug "    timestamp: \"$message{'TIME'}\"\n";
	debug "    priority: \"$message{'priority_code'}\"\n";
	debug "    facility: \"$message{'facility_code'}\"\n";
	debug "    content: \"$message{'MSG'}\"\n";

	# here we traverse our logging rules and apply the proper procedure
	# (multiple actions possible)
	for my $rule (@rules) {
		# do not attempt to match rules that are for rotation-only files:
		(${$rule}{'log'}) or next;
		# perform a match on $message{'facility|priority'}
		if ( ( ${$rule}{'pri_mask'} & ( 2<<$message{'priority_code'}) ) &&
				( ${$rule}{'fac_mask'} & ( 2<<$message{'facility_code'}) ) ) {
			# strip the hostname down if requested:
			if (${$rule}{'domain'}) {
				$message{'HOSTNAME'} =~ s/\.${$rule}{'domain'}//;
			} elsif (exists $option{'domain'}) {
				$message{'HOSTNAME'} =~ s/\.$option{'domain'}//;
			}
			# create the output format message now
			my $output;
			# figure out what timestamp format we need
			if ( defined ${$rule}{'timeformat'} ) {
				$message{'TIMESTAMP'} = strftime ${$rule}{'timeformat'}, localtime ($message{'TIME'});
			} elsif ( defined $option{'timeformat'} ) {
				$message{'TIMESTAMP'} = strftime $option{'timeformat'}, localtime ($message{'TIME'});
			} else {
				$message{'TIMESTAMP'} = strftime $timestamp_template, localtime ($message{'TIME'});
			}
			if ( defined ${$rule}{'format'} ) {
				$output = format_message ( ${$rule}{'format'}, \%message );
			} elsif ( defined $option{'format'} ) {
				$output = format_message ( $option{'format'}, \%message );
			} else {
				$output = format_message ( $message_template, \%message );
			}
			# complex match so we can match hostname/time too:
			for ($output) {
				# seach for a pattern if applicable
				if ( match( $output, $rule ) && filter( $output, $rule) ) {
					if (defined ${$rule}{'file'}) {
						# append the message to this file
						if ( ${$rule}{'file'} eq "-" ) {
							print $output;
						} else {
							debug "    write to \"" . ${$rule}{'file'} . "\"\n";
							# very bad writing below
							local *LOG;
							open ( LOG, ">>${$rule}{'file'}" ) or die "error: cannot open \"${$rule}{'file'}\" for writing";
							print LOG $output;
							close ( LOG );
						}
					} elsif (defined ${$rule}{'pipe'}) {
						# write to a pipe

					} elsif (defined ${$rule}{'command'}) {
						# execute a command
						chomp $output;
						debug "    executing \"${$rule}{'command'} \'$output\'\n";
						send_local ('debug', "$id: executing command: \"${$rule}{'command'} \'$output\'\"");
						if (fork == 0) {
							# $SIG{CHLD} = 'IGN' || waitpid(-1, WNOHANG)
							exec("${$rule}{'command'} \'$output\'");
						}
					} elsif (defined ${$rule}{'host'}) {
						# log to a remote host
						send_remote ( ${$rule}{'host'}, \%message );
					}
				}
			}
		}
	}
}


sub print_help {
	# a generic help blarb
	print <<HELP;
Usage: $id [opts]

Logging and rotation daemon 

Options for lard:
    -h/-?    Display this message

    -r       Enable remote reception of syslog messages
    -K       Do not receive kernel messages from /proc/kmsg unders
             linux (on by default if /proc/kmsg exists)
    -n       Do not daemonize: stay in the foreground
    -d       Debug mode, print out lots of info. Implies -n.
    -s       Send a running lard daemon a rotate signal. If no
             running instance is found, rotate files and exit
    -f conf  Specify an alternative configuration file

See lard(8) and lard.conf(5) for additional documentation

HELP
	exit 100;
}

=head1 NAME

LARD - Log and Rotate Daemon

=head1 SYNOPSIS

Run this daemon like you would any other. The daemon automatically
forks into the background after parsing the config file:

    # lard

Make sure there isn't a process already occupying the /dev/log
socket or the UDP port in case you listen to remote messages:

    # lard -r

=head1 DESCRIPTION

lard is a replacement for syslogd, klogd and logrotate in one. It makes 
a lot of sense to combine the ability of these two programs together
since the daemon can rotate the logfiles independently of write
access to logfiles because it knows best when it's writing to them.

lard has also better pattern matching and can match regular expressions
on the message part of log messages, next to the traditional facility
and priority matching.

The output formats of the messages is custom, and a lot of fields
can be chosen to display the type of message, header details and
date/time formats. Per logfile/command these options can be adjusted.

Rotation can be done based on time or size. Time rotation data
is kept in a separate file and thus on the first run may not be accurate.
Post-rotate commands can be passed and are started after all files have
been rotated. Lard filters out any duplicate post-rotate commands.

Rotation is not automatically triggered. However, you must signal
a running lard instance that it is time to rotate the logfiles it
keeps track of. The signal for this is SIGURS1. You can also
call lard with the -s option to do this automatically, without
the need to lookup the PID (which is kept by default in
/var/run/lard.pid).

The daemon can run in the foreground and dump selected messages
to stdout if you create a 'log "-"' rule, where "-" is the alias
used for STDOUT. Any message matching the criteria will be
printed on stdout.

A message matching special criteria can also be passed directly to
a shell command. This can be usefull to send alerts directly, without
waiting for auditing tools to find them later. Beware that using
input from messages in scripts run as root could be a security
risk.

Remote reception and delivery is supported with a 'host "hostname"'
rule. Use the '-r' option to enable the UDP socket for incoming
syslog messages. Alternatively, you can provide a 'listen' address
to change the default (which is ALL available addresses) address
and port.

=head2 Normal Usage

	# lard [options]

See L<"OPTIONS"> for details on the command line switches supported.

=head1 OPTIONS

lard currently supports the following command line switches:

=over 4

=item B<-h>, B<-?>

Prints a brief usage note.

=item B<-r>

Enable remote reception. The daemon will open a UDP socket and listen
on port 514 by default.

=item B<-K>

The linux kernel logs kernel messages to the file /proc/kmsg. Lard
by default will monitor the file for incoming messages and process
these just like normal syslog messages. You can disable this feature
with this option, in case you do not want kernel messages to be logged
or if you are running some other logging tool for kernel messages.

=item B<-f> I<filename>

Open a different configuration file instead of the default, which is
/etc/lard.conf.

=item B<-n>

Do not daemonize. The daemon doesn't run in the background. Usefull
with the stdout logging possibility.

=item B<-d>

Display debug output. This implies -n, lard will not fork into the
background.

=item B<-s>

Send a rotate trigger to a running lard daemon. The lard daemon will
check if any file needs to be rotated according to the criteria in
the lard.conf file, and rotate the logfiles appropriate. The client
lard process will exit immediately. Alternatively, you can also
directly send a SIGUSR1 to the running lard daemon directly.

=back

=head1 SIGNALS

Lard can receive a few signals that influence it's behavour next to the
obvious B<TERM> and B<INT> signal:

=over 8

=item B<SIGHUP>

Sending lard a B<SIGHUP> signal will cause lard to close all listening
sockets, re-read the configuration file and re-initiate the sockets.
This allows you to change configuration parameters on the fly without
restarting lard.

=item B<SIGUSR1>

Sending lard a B<SIGUSR1> causes lard to check all logfiles to see
if they need to be rotated. Lard will temporarily suspend the logging
of incoming messages and thus can safely move/rename the logfiles and
optionall compress them. You can send this rotate signal also by issueing
a `lard -s`, which will do this for you. This command can be run
from a crontab for instance, especialy when you want to do some processing
of your logfiles before archiving them.

=back

=head1 BUGS

=head2 Reporting Bugs

See http://lard.foo-projects.org/ for contact information.

=head2 Known Issues

None at this moment.

=head1 SEE ALSO

lard(8), lard.conf(5), [RFC 3164]

=head1 AUTHOR

lard was written by Auke Kok, http://lard.foo-projects.org/

=head1 COPYRIGHT

The author disclaims all copyrights and releases this document into the
public domain.

=head1 HISTORY

Adapted from udp_echo_serv.pl by Lincoln D. Stein in the text
http://www.modperl.com/perl_networking/ (Chapter 18), plus data from
the Net::Syslog module as well as information in the sys/syslog.h
header file.

Parts used from syslog_snarf.pl, written by Jeremy Mates,
http://sial.org/contact/

=cut
