Annotation of loncom/lonc, revision 1.20

1.1       albertel    1: #!/usr/bin/perl
                      2: 
                      3: # The LearningOnline Network
                      4: # lonc - LON TCP-Client Domain-Socket-Server
                      5: # provides persistent TCP connections to the other servers in the network
                      6: # through multiplexed domain sockets
                      7: #
                      8: # PID in subdir logs/lonc.pid
                      9: # kill kills
                     10: # HUP restarts
                     11: # USR1 tries to open connections again
                     12: 
1.2       www        13: # 6/4/99,6/5,6/7,6/8,6/9,6/10,6/11,6/12,7/14,7/19,
1.5       www        14: # 10/8,10/9,10/15,11/18,12/22,
1.10      www        15: # 2/8,7/25 Gerd Kortemeyer
                     16: # 12/05 Scott Harrison
                     17: # 12/05 Gerd Kortemeyer
1.14      www        18: # 01/10/01 Scott Harrison
1.19      www        19: # 03/14/01,03/15,06/12,11/26,11/27 Gerd Kortemeyer
1.10      www        20: # 
1.1       albertel   21: # based on nonforker from Perl Cookbook
                     22: # - server who multiplexes without forking
                     23: 
                     24: use POSIX;
                     25: use IO::Socket;
                     26: use IO::Select;
                     27: use IO::File;
                     28: use Socket;
                     29: use Fcntl;
                     30: use Tie::RefHash;
                     31: use Crypt::IDEA;
                     32: 
1.18      www        33: my $status='';
                     34: my $lastlog='';
                     35: 
1.9       harris41   36: # grabs exception and records it to log before exiting
                     37: sub catchexception {
                     38:     my ($signal)=@_;
1.10      www        39:     $SIG{'QUIT'}='DEFAULT';
                     40:     $SIG{__DIE__}='DEFAULT';
1.9       harris41   41:     &logthis("<font color=red>CRITICAL: "
                     42:      ."ABNORMAL EXIT. Child $$ for server $wasserver died through "
1.11      harris41   43:      ."\"$signal\" with this parameter->[$@]</font>");
1.9       harris41   44:     die($@);
                     45: }
                     46: 
1.17      www        47: $childmaxattempts=5;
1.5       www        48: 
1.8       harris41   49: # -------------------------------- Set signal handlers to record abnormal exits
                     50: 
                     51: $SIG{'QUIT'}=\&catchexception;
                     52: $SIG{__DIE__}=\&catchexception;
                     53: 
1.1       albertel   54: # ------------------------------------ Read httpd access.conf and get variables
                     55: 
1.11      harris41   56: open (CONFIG,"/etc/httpd/conf/access.conf") || die "Can't read access.conf";
1.1       albertel   57: 
                     58: while ($configline=<CONFIG>) {
                     59:     if ($configline =~ /PerlSetVar/) {
                     60: 	my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.4       www        61:         chomp($varvalue);
1.1       albertel   62:         $perlvar{$varname}=$varvalue;
                     63:     }
                     64: }
                     65: close(CONFIG);
1.7       www        66: 
1.13      harris41   67: # ----------------------------- Make sure this process is running from user=www
                     68: my $wwwid=getpwnam('www');
                     69: if ($wwwid!=$<) {
                     70:    $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                     71:    $subj="LON: $perlvar{'lonHostID'} User ID mismatch";
1.14      www        72:    system("echo 'User ID mismatch.  lonc must be run as user www.' |\
1.13      harris41   73:  mailto $emailto -s '$subj' > /dev/null");
                     74:    exit 1;
                     75: }
                     76: 
1.7       www        77: # --------------------------------------------- Check if other instance running
                     78: 
                     79: my $pidfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
                     80: 
                     81: if (-e $pidfile) {
                     82:    my $lfh=IO::File->new("$pidfile");
                     83:    my $pide=<$lfh>;
                     84:    chomp($pide);
1.11      harris41   85:    if (kill 0 => $pide) { die "already running"; }
1.7       www        86: }
1.1       albertel   87: 
                     88: # ------------------------------------------------------------- Read hosts file
                     89: 
1.11      harris41   90: open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
1.1       albertel   91: 
                     92: while ($configline=<CONFIG>) {
                     93:     my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
                     94:     chomp($ip);
                     95:     $hostip{$id}=$ip;
                     96: }
                     97: close(CONFIG);
                     98: 
                     99: # -------------------------------------------------------- Routines for forking
                    100: 
                    101: %children               = ();       # keys are current child process IDs,
                    102:                                     # values are hosts
                    103: %childpid               = ();       # the other way around
                    104: 
                    105: %childatt               = ();       # number of attempts to start server
                    106:                                     # for ID
                    107: 
                    108: sub REAPER {                        # takes care of dead children
                    109:     $SIG{CHLD} = \&REAPER;
                    110:     my $pid = wait;
                    111:     my $wasserver=$children{$pid};
1.6       www       112:     &logthis("<font color=red>CRITICAL: "
                    113:      ."Child $pid for server $wasserver died ($childatt{$wasserver})</font>");
1.1       albertel  114:     delete $children{$pid};
                    115:     delete $childpid{$wasserver};
                    116:     my $port = "$perlvar{'lonSockDir'}/$wasserver";
                    117:     unlink($port);
                    118: }
                    119: 
                    120: sub HUNTSMAN {                      # signal handler for SIGINT
                    121:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
1.17      www       122:     map {
                    123:         $wasserver=$children{$_};
1.18      www       124:         &status("Closing $wasserver");
1.17      www       125:         &logthis('Closing '.$wasserver.': '.&subreply('exit',$wasserver));
1.18      www       126:         &status("Kill PID $_ for $wasserver");
1.17      www       127: 	kill ('INT',$_);
                    128:     } keys %children;
1.1       albertel  129:     my $execdir=$perlvar{'lonDaemons'};
                    130:     unlink("$execdir/logs/lonc.pid");
1.5       www       131:     &logthis("<font color=red>CRITICAL: Shutting down</font>");
1.1       albertel  132:     exit;                           # clean up with dignity
                    133: }
                    134: 
                    135: sub HUPSMAN {                      # signal handler for SIGHUP
                    136:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.17      www       137:     map {
                    138:         $wasserver=$children{$_};
1.18      www       139:         &status("Closing $wasserver");
1.17      www       140:         &logthis('Closing '.$wasserver.': '.&subreply('exit',$wasserver));
1.18      www       141:         &status("Kill PID $_ for $wasserver");
1.17      www       142: 	kill ('INT',$_);
                    143:     } keys %children;
1.5       www       144:     &logthis("<font color=red>CRITICAL: Restarting</font>");
1.12      harris41  145:     unlink("$execdir/logs/lonc.pid");
1.1       albertel  146:     my $execdir=$perlvar{'lonDaemons'};
                    147:     exec("$execdir/lonc");         # here we go again
                    148: }
                    149: 
1.18      www       150: sub checkchildren {
                    151:     &initnewstatus();
                    152:     &logstatus();
                    153:     &logthis('Going to check on the children');
                    154:     map {
                    155: 	sleep 1;
                    156:         unless (kill 'USR1' => $_) {
                    157: 	    &logthis ('Child '.$_.' is dead');
                    158:             &logstatus($$.' is dead');
                    159:         } 
                    160:     } sort keys %children;
                    161: }
                    162: 
1.1       albertel  163: sub USRMAN {
                    164:     &logthis("USR1: Trying to establish connections again");
                    165:     foreach $thisserver (keys %hostip) {
                    166: 	$answer=subreply("ping",$thisserver);
1.6       www       167:         &logthis("USR1: Ping $thisserver "
                    168:         ."(pid >$childpid{$thisserver}<, $childatt{thisserver} attempts): "
                    169:         ." >$answer<");
1.1       albertel  170:     }
1.6       www       171:     %childatt=();
1.18      www       172:     &checkchildren();
1.1       albertel  173: }
                    174: 
                    175: # -------------------------------------------------- Non-critical communication
                    176: sub subreply { 
                    177:  my ($cmd,$server)=@_;
1.5       www       178:  my $answer='';
1.1       albertel  179:  if ($server ne $perlvar{'lonHostID'}) { 
                    180:     my $peerfile="$perlvar{'lonSockDir'}/$server";
                    181:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    182:                                       Type    => SOCK_STREAM,
                    183:                                       Timeout => 10)
                    184:        or return "con_lost";
1.19      www       185:     $SIG{ALRM}=sub { die "timeout" };
                    186:     $SIG{__DIE__}='DEFAULT';
                    187:     eval {
                    188:      alarm(10);
                    189:      print $sclient "$cmd\n";
                    190:      my $answer=<$sclient>;
                    191:      chomp($answer);
                    192:      alarm(0);
                    193:     };
                    194:     if ((!$answer) || ($@=~/timeout/)) { $answer="con_lost"; }
                    195:     $SIG{ALRM}='DEFAULT';
                    196:     $SIG{__DIE__}=\&catchexception;
1.1       albertel  197:  } else { $answer='self_reply'; }
                    198:  return $answer;
                    199: }
                    200: 
                    201: # --------------------------------------------------------------------- Logging
                    202: 
                    203: sub logthis {
                    204:     my $message=shift;
                    205:     my $execdir=$perlvar{'lonDaemons'};
                    206:     my $fh=IO::File->new(">>$execdir/logs/lonc.log");
                    207:     my $now=time;
                    208:     my $local=localtime($now);
1.18      www       209:     $lastlog=$local.': '.$message;
1.1       albertel  210:     print $fh "$local ($$): $message\n";
                    211: }
                    212: 
1.3       www       213: 
                    214: sub logperm {
                    215:     my $message=shift;
                    216:     my $execdir=$perlvar{'lonDaemons'};
                    217:     my $now=time;
                    218:     my $local=localtime($now);
                    219:     my $fh=IO::File->new(">>$execdir/logs/lonnet.perm.log");
                    220:     print $fh "$now:$message:$local\n";
                    221: }
1.18      www       222: # ------------------------------------------------------------------ Log status
                    223: 
                    224: sub logstatus {
                    225:     my $docdir=$perlvar{'lonDocRoot'};
                    226:     my $fh=IO::File->new(">>$docdir/lon-status/loncstatus.txt");
                    227:     print $fh $$."\t".$status."\t".$lastlog."\n";
                    228: }
                    229: 
                    230: sub initnewstatus {
                    231:     my $docdir=$perlvar{'lonDocRoot'};
                    232:     my $fh=IO::File->new(">$docdir/lon-status/loncstatus.txt");
                    233:     my $now=time;
                    234:     my $local=localtime($now);
                    235:     print $fh "LONC status $local - parent $$\n\n";
                    236: }
                    237: 
                    238: # -------------------------------------------------------------- Status setting
                    239: 
                    240: sub status {
                    241:     my $what=shift;
                    242:     my $now=time;
                    243:     my $local=localtime($now);
                    244:     $status=$local.': '.$what;
                    245: }
                    246: 
1.3       www       247: 
1.1       albertel  248: # ---------------------------------------------------- Fork once and dissociate
                    249: 
                    250: $fpid=fork;
                    251: exit if $fpid;
1.11      harris41  252: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel  253: 
1.11      harris41  254: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel  255: 
                    256: # ------------------------------------------------------- Write our PID on disk
                    257: 
                    258: $execdir=$perlvar{'lonDaemons'};
                    259: open (PIDSAVE,">$execdir/logs/lonc.pid");
                    260: print PIDSAVE "$$\n";
                    261: close(PIDSAVE);
1.5       www       262: &logthis("<font color=red>CRITICAL: ---------- Starting ----------</font>");
1.1       albertel  263: 
                    264: # ----------------------------- Ignore signals generated during initial startup
                    265: $SIG{HUP}=$SIG{USR1}='IGNORE';
                    266: # ------------------------------------------------------- Now we are on our own
                    267:     
                    268: # Fork off our children, one for every server
                    269: 
1.18      www       270: &status("Forking ...");
                    271: 
1.1       albertel  272: foreach $thisserver (keys %hostip) {
                    273:     make_new_child($thisserver);
                    274: }
                    275: 
                    276: &logthis("Done starting initial servers");
                    277: # ----------------------------------------------------- Install signal handlers
                    278: 
                    279: $SIG{CHLD} = \&REAPER;
                    280: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                    281: $SIG{HUP}  = \&HUPSMAN;
                    282: $SIG{USR1} = \&USRMAN;
                    283: 
                    284: # And maintain the population.
                    285: while (1) {
1.18      www       286:     &status("Sleeping");
1.1       albertel  287:     sleep;                          # wait for a signal (i.e., child's death)
                    288:                                     # See who died and start new one
1.18      www       289:     &status("Woke up");
1.1       albertel  290:     foreach $thisserver (keys %hostip) {
                    291:         if (!$childpid{$thisserver}) {
1.17      www       292: 	    if ($childatt{$thisserver}<$childmaxattempts) {
1.6       www       293: 	       $childatt{$thisserver}++;
1.5       www       294:                &logthis(
                    295:    "<font color=yellow>INFO: Trying to reconnect for $thisserver "
1.6       www       296:   ."($childatt{$thisserver} of $childmaxattempts attempts)</font>"); 
1.1       albertel  297:                make_new_child($thisserver);
                    298: 	    }
                    299:         }       
                    300:     }
                    301: }
                    302: 
                    303: 
                    304: sub make_new_child {
                    305:    
                    306:     my $conserver=shift;
                    307:     my $pid;
                    308:     my $sigset;
                    309:     &logthis("Attempting to start child for server $conserver");
                    310:     # block signal for fork
                    311:     $sigset = POSIX::SigSet->new(SIGINT);
                    312:     sigprocmask(SIG_BLOCK, $sigset)
1.11      harris41  313:         or die "Can't block SIGINT for fork: $!\n";
1.1       albertel  314:     
1.11      harris41  315:     die "fork: $!" unless defined ($pid = fork);
1.1       albertel  316:     
                    317:     if ($pid) {
                    318:         # Parent records the child's birth and returns.
                    319:         sigprocmask(SIG_UNBLOCK, $sigset)
1.11      harris41  320:             or die "Can't unblock SIGINT for fork: $!\n";
1.1       albertel  321:         $children{$pid} = $conserver;
                    322:         $childpid{$conserver} = $pid;
                    323:         return;
                    324:     } else {
                    325:         # Child can *not* return from this subroutine.
                    326:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
1.18      www       327:         $SIG{USR1}= \&logstatus;
                    328:    
1.1       albertel  329:         # unblock signals
                    330:         sigprocmask(SIG_UNBLOCK, $sigset)
1.11      harris41  331:             or die "Can't unblock SIGINT for fork: $!\n";
1.1       albertel  332: 
                    333: # ----------------------------- This is the modified main program of non-forker
                    334: 
                    335: $port = "$perlvar{'lonSockDir'}/$conserver";
                    336: 
                    337: unlink($port);
1.18      www       338: 
1.1       albertel  339: # ---------------------------------------------------- Client to network server
1.18      www       340: 
                    341: &status("Opening TCP: $conserver");
                    342: 
1.1       albertel  343: unless (
                    344:   $remotesock = IO::Socket::INET->new(PeerAddr => $hostip{$conserver},
                    345:                                       PeerPort => $perlvar{'londPort'},
                    346:                                       Proto    => "tcp",
                    347:                                       Type     => SOCK_STREAM)
1.5       www       348:    ) { 
                    349:        my $st=120+int(rand(240));
                    350:        &logthis(
                    351: "<font color=blue>WARNING: Couldn't connect $conserver ($st secs): $@</font>");
                    352:        sleep($st);
1.1       albertel  353:        exit; 
                    354:      };
1.20    ! www       355: # ----------------------------------------------------------------- Init dialog
1.18      www       356: 
                    357: &status("Init dialogue: $conserver");
                    358: 
1.20    ! www       359:      $SIG{ALRM}=sub { die "timeout" };
        !           360:      $SIG{__DIE__}='DEFAULT';
        !           361:      eval {
        !           362:          alarm(60);
1.2       www       363: print $remotesock "init\n";
                    364: $answer=<$remotesock>;
                    365: print $remotesock "$answer";
1.1       albertel  366: $answer=<$remotesock>;
                    367: chomp($answer);
1.20    ! www       368:           alarm(0);
        !           369:      };
        !           370:      $SIG{ALRM}='DEFAULT';
        !           371:      $SIG{__DIE__}=\&catchexception;
        !           372:  
        !           373:      if ($@=~/timeout/) {
        !           374: 	 &logthis("Timed out during init: $conserver");
        !           375:          exit;
        !           376:      }
        !           377: 
        !           378: 
1.2       www       379: &logthis("Init reply for $conserver: >$answer<");
1.17      www       380: if ($answer ne 'ok') {
                    381:        my $st=120+int(rand(240));
                    382:        &logthis(
                    383: "<font color=blue>WARNING: Init failed $conserver ($st secs)</font>");
                    384:        sleep($st);
                    385:        exit; 
                    386: }
1.1       albertel  387: sleep 5;
1.18      www       388: &status("Ponging $conserver");
1.1       albertel  389: print $remotesock "pong\n";
                    390: $answer=<$remotesock>;
                    391: chomp($answer);
                    392: &logthis("Pong reply for $conserver: >$answer<");
                    393: # ----------------------------------------------------------- Initialize cipher
                    394: 
1.18      www       395: &status("Initialize cipher: $conserver");
1.1       albertel  396: print $remotesock "ekey\n";
                    397: my $buildkey=<$remotesock>;
                    398: my $key=$conserver.$perlvar{'lonHostID'};
                    399: $key=~tr/a-z/A-Z/;
                    400: $key=~tr/G-P/0-9/;
                    401: $key=~tr/Q-Z/0-9/;
                    402: $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
                    403: $key=substr($key,0,32);
                    404: my $cipherkey=pack("H32",$key);
                    405: if ($cipher=new IDEA $cipherkey) {
1.12      harris41  406:    &logthis("Secure connection initialized: $conserver");
1.1       albertel  407: } else {
1.5       www       408:    my $st=120+int(rand(240));
                    409:    &logthis(
                    410:      "<font color=blue>WARNING: ".
                    411:      "Could not establish secure connection, $conserver ($st secs)!</font>");
                    412:    sleep($st);
                    413:    exit;
1.1       albertel  414: }
                    415: 
1.3       www       416: # ----------------------------------------- We're online, send delayed messages
1.18      www       417:     &status("Checking for delayed messages");
1.4       www       418:     my @allbuffered;
1.3       www       419:     my $path="$perlvar{'lonSockDir'}/delayed";
1.4       www       420:     opendir(DIRHANDLE,$path);
                    421:     @allbuffered=grep /\.$conserver$/, readdir DIRHANDLE;
                    422:     closedir(DIRHANDLE);
1.3       www       423:     my $dfname;
1.4       www       424:     map {
1.18      www       425:         &status("Sending delayed $conserver $_");
1.4       www       426:         $dfname="$path/$_";
                    427:         &logthis($dfname);
1.3       www       428:         my $wcmd;
                    429:         {
                    430:          my $dfh=IO::File->new($dfname);
1.4       www       431:          $cmd=<$dfh>;
1.3       www       432:         }
                    433:         chomp($cmd);
                    434:         my $bcmd=$cmd;
                    435:         if ($cmd =~ /^encrypt\:/) {
                    436: 	    my $rcmd=$cmd;
                    437:             $rcmd =~ s/^encrypt\://;
                    438:             chomp($rcmd);
                    439:             my $cmdlength=length($rcmd);
                    440:             $rcmd.="         ";
                    441:             my $encrequest='';
                    442:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                    443:                 $encrequest.=
                    444:                     unpack("H16",$cipher->encrypt(substr($rcmd,$encidx,8)));
                    445:             }
                    446:             $cmd="enc:$cmdlength:$encrequest\n";
                    447:         }
1.20    ! www       448:     $SIG{ALRM}=sub { die "timeout" };
        !           449:     $SIG{__DIE__}='DEFAULT';
        !           450:     eval {
        !           451:         alarm(60);
1.3       www       452:         print $remotesock "$cmd\n";
                    453:         $answer=<$remotesock>;
                    454: 	chomp($answer);
1.20    ! www       455:         alarm(0);
        !           456:     };
        !           457:     $SIG{ALRM}='DEFAULT';
        !           458:     $SIG{__DIE__}=\&catchexception;
        !           459: 
        !           460:         if (($answer ne '') && ($@!~/timeout/)) {
1.3       www       461: 	    unlink("$dfname");
1.4       www       462:             &logthis("Delayed $cmd to $conserver: >$answer<");
1.3       www       463:             &logperm("S:$conserver:$bcmd");
                    464:         }        
1.4       www       465:     } @allbuffered;
1.1       albertel  466: 
                    467: # ------------------------------------------------------- Listen to UNIX socket
1.18      www       468: &status("Opening socket $conserver");
1.1       albertel  469: unless (
                    470:   $server = IO::Socket::UNIX->new(Local  => $port,
                    471:                                   Type   => SOCK_STREAM,
                    472:                                   Listen => 10 )
1.5       www       473:    ) { 
                    474:        my $st=120+int(rand(240));
                    475:        &logthis(
                    476:          "<font color=blue>WARNING: ".
                    477:          "Can't make server socket $conserver ($st secs): $@</font>");
                    478:        sleep($st);
1.1       albertel  479:        exit; 
                    480:      };
                    481: 
                    482: # -----------------------------------------------------------------------------
                    483: 
1.5       www       484: &logthis("<font color=green>$conserver online</font>");
                    485: 
                    486: # -----------------------------------------------------------------------------
1.1       albertel  487: # begin with empty buffers
                    488: %inbuffer  = ();
                    489: %outbuffer = ();
                    490: %ready     = ();
                    491: 
                    492: tie %ready, 'Tie::RefHash';
                    493: 
                    494: nonblock($server);
                    495: $select = IO::Select->new($server);
                    496: 
                    497: # Main loop: check reads/accepts, check writes, check ready to process
                    498: while (1) {
                    499:     my $client;
                    500:     my $rv;
                    501:     my $data;
                    502: 
                    503:     # check for new information on the connections we have
                    504: 
                    505:     # anything to read or accept?
1.16      www       506:     foreach $client ($select->can_read(0.1)) {
1.1       albertel  507: 
                    508:         if ($client == $server) {
                    509:             # accept a new connection
1.18      www       510:             &status("Accept new connection: $conserver");
1.1       albertel  511:             $client = $server->accept();
                    512:             $select->add($client);
                    513:             nonblock($client);
                    514:         } else {
                    515:             # read data
                    516:             $data = '';
                    517:             $rv   = $client->recv($data, POSIX::BUFSIZ, 0);
                    518: 
                    519:             unless (defined($rv) && length $data) {
                    520:                 # This would be the end of file, so close the client
                    521:                 delete $inbuffer{$client};
                    522:                 delete $outbuffer{$client};
                    523:                 delete $ready{$client};
                    524: 
1.18      www       525:                 &status("Idle $conserver");
1.1       albertel  526:                 $select->remove($client);
                    527:                 close $client;
                    528:                 next;
                    529:             }
                    530: 
                    531:             $inbuffer{$client} .= $data;
                    532: 
                    533:             # test whether the data in the buffer or the data we
                    534:             # just read means there is a complete request waiting
                    535:             # to be fulfilled.  If there is, set $ready{$client}
                    536:             # to the requests waiting to be fulfilled.
                    537:             while ($inbuffer{$client} =~ s/(.*\n)//) {
                    538:                 push( @{$ready{$client}}, $1 );
                    539:             }
                    540:         }
                    541:     }
                    542: 
                    543:     # Any complete requests to process?
                    544:     foreach $client (keys %ready) {
                    545:         handle($client);
                    546:     }
                    547: 
                    548:     # Buffers to flush?
                    549:     foreach $client ($select->can_write(1)) {
                    550:         # Skip this client if we have nothing to say
                    551:         next unless exists $outbuffer{$client};
                    552: 
                    553:         $rv = $client->send($outbuffer{$client}, 0);
                    554:         unless (defined $rv) {
                    555:             # Whine, but move on.
1.15      www       556:             &logthis("I was told I could write, but I can't.\n");
1.1       albertel  557:             next;
                    558:         }
1.15      www       559:         $errno=$!;
1.1       albertel  560:         if (($rv == length $outbuffer{$client}) ||
1.15      www       561:             ($errno == POSIX::EWOULDBLOCK) || ($errno == 0)) {
1.1       albertel  562:             substr($outbuffer{$client}, 0, $rv) = '';
                    563:             delete $outbuffer{$client} unless length $outbuffer{$client};
                    564:         } else {
                    565:             # Couldn't write all the data, and it wasn't because
                    566:             # it would have blocked.  Shutdown and move on.
1.15      www       567: 
                    568: 	    &logthis("Dropping data with ".$errno.": ".
                    569:                      length($outbuffer{$client}).", $rv");
                    570: 
1.1       albertel  571:             delete $inbuffer{$client};
                    572:             delete $outbuffer{$client};
                    573:             delete $ready{$client};
                    574: 
                    575:             $select->remove($client);
                    576:             close($client);
                    577:             next;
                    578:         }
                    579:     }
                    580: }
                    581: }
                    582: 
                    583: # ------------------------------------------------------- End of make_new_child
                    584: 
                    585: # handle($socket) deals with all pending requests for $client
                    586: sub handle {
                    587:     # requests are in $ready{$client}
                    588:     # send output to $outbuffer{$client}
                    589:     my $client = shift;
                    590:     my $request;
                    591: 
                    592:     foreach $request (@{$ready{$client}}) {
                    593: # ============================================================= Process request
                    594:         # $request is the text of the request
                    595:         # put text of reply into $outbuffer{$client}
                    596: # -----------------------------------------------------------------------------
                    597:         if ($request =~ /^encrypt\:/) {
                    598: 	    my $cmd=$request;
                    599:             $cmd =~ s/^encrypt\://;
                    600:             chomp($cmd);
                    601:             my $cmdlength=length($cmd);
                    602:             $cmd.="         ";
                    603:             my $encrequest='';
                    604:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                    605:                 $encrequest.=
                    606:                     unpack("H16",$cipher->encrypt(substr($cmd,$encidx,8)));
                    607:             }
                    608:             $request="enc:$cmdlength:$encrequest\n";
                    609:         }
1.19      www       610: # --------------------------------------------------------------- Main exchange
                    611:     $SIG{ALRM}=sub { die "timeout" };
                    612:     $SIG{__DIE__}='DEFAULT';
                    613:     eval {
                    614:         alarm(300);
1.18      www       615:         &status("Sending $conserver: $request");
1.1       albertel  616:         print $remotesock "$request";
1.18      www       617:         &status("Waiting for reply from $conserver: $request");
1.1       albertel  618:         $answer=<$remotesock>;
1.18      www       619:         &status("Received reply: $request");
1.19      www       620:         alarm(0);
                    621:     };
                    622:     if ($@=~/timeout/) { 
                    623:        $answer='';
                    624:        &logthis(
                    625:         "<font color=red>CRITICAL: Timeout $conserver: $request</font>");
                    626:     }  
                    627:     $SIG{ALRM}='DEFAULT';
                    628:     $SIG{__DIE__}=\&catchexception;
                    629: 
                    630: 
1.1       albertel  631:         if ($answer) {
                    632: 	   if ($answer =~ /^enc/) {
                    633:                my ($cmd,$cmdlength,$encinput)=split(/:/,$answer);
                    634:                chomp($encinput);
                    635: 	       $answer='';
                    636:                for (my $encidx=0;$encidx<length($encinput);$encidx+=16) {
                    637:                   $answer.=$cipher->decrypt(
                    638:                    pack("H16",substr($encinput,$encidx,16))
                    639:                   );
                    640: 	       }
                    641: 	      $answer=substr($answer,0,$cmdlength);
                    642: 	      $answer.="\n";
                    643: 	   }
                    644:            $outbuffer{$client} .= $answer;
                    645:         } else {
                    646:            $outbuffer{$client} .= "con_lost\n";
                    647:         }
                    648: 
                    649: # ===================================================== Done processing request
                    650:     }
                    651:     delete $ready{$client};
1.18      www       652:     &status("Completed $conserver: $request");
1.1       albertel  653: # -------------------------------------------------------------- End non-forker
                    654: }
                    655: # ---------------------------------------------------------- End make_new_child
                    656: }
                    657: 
                    658: # nonblock($socket) puts socket into nonblocking mode
                    659: sub nonblock {
                    660:     my $socket = shift;
                    661:     my $flags;
                    662: 
                    663:     
                    664:     $flags = fcntl($socket, F_GETFL, 0)
1.11      harris41  665:             or die "Can't get flags for socket: $!\n";
1.1       albertel  666:     fcntl($socket, F_SETFL, $flags | O_NONBLOCK)
1.11      harris41  667:             or die "Can't make socket nonblocking: $!\n";
1.8       harris41  668: }
1.1       albertel  669: 

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>