Files
pannello/proxy/conntrack.pl
2016-03-23 12:01:23 +01:00

135 lines
3.0 KiB
Perl
Executable File

#!/usr/bin/perl
$|=1;
use DBI;
use FindBin qw($Bin);
my $param = shift @ARGV;
our $verbose = 0;
if ($param eq '-v') {
$verbose = 1;
}
require "$Bin/conntrack.conf";
`sysctl -w net.netfilter.nf_conntrack_acct=1`;
my $dbmysql = DBI->connect("DBI:mysql:;host=$DBhost", $DBuser, $DBpass) or die ($DBI::errstr);
$sts = $dbmysql->prepare("use $DBname");
$sts->execute ();
$query = " SELECT
id,
ip,
port
FROM
proxy_conn
WHERE
attivo = 1
";
$sts = $dbmysql->prepare($query);
$sts->execute ();
while ( $ref = $sts->fetchrow_hashref ) {
my $id = $$ref{'id'};
my $ip = $$ref{'ip'};
my $port = $$ref{'port'};
if (!fork) {
while (1) {
my $pidi = fork;
if (!$pidi) {
conntrack ($id, $ip, $port);
exit;
} else {
waitpid $newpidi, WNOHANG;
}
}
}
}
if ($verbose) {
while (1) { sleep 1000; }
}
exit 1;
sub conntrack {
my $sess_id = shift;
my $proxy_IP = shift;
my $proxy_PORT = shift;
print "Attivato agente $sess_id su $proxy_IP:$proxy_PORT\n" if ($verbose);
my $dbmysql = DBI->connect("DBI:mysql:;host=$DBhost", $DBuser, $DBpass) or die ($DBI::errstr);
$sts = $dbmysql->prepare("use $DBname");
$sts->execute ();
open CT, "/usr/sbin/conntrack -E -eNEW,DESTROY -otimestamp,id -p tcp -d $proxy_IP --dport $proxy_PORT |" or die "non va\n";
while (<CT>) {
my $riga = $_;
# print "$riga";
if ( $riga =~ /^\s*\[(\d+)\.\d+\]\s+\[NEW\] tcp\s+\d+ \d+ \S*\s*src=(\S+) dst=(\S+) sport=\d+ dport=(\d+)\s+\[\w+\] src=\S+ dst=\S+ sport=\d+ dport=\d+ id=(\d+)/ ) {
my $remote_START = $1;
my $remote_IP = $2;
my $local_IP = $3;
my $local_PORT = $4;
my $thread_ID = $5;
my $query = " INSERT INTO
proxy_dati
(ip, thread, data_new)
VALUES
('$remote_IP', $thread_ID, FROM_UNIXTIME($remote_START))
";
# print "$query\n";
$sts = $dbmysql->prepare($query);
$sts->execute ();
# print "$riga";
}
if ( $riga =~ /^\s*\[(\d+)\.\d+\]\s+\[DESTROY\] tcp\s+\d+ src=(\S+) dst=(\S+) sport=\d+ dport=(\d+) packets=\d+ bytes=(\d+) src=\S+ dst=\S+ sport=\d+ dport=\d+ packets=\d+ bytes=(\d+) \[\w+\] id=(\d+)/) {
my $remote_DESTROY = $1;
my $remote_IP = $2;
my $local_IP = $3;
my $local_PORT = $4;
my $remote_SEND = $5;
my $remote_RECEIVE = $6;
my $thread_ID = $7;
print "$sess_id - IP: $remote_IP - ID: $thread_ID - Invati: $remote_SEND - Ricevuti: $remote_RECEIVE\n" if ($verbose);
my $query = " UPDATE
proxy_dati
SET
data_destroy = FROM_UNIXTIME($remote_DESTROY),
inviati = $remote_SEND,
ricevuti = $remote_RECEIVE,
tempo = TIMESTAMPDIFF(SECOND, data_new, FROM_UNIXTIME($remote_DESTROY)),
vel_inv = $remote_SEND / TIMESTAMPDIFF(SECOND, data_new, FROM_UNIXTIME($remote_DESTROY)),
vel_ric = $remote_RECEIVE / TIMESTAMPDIFF(SECOND, data_new, FROM_UNIXTIME($remote_DESTROY))
WHERE
thread = $thread_ID
AND
ip = '$remote_IP'
AND
data_destroy IS NULL
";
# print "$query\n";
$sts = $dbmysql->prepare($query);
$sts->execute ();
}
}
close CT;
}