1 |
#!/usr/bin/perl |
2 |
|
3 |
use warnings; |
4 |
use strict; |
5 |
|
6 |
use IO::Socket; |
7 |
use Data::Dump qw/dump/; |
8 |
use DBI; |
9 |
|
10 |
my $port = 514; |
11 |
|
12 |
my $MAXLEN = 1524; |
13 |
|
14 |
my $dsn = 'DBI:Pg:dbname=syslog;host=llin.lan'; |
15 |
my $user = 'dpavlin'; |
16 |
my $debug = 0; |
17 |
|
18 |
my @facilities = ( qw/ |
19 |
kernel user mail system security internal printer news uucp clock security2 |
20 |
FTP NTP audit alert clock2 local0 local1 local2 local3 local4 local5 local6 local7 |
21 |
/ ); |
22 |
|
23 |
# Start Listening on UDP port 514 |
24 |
my $sock = IO::Socket::INET->new( |
25 |
LocalPort => $port, |
26 |
Proto => 'udp' |
27 |
# ReuseAddr => 1, |
28 |
) || die "can't listen to $port: $!"; |
29 |
|
30 |
my $dbh = DBI->connect( $dsn, $user, '', { RaiseError => 1 } ) || die $DBI::errstr; |
31 |
|
32 |
my $sth = $dbh->prepare(qq{ |
33 |
insert into log |
34 |
(ip,hostname,facility,priority,level,program,message) values |
35 |
(? ,? ,? ,? ,? ,? ,? ) |
36 |
}); |
37 |
|
38 |
print "INFO: listen on $port",$/; |
39 |
|
40 |
my $rin = ''; |
41 |
my $buf; |
42 |
while(1) { |
43 |
$sock->recv($buf, $MAXLEN); |
44 |
my ($port, $ipaddr) = sockaddr_in($sock->peername); |
45 |
my $hostname = gethostbyaddr($ipaddr, AF_INET); |
46 |
my $ip = join('.', unpack('C4',$ipaddr)); |
47 |
warn "# ",dump( $port, $ipaddr, $hostname, $buf ); |
48 |
|
49 |
if ( $buf =~ /<(\d+)>\s*(\S*)\s*:\s*(.*)/ ) { |
50 |
my $level=$1 % 8; |
51 |
my $fac=($1-$level) / 8; |
52 |
$sth->execute( $ip, $hostname, $fac, $1, $level, $2, $3 ); |
53 |
} else { |
54 |
$sth->execute( $ip, $hostname, undef, undef, undef, undef, $buf ); |
55 |
} |
56 |
} |