#!/usr/local/bin/php
<?php

/*
 * Gaby Vanhegan <gaby@vanhegan.net> 2004-12-03
 *
 * Munge logs from spamd (pf) and put them into an rrd file
 * for handling by rrdtool.
 */

// Where are we?  Where do RRD's go?  Where do the logs come from?
$BASE		= "/home/gaby/prel/rrd";
$BASE_RRD	= "/var/symon/rrds/localhost";

$LOG		= "/home/gaby/rrd-logs/rblsmtpd.log";
$LOG_TMP	= tempnam( "/tmp", "rrd-rblsmtpd" );

// No log?  Nothing to do.
if ( !( file_exists( $LOG ) ) ) { exit; }

$lists		= array();

// Sample log line:
// @4000000041b08be60ef96984 rblsmtpd: 195.42.160.18 pid 15201: 451 http://dsbl.org/listing?195.42.160.18

// Log some output text please
function log_msg ( $input ) {
	$msg	= trim( $input );
	$lines	= explode( "\n", $msg );
	foreach ( $lines as $line ) {
		$when	= date( "Y-m-d H:i:s" );
		print "[$when] $line\n";
		}
	}

// Convert a tai64n to a unix timestamp
function tai64n2unix ( $tai ) {

	// Convert TAI64N to local time
	$result	= shell_exec( "echo '$tai' | /usr/local/bin/tai64nlocal" );
	$result		= trim( $result );

	// The result is 2004-12-01 19:54:32.159264500
	// Chop off the microseconds
	list( $date, $chaff )	= explode( ".", $result );

	// Convert to epoch time and return
	$return		= strtotime( $date );
	return $return;
	}

// Move the log file out of active duty
rename( $LOG, $LOG_TMP );
$fh		= fopen( $LOG_TMP, "r" );

// Now going through our log data...
while( $line = fgets( $fh ) ) {

	$line	= trim( $line );
	$hit	= false;

	// Single up the whitespace in the line
	$hit	= preg_match( "/^(@.+) rblsmtpd: .+http:\/\/(.+)\.[com|net|org].+$/", $line, $matches );

	// If it matches a line
	if ( $hit ) {
		// Normalise the time to the nearest half hour (1800 seconds)
		$the_time	= tai64n2unix( $matches[1] );
		$the_time	= ( $the_time - ( $the_time % 1800 ) );

		// Which list?
		$list		= strtolower( $matches[2] );
		$list		= str_replace( "www.", "", $list );

		$lists[ $list ][ $the_time ][ "blocks" ]	+= 1;
		$lists[ "all" ][ $the_time ][ "blocks" ]	+= 1;
		}
	}

fclose( $fh );
unlink( $LOG_TMP );

foreach ( $lists as $list => $data ) {

	$rrd_file	= "rblsmtpd_" . $list . ".rrd";
	if ( $list == "all" ) { $rrd_file = "rblsmtpd.rrd"; }

	$command_base	= "/usr/local/bin/rrdtool update $BASE_RRD/$rrd_file";
	$command		= $command_base;
	$count			= 1;

	if ( file_exists( $rrd_file ) ) {

		// Sort out data in ascending date please
		ksort( $data );

		foreach ( $data as $time => $values ) {

			$count++;

			$blocks		= $values[ "blocks" ];
			$wait		= $values[ "time" ];

			if ( ( $count % 30 ) < 1 ) {
				//log_msg( $command );
				print trim( shell_exec( $command ) );
				$command	= $command_base;
				}

			$command	.= " $time:$blocks:$wait";
			}

		//log_msg( $command );
		print trim( shell_exec( $command ) );
		}
	else {
		log_msg( "$rrd_file does not exist!" );
		}
	}

?>
