#!/usr/bin/perl
#
# Human HTTP Proxy
#

$PORT=8000;
$FILE="/tmp/htproxy";
$EDITOR="/usr/bin/vi";
@IGNORE=("\.gif","\.jpg","\.png","\.css","\.js","\.css");

use IO::Socket;

$l=IO::Socket::INET->new(
	LocalPort  => $PORT,
	Listen     => 1,
	Reuse	   => 1) || die "Cannot Listen at port $PORT\n";

while(1)
{
  $buf="";
  $host="";

  $s=$l->accept();
  print "Accepted\n";
  $first=<$s>;
  $first=~s/\r\n//;
  $save=0;
  while(1)
  {
  	$line=<$s>;
	if ( $line=~/^Host: (.*)\r\n/ )
	{
		$host="$1";
	}
	$buf.=$line;
	if ( $buf=~/\r\n\r\n$/ ) { last; }
  }
  $msg=$buf;
  $get=$first;
  $get=~s/http\:\/\/$host//;

  open F,">","$FILE" || $s->close();
  	print F "$get\r\n";
	print F "$msg\r\n";
  close F;
  #print "MESSAGE: $msg\n";
  print "host: $host\n";
  print "line: $first\n";
  print "file: $get\n";

  $ignosapo=0;
  foreach $ign (@IGNORE)
  {
  	if ($get=~/$ign/)
	{ $ignosapo=1; }
  }
  if ( $ignosapo == 0 )
  {
    print "EDIT HEADERS? (y/n)\n";
    if ( <STDIN>=~/y/ )
    {  system("$EDITOR $FILE");  }
  }
   # Connect to remote host
    $r=IO::Socket::INET->new(
    	PeerAddr => $host,
  	PeerPort => 80 ) || 
		$s->close(); 
    print "connected\n";
   # send headers
    open F,"$FILE" || $->close();
  	while(<F>)
	{ print $r $_; }
    close F;
   # dump data to incoming connection
    while(<$r>)
     { print $s $_; }
    $r->close();
    $s->close();
    print "sent\n";
}

