#!/usr/bin/perl
$|=1;

use DBI;
use Switch;
use FindBin qw($Bin);

require "$Bin/../script/conntrack.conf";

local $SIG{ALRM} = sub {
	my $time = localtime; # scalar context
#	print LOG "$$ - $time - Exit\n";
	exit 1;
};

srand($$);
$timeout = 60 * (int(rand(5))+61);
$limit = 50;

my $dbmysql = DBI->connect("DBI:mysql:;host=$DBhost", $DBuser, $DBpass) or die ($DBI::errstr);
$sts = $dbmysql->prepare("use $DBname");
$sts->execute ();

#open LOG, ">> /srv/www/htdocs/pannello_vbc/proxy/squid_acl/squid_pool.log";
#LOG->autoflush(1);

while($limit) {
	alarm $timeout;
	my $query = "";
	my $input = <>;
	chop $input;

	my @param = split / /, $input;

	my $ritorno = cerca ($param[1],$param[2], -1);
	$limit--;
	if ($ritorno) {
#		print LOG "$param[0] - $param[1] - $param[2] - ERR\n";
		print "DENY\n";
	} else {
		$ritorno = cerca ($param[1],$param[2], 1);
		if ($ritorno) {
#			print LOG "$param[0] - $param[1] - $param[2] - OK\n";
			print "OK\n";
		} else {
#			print LOG "$param[0] - $param[1] - $param[2] - ERR\n";
			print "\n";
		}
	}
}
exit;

sub cerca {
	my $ip = shift;
	my $url = shift;
	my $stato = shift;

	if ($stato == 1) {
		$tutto = "";
	} else {
		$tutto = "";
	}

	$query = "	SELECT
				1
			FROM
				proxy_net
			JOIN
				proxy_acl_net
				ON
					proxy_net.id = proxy_acl_net.idaclnet
					AND
					proxy_acl_net.stato = $stato
			JOIN
				proxy_acl_list
				ON
					proxy_acl_net.idacllist = proxy_acl_list.id
					AND
					proxy_acl_list.attivo = 1
			JOIN
				proxy_acl
				ON
					proxy_acl.idacllist = proxy_acl_list.id
					AND
					proxy_acl.attivo = 1
					AND
					LOCATE(proxy_acl.rif, '$url') > 0
			WHERE
				(INET_ATON('$ip') & INET_ATON(proxy_net.mask)) = INET_ATON(proxy_net.net)
			UNION DISTINCT SELECT
					1
				FROM
					proxy_net
				JOIN
					proxy_acl_net
					ON
						proxy_net.id = proxy_acl_net.idaclnet
						AND
						proxy_acl_net.stato = $stato
				JOIN
					proxy_acl_list
					ON
					proxy_acl_net.idacllist = proxy_acl_list.id
					AND
					proxy_acl_list.nome = 'ALL'
				WHERE
					(INET_ATON('$ip') & INET_ATON(proxy_net.mask)) = INET_ATON(proxy_net.net)
	";

#	print "$query\n";
	$sts = $dbmysql->prepare($query);
	$sts->execute ();

	if ($ref = $sts->fetchrow_hashref ) {
		return 1;
	} else {
		return 0;
	}
}
