So I'm trying to create a perl script that opens a socket on port 5555 and my web browser (internet explorer) then connects to it and the perl script connects to another server which is defined in the script. Then outputs the data from the browser socket to the other socket and any data from the other socket to the browser socket. Basically a "go between". Here's my code:
Code:
#!/usr/bin/perl -w
# serverfork.pl - a server that forks a child
# process to handle client connections
use IO::Socket;
use Sys::Hostname;
use POSIX qw(:sys_wait_h);
sub REAP {
1 until (-1 == waitpid(-1, WNOHANG));
$SIG{CHLD} = \&REAP;
}
$SIG{CHLD} = \&REAP;
my $sock = new IO::Socket::INET(
LocalPort => 5555,
Proto => 'tcp',
Listen => SOMAXCONN,
Reuse => 1,
Blocking => 0);
$sock->autoflush(1);
$sock or die "no socket :$!";
my($new_sock, $buf, $kid);
while ($new_sock = $sock->accept()) {
# execute a fork, if this is
# the parent, its work is done,
# go straight to continue
next if $kid = fork;
die "fork: $!" unless defined $kid;
# child now...
# close the server - not needed
#close $sock;
$needed = true;
if($kid){
}else{
while ($needed) {
my $outSock = new IO::Socket::INET (
PeerAddr => 'XXX.XXX.XXX.XXX',
PeerPort => '80',
Proto => 'tcp',
); die "Could not create socket: $!\n" unless $outSock;
$done = 0;
$post = 0;
print "______________REQUEST_________________\n";
while($done == 0) {
print "Reading...\n";
$buf = <$new_sock>;
print "Read.\n";
@header = split(/ /, $buf);
print $outSock $buf;
print $buf;
if($header[0] eq "POST"){
$post = 1;
}
if($buf =~ /^\r\n/ && $post == 0){
$done = 1;
print "Done get: $done\n";
}if($buf =~ /^\r\n/ && $post == 1){
print "Post Data: ".<$new_sock>;
$done = 1;
print "Done post: $done\n";
}
}
print "______________RESPONSE_________________\n";
while (($buf = <$outSock>)) {
print $new_sock $buf;
#print $buf;
}
print "______________END_________________\n";
if(!$outSock){
close($outSock);
$needed = false;
}
}
}
#exit;
} continue {
print "Closing\n";
# parent closes the client since
# it is not needed
close $new_sock;
}
The problem I am having is that it blocks or something whenever there is any post data. I try and read the post data and it just hangs. I've tried everything I can think of, like setting non-block but I believe it's set by default, but setting it did nothing.
I tried sysread() to read the amount of bytes that the http request says the content length is. That didn't work....or maybe I didn't do it right.