#!/usr/bin/perl

use Mysql;
$CONF='/etc/dynacc.conf';
$FILTER='/sbin/iptables';
$DB_HOST='localhost';
#$DB_HOST='braille.fcc.ro';
$DB_USER='root';
$DB_PASS='';
$DATABASE='acct';



sub set
{

# Check if the chain exists and all traffic goes through it
$vezi=`$FILTER -L|grep "Chain ac"`;
if ($vezi eq '') {$execline="$FILTER -N ac; $FILTER -I FORWARD 2 -j ac"; } 
 elsif (index($vezi,'1') == "-1") {$execline="$FILTER -I FORWARD 2 -j ac"; }
 else {$execline=''; }
$execline ne '' && system("$execline");
system("$FILTER -F ac");

open(conf,$CONF) || die "Cannot open $CONF";
while($line=<conf>)
{
chop($line);
if ($line =~ /^#/ || $line =~ /^\s*$/) { next; };
@rule{name,prot,src,sport,dst,dport} = split(/\|/,$line,6); 
$execline="$FILTER -A ac";
if ($rule{prot} ne '') {$execline.=" -p $rule{prot}"; };
if ($rule{src} ne '') {$execline.=" -s $rule{src}"; };
if ($rule{sport} ne '') {$execline.=" --sport $rule{sport}"; };
if ($rule{dst} ne '') {$execline.=" -d $rule{dst}"; };
if ($rule{dport} ne '') {$execline.=" --dport $rule{dport}"; };
$execline.=" -j ACCEPT";
print $rule{name},"\n";
system("$execline"); 
}
close(conf);
}

sub zii
{
($prot,$src,$dst,$sport,$dport) = @_;
if ($prot eq '') { $prot='all';}
if ($src eq '0/0') { $src='0.0.0.0/0';}
if ($dst eq '0/0') { $dst='0.0.0.0/0';}

open(all,"$FILTER -nL ac -vx|"); @altceva=<all>; close(all);
for($i=2; $i<@altceva; $i++) 
{
@ceva=(split(/ +/,$altceva[$i]))[2,4,8,9,11,12]; 
if($ceva[4] =~ /^dpt/) {$ceva[5]=$ceva[4]; $ceva[4]='';}
if($prot eq $ceva[1] && $src eq $ceva[2] && $dst eq $ceva[3] && index($ceva[4],$sport) != -1 && index($ceva[5],$dport) != -1) { return $ceva[0];}
}
}

sub get
{
open(conf,$CONF) || die "Cannot open $CONF";
while($line=<conf>)
{
chop($line);
if ($line =~ /^#/ || $line =~ /^\s*$/) { next; };
@rule{name,prot,src,sport,dst,dport} = split(/\|/,$line,6);
if (index($rule{name},$_[0]) ne '-1') 
{ return &zii("$rule{prot}","$rule{src}","$rule{dst}","$rule{sport}","$rule{dport}");
}
} 
close(conf);
}

sub mrtg
{
$ce=$_[0];
$in=&get("$ce in");
$out=&get("$ce out");
$uptime=`uptime |cut -b 14-27`; 
$hostname=`hostname`;
print "$in\n$out\n$uptime$hostname";
}

sub mysql
{
$dbh=Mysql->connect($DB_HOST,$DATABASE,$DB_USER,$DB_PASS);
$ce=$_[0];
$in=&get("$ce in");
$out=&get("$ce out");
$qry="insert into $ce (inBytes, outBytes, time_stamp) values ($in, $out, now())";
$dbq=$dbh->query($qry);
}

(@ARGV >= 1) || die "Usage: razacc {-s | -m rulename | -u rulename}";
while($opt=shift(@ARGV))
{
if ($opt eq "-s") {&set;} 
if ($opt eq "-m") { $x=shift @ARGV; &mrtg($x); }
if ($opt eq "-u") { $x=shift @ARGV; &mysql($x);}
}

#						Razvan Radu <rot@fcc.ro>
