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

use IPC::Open2;

use POSIX;
setuid(100);

sub debug {
	print STDERR @_;
}

debug "Starting " . join(" ", @ARGV) . "\n";
$pid = open2(*read1,*write1,@ARGV);
debug "Started pid $pid\n";

while(<STDIN>) {
  debug "Got $_\n";
  my ($method, $url, $ip, $user) = split(/ /);
  $url =~ s/%([0-9a-fA-F][0-9a-fA-F])/pack("c",hex($1))/eg;
  $method =~ s/%([0-9a-fA-F][0-9a-fA-F])/pack("c",hex($1))/eg;
  $user =~ s/%([0-9a-fA-F][0-9a-fA-F])/pack("c",hex($1))/eg;
  $id =~ s/%([0-9a-fA-F][0-9a-fA-F])/pack("c",hex($1))/eg;
  $user =~ s%.*\\%%;
  $user =~ s%.*/%%;
  $user =~ s%.*@%%;

  $user = "-" if $user == "";
  $ip = "-" if $ip == "";

#       For each requested URL rewriter will receive on line with the format
#
#       URL <SP> client_ip "/" fqdn <SP> user <SP> method [<SP> kvpairs]<NL>

  print write1 "$url $ip/- $user $method\n"; $ans = <read1>;
  debug "Answer: $ans\n";

  if ($ans =~ /^3/ || $ans =~ m%http://10.24.108.182/cgi-bin/squidGuard.cgi%) { 
    my ($message) = ($ans =~ m/targetgroup=([^&]*)/);
    print "ERR message=$message log=$message\n";
  } else {
    print "OK\n";
  }
} 
