#!/usr/bin/perl # Usage: redirector.pl daemon_port proxy_address proxy_port #use Socket; use IO::Select; use IO::Socket; ($dport, $destaddress,$destport) = @ARGV; die "Usage: $0 daemon_port destination_address destination_port\n" unless ( $dport && $destaddress && $destport ); # Set up network communication $protocol = getprotobyname("tcp"); $makeNewConnection=1; while ($makeNewConnection) { # do "daemon" thing. ## $lsn = new IO::Socket::INET(Listen => 1, LocalPort => $dport); ## examples from IO::Select socket(INC, PF_INET, SOCK_STREAM, $protocol) || die "socket:$!"; setsockopt (INC, SOL_SOCKET, SO_REUSEADDR, pack ("l", 1)) || die "setsockopt:$!"; bind(INC,sockaddr_in($dport,INADDR_ANY)) || die "bind: $!"; listen(INC,1) || die "listen:$!"; accept(OUT,INC) || die "accept:$!"; $fhin = $fhout = \*OUT; # connect to dest socket (DEST, PF_INET, SOCK_STREAM, $protocol) or die("Failed to create socket:$!"); connect (DEST, sockaddr_in($destport,inet_aton($destaddress))) or die("Failed to connect to $destaddress port $destport:$!"); $makeNewConnection=0; # Force immediate flushing of socket buffers foreach ( \*DEST, $fhin, $fhout ) { select($_); $|=1;} # Start copying packets in both directions. ## $sel = new IO::Select( $lsn ); $s = IO::Select->new($fhin,\*DEST); while ( ! $makeNewConnection ) { #this loop takes cpu to 100% until the very last #part of the web page has been retrieved or timed out.:-) foreach $fh ( $s->can_read(10) ) { # if ( ! defined($num = sysread($fh,$_,4096)) ) #never happens if ( ! ($num = sysread($fh,$_,4096)) ) { #0 indicates end of input # if (!(fileno($fh) == fileno($fhin))) { $s->remove($fh); close $fh; $s->remove($fhin); close $fhin; $makeNewConnection=1; # exit; # }; } # print STDERR "$num: $_\n"; ## if($fh == $lsn) { ## # Create a new socket ## $new = $lsn->accept; ## $sel->add($new); ## } syswrite( ((fileno($fh)==fileno($fhin))?DEST:$fhout),$_,$num); } } }; 1;