Hi. I'm stuck at this and it doesn't make sense to me. Somehow the code works for IE but not for Chrome and Firefox. I'm printing to the terminal and it seems that for FF/Chrome it stops after the blank line (after the header) and waits for the content... but the content is actually there. Appreciate any help.
Code:
#!c:\bin\perl -w
use URI;
use IO::Socket;
use threads('yield', 'stack_size' => 64*4096);
#use threads;
use strict;
my $debug = 1;
#suppress PIPE signal
$SIG{PIPE} = 'IGNORE';
# command-line arguments
my $proxy_port=shift(@ARGV);
$proxy_port=8080 unless $proxy_port =~ /\d+/;
# create socket connection for proxy
my $proxy = IO::Socket::INET->new (
LocalPort => $proxy_port,
Type => SOCK_STREAM,
proto => 'tcp',
Reuse => 1,
Listen => 10);
binmode $proxy;
# create thread for each browser request
while (my $browser_request = $proxy->accept()) {
binmode $browser_request;
my $t = threads->new(\&fetch, $browser_request);
$t->detach;
}
# sub routine called by each thread
sub fetch{
my $browser = $_[0];
my $method ="";
my $content_length = 0;
my $content = 0;
my $accu_content_length = 0;
my $host;
my $hostAddr;
my $httpVer;
my $request;
my $count;
while (my $browser_line = <$browser>) {
# check method from browser request
unless ($method) {
($method, $hostAddr, $httpVer) = $browser_line =~ /^(\w+) +(\S+) +(\S+)/;
# get host name and port from browser and create new socket connection to host
my $uri = URI->new($hostAddr);
$host = IO::Socket::INET->new (
PeerAddr=> $uri->host,
PeerPort=> $uri->port );
die "couldn’t open $hostAddr" unless $host;
binmode $host;
print $host "$method ".$uri->path_query." $httpVer\n";
print "METJHOD: $method ".$uri->path_query." $httpVer\n";
next;
}
$content_length = $1 if $browser_line=~/Content-length: +(\d+)/i;
$accu_content_length+=length $browser_line;
if ($debug == 1){ print "[$count] $browser_line \n"; $count++ }
print $host $browser_line;
# check if last line
last if $browser_line =~ /^\s*$/ and $method ne "POST";
if ($browser_line =~ /^\s*$/ and $method eq "POST") {
$content = 1;
print "COUNTER POST: $count\n";
last unless $content_length;
next;
}
if ($content) {
$accu_content_length+=length $browser_line;
last if $accu_content_length >= $content_length;
}
#$request .= $browser_line;
}
#print $request;
$content_length = 0;
$content = 0;
$accu_content_length = 0;
while (my $host_line = <$host>) {
if ($debug == 2){ print $host_line; }
print $browser $host_line;
$content_length = $1 if $host_line=~/Content-length: +(\d+)/i;
#print "\n1: $1\n";
if ($host_line =~ m/^\s*$/ and not $content) {
$content = 1;
#last unless $content_length;
next;
}
if ($content) {
if ($content_length) {
$accu_content_length+=length $host_line;
print "\nContent Length: $content_length, accu: $accu_content_length\n";
last if $accu_content_length >= $content_length;
}
}
}
$browser-> close;
$host -> close;
}