#!/usr/bin/perl
use Socket;
use IO::Handle;
open(STDERR, ">&STDOUT") || die "error opening STDOUT";
if(!$ARGV[0]) {
    die "enter port";
}
socket(S, PF_INET, SOCK_STREAM, getprotobyname('tcp')) || die "error in socket";
bind(S, sockaddr_in($ARGV[0], INADDR_ANY)) || die "error in bind";
($port) = unpack_sockaddr_in(getsockname(S));
#print "$port\n";
setsockopt(S, SOL_SOCKET, SO_REUSEADDR, pack("l", 1)) || die "error in setsockopt";
listen(S, SOMAXCONN) || die "error in listen";
eval { 
    local $SIG{ALRM} = sub { die "error: alarm timed out" };
    alarm 60;
    accept(C, S);
    alarm 0;
};
if ($@ and $@ !~ /alarm clock restart/) {
    print "error: Accept timed out. Remote user did not send data.\n";
    die; exit(-1); }
C->autoflush(1);
syswrite(C, "1", 1);
sysread(C, $buf, 4);
if (!($buf eq "SEND")) { 
    print "error: invalid response - expected SEND: $buf\n"; # exit(-1); 
}
sysread(C, $buf, 500);
if ($buf =~ /^([^\"]*)\"([^\"]*)\".*?([\d]*)$/) {
    ($nick, $name, $size) = ($1, $2, $3); 
} else { 
    print "error: invalid response - expected fileinfo: $buf\n"; exit(-1); }
syswrite(C, "0", 1);
eval {
 local $SIG{ALRM} = sub { die "error: alarm timed out" };
 alarm 60;

 while($l = <C>) { alarm 0; print $l; alarm 60;}
 alarm 0;
};
if ($@ and $@ !~ /alarm clock restart/) {
    print "error: time out. Remote user stopped sending data.\n";
    die; exit(-1); }

exit;

