Annotation of loncom/lonc, revision 1.19

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:      };
                    355: # --------------------------------------- Send a ping to make other end do USR1
1.18      www       356: 
                    357: &status("Init dialogue: $conserver");
                    358: 
1.2       www       359: print $remotesock "init\n";
                    360: $answer=<$remotesock>;
                    361: print $remotesock "$answer";
1.1       albertel  362: $answer=<$remotesock>;
                    363: chomp($answer);
1.2       www       364: &logthis("Init reply for $conserver: >$answer<");
1.17      www       365: if ($answer ne 'ok') {
                    366:        my $st=120+int(rand(240));
                    367:        &logthis(
                    368: "<font color=blue>WARNING: Init failed $conserver ($st secs)</font>");
                    369:        sleep($st);
                    370:        exit; 
                    371: }
1.1       albertel  372: sleep 5;
1.18      www       373: &status("Ponging $conserver");
1.1       albertel  374: print $remotesock "pong\n";
                    375: $answer=<$remotesock>;
                    376: chomp($answer);
                    377: &logthis("Pong reply for $conserver: >$answer<");
                    378: # ----------------------------------------------------------- Initialize cipher
                    379: 
1.18      www       380: &status("Initialize cipher: $conserver");
1.1       albertel  381: print $remotesock "ekey\n";
                    382: my $buildkey=<$remotesock>;
                    383: my $key=$conserver.$perlvar{'lonHostID'};
                    384: $key=~tr/a-z/A-Z/;
                    385: $key=~tr/G-P/0-9/;
                    386: $key=~tr/Q-Z/0-9/;
                    387: $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
                    388: $key=substr($key,0,32);
                    389: my $cipherkey=pack("H32",$key);
                    390: if ($cipher=new IDEA $cipherkey) {
1.12      harris41  391:    &logthis("Secure connection initialized: $conserver");
1.1       albertel  392: } else {
1.5       www       393:    my $st=120+int(rand(240));
                    394:    &logthis(
                    395:      "<font color=blue>WARNING: ".
                    396:      "Could not establish secure connection, $conserver ($st secs)!</font>");
                    397:    sleep($st);
                    398:    exit;
1.1       albertel  399: }
                    400: 
1.3       www       401: # ----------------------------------------- We're online, send delayed messages
1.18      www       402:     &status("Checking for delayed messages");
1.4       www       403:     my @allbuffered;
1.3       www       404:     my $path="$perlvar{'lonSockDir'}/delayed";
1.4       www       405:     opendir(DIRHANDLE,$path);
                    406:     @allbuffered=grep /\.$conserver$/, readdir DIRHANDLE;
                    407:     closedir(DIRHANDLE);
1.3       www       408:     my $dfname;
1.4       www       409:     map {
1.18      www       410:         &status("Sending delayed $conserver $_");
1.4       www       411:         $dfname="$path/$_";
                    412:         &logthis($dfname);
1.3       www       413:         my $wcmd;
                    414:         {
                    415:          my $dfh=IO::File->new($dfname);
1.4       www       416:          $cmd=<$dfh>;
1.3       www       417:         }
                    418:         chomp($cmd);
                    419:         my $bcmd=$cmd;
                    420:         if ($cmd =~ /^encrypt\:/) {
                    421: 	    my $rcmd=$cmd;
                    422:             $rcmd =~ s/^encrypt\://;
                    423:             chomp($rcmd);
                    424:             my $cmdlength=length($rcmd);
                    425:             $rcmd.="         ";
                    426:             my $encrequest='';
                    427:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                    428:                 $encrequest.=
                    429:                     unpack("H16",$cipher->encrypt(substr($rcmd,$encidx,8)));
                    430:             }
                    431:             $cmd="enc:$cmdlength:$encrequest\n";
                    432:         }
                    433: 
                    434:         print $remotesock "$cmd\n";
                    435:         $answer=<$remotesock>;
                    436: 	chomp($answer);
                    437:         if ($answer ne '') {
                    438: 	    unlink("$dfname");
1.4       www       439:             &logthis("Delayed $cmd to $conserver: >$answer<");
1.3       www       440:             &logperm("S:$conserver:$bcmd");
                    441:         }        
1.4       www       442:     } @allbuffered;
1.1       albertel  443: 
                    444: # ------------------------------------------------------- Listen to UNIX socket
1.18      www       445: &status("Opening socket $conserver");
1.1       albertel  446: unless (
                    447:   $server = IO::Socket::UNIX->new(Local  => $port,
                    448:                                   Type   => SOCK_STREAM,
                    449:                                   Listen => 10 )
1.5       www       450:    ) { 
                    451:        my $st=120+int(rand(240));
                    452:        &logthis(
                    453:          "<font color=blue>WARNING: ".
                    454:          "Can't make server socket $conserver ($st secs): $@</font>");
                    455:        sleep($st);
1.1       albertel  456:        exit; 
                    457:      };
                    458: 
                    459: # -----------------------------------------------------------------------------
                    460: 
1.5       www       461: &logthis("<font color=green>$conserver online</font>");
                    462: 
                    463: # -----------------------------------------------------------------------------
1.1       albertel  464: # begin with empty buffers
                    465: %inbuffer  = ();
                    466: %outbuffer = ();
                    467: %ready     = ();
                    468: 
                    469: tie %ready, 'Tie::RefHash';
                    470: 
                    471: nonblock($server);
                    472: $select = IO::Select->new($server);
                    473: 
                    474: # Main loop: check reads/accepts, check writes, check ready to process
                    475: while (1) {
                    476:     my $client;
                    477:     my $rv;
                    478:     my $data;
                    479: 
                    480:     # check for new information on the connections we have
                    481: 
                    482:     # anything to read or accept?
1.16      www       483:     foreach $client ($select->can_read(0.1)) {
1.1       albertel  484: 
                    485:         if ($client == $server) {
                    486:             # accept a new connection
1.18      www       487:             &status("Accept new connection: $conserver");
1.1       albertel  488:             $client = $server->accept();
                    489:             $select->add($client);
                    490:             nonblock($client);
                    491:         } else {
                    492:             # read data
                    493:             $data = '';
                    494:             $rv   = $client->recv($data, POSIX::BUFSIZ, 0);
                    495: 
                    496:             unless (defined($rv) && length $data) {
                    497:                 # This would be the end of file, so close the client
                    498:                 delete $inbuffer{$client};
                    499:                 delete $outbuffer{$client};
                    500:                 delete $ready{$client};
                    501: 
1.18      www       502:                 &status("Idle $conserver");
1.1       albertel  503:                 $select->remove($client);
                    504:                 close $client;
                    505:                 next;
                    506:             }
                    507: 
                    508:             $inbuffer{$client} .= $data;
                    509: 
                    510:             # test whether the data in the buffer or the data we
                    511:             # just read means there is a complete request waiting
                    512:             # to be fulfilled.  If there is, set $ready{$client}
                    513:             # to the requests waiting to be fulfilled.
                    514:             while ($inbuffer{$client} =~ s/(.*\n)//) {
                    515:                 push( @{$ready{$client}}, $1 );
                    516:             }
                    517:         }
                    518:     }
                    519: 
                    520:     # Any complete requests to process?
                    521:     foreach $client (keys %ready) {
                    522:         handle($client);
                    523:     }
                    524: 
                    525:     # Buffers to flush?
                    526:     foreach $client ($select->can_write(1)) {
                    527:         # Skip this client if we have nothing to say
                    528:         next unless exists $outbuffer{$client};
                    529: 
                    530:         $rv = $client->send($outbuffer{$client}, 0);
                    531:         unless (defined $rv) {
                    532:             # Whine, but move on.
1.15      www       533:             &logthis("I was told I could write, but I can't.\n");
1.1       albertel  534:             next;
                    535:         }
1.15      www       536:         $errno=$!;
1.1       albertel  537:         if (($rv == length $outbuffer{$client}) ||
1.15      www       538:             ($errno == POSIX::EWOULDBLOCK) || ($errno == 0)) {
1.1       albertel  539:             substr($outbuffer{$client}, 0, $rv) = '';
                    540:             delete $outbuffer{$client} unless length $outbuffer{$client};
                    541:         } else {
                    542:             # Couldn't write all the data, and it wasn't because
                    543:             # it would have blocked.  Shutdown and move on.
1.15      www       544: 
                    545: 	    &logthis("Dropping data with ".$errno.": ".
                    546:                      length($outbuffer{$client}).", $rv");
                    547: 
1.1       albertel  548:             delete $inbuffer{$client};
                    549:             delete $outbuffer{$client};
                    550:             delete $ready{$client};
                    551: 
                    552:             $select->remove($client);
                    553:             close($client);
                    554:             next;
                    555:         }
                    556:     }
                    557: }
                    558: }
                    559: 
                    560: # ------------------------------------------------------- End of make_new_child
                    561: 
                    562: # handle($socket) deals with all pending requests for $client
                    563: sub handle {
                    564:     # requests are in $ready{$client}
                    565:     # send output to $outbuffer{$client}
                    566:     my $client = shift;
                    567:     my $request;
                    568: 
                    569:     foreach $request (@{$ready{$client}}) {
                    570: # ============================================================= Process request
                    571:         # $request is the text of the request
                    572:         # put text of reply into $outbuffer{$client}
                    573: # -----------------------------------------------------------------------------
                    574:         if ($request =~ /^encrypt\:/) {
                    575: 	    my $cmd=$request;
                    576:             $cmd =~ s/^encrypt\://;
                    577:             chomp($cmd);
                    578:             my $cmdlength=length($cmd);
                    579:             $cmd.="         ";
                    580:             my $encrequest='';
                    581:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                    582:                 $encrequest.=
                    583:                     unpack("H16",$cipher->encrypt(substr($cmd,$encidx,8)));
                    584:             }
                    585:             $request="enc:$cmdlength:$encrequest\n";
                    586:         }
1.19    ! www       587: # --------------------------------------------------------------- Main exchange
        !           588:     $SIG{ALRM}=sub { die "timeout" };
        !           589:     $SIG{__DIE__}='DEFAULT';
        !           590:     eval {
        !           591:         alarm(300);
1.18      www       592:         &status("Sending $conserver: $request");
1.1       albertel  593:         print $remotesock "$request";
1.18      www       594:         &status("Waiting for reply from $conserver: $request");
1.1       albertel  595:         $answer=<$remotesock>;
1.18      www       596:         &status("Received reply: $request");
1.19    ! www       597:         alarm(0);
        !           598:     };
        !           599:     if ($@=~/timeout/) { 
        !           600:        $answer='';
        !           601:        &logthis(
        !           602:         "<font color=red>CRITICAL: Timeout $conserver: $request</font>");
        !           603:     }  
        !           604:     $SIG{ALRM}='DEFAULT';
        !           605:     $SIG{__DIE__}=\&catchexception;
        !           606: 
        !           607: 
1.1       albertel  608:         if ($answer) {
                    609: 	   if ($answer =~ /^enc/) {
                    610:                my ($cmd,$cmdlength,$encinput)=split(/:/,$answer);
                    611:                chomp($encinput);
                    612: 	       $answer='';
                    613:                for (my $encidx=0;$encidx<length($encinput);$encidx+=16) {
                    614:                   $answer.=$cipher->decrypt(
                    615:                    pack("H16",substr($encinput,$encidx,16))
                    616:                   );
                    617: 	       }
                    618: 	      $answer=substr($answer,0,$cmdlength);
                    619: 	      $answer.="\n";
                    620: 	   }
                    621:            $outbuffer{$client} .= $answer;
                    622:         } else {
                    623:            $outbuffer{$client} .= "con_lost\n";
                    624:         }
                    625: 
                    626: # ===================================================== Done processing request
                    627:     }
                    628:     delete $ready{$client};
1.18      www       629:     &status("Completed $conserver: $request");
1.1       albertel  630: # -------------------------------------------------------------- End non-forker
                    631: }
                    632: # ---------------------------------------------------------- End make_new_child
                    633: }
                    634: 
                    635: # nonblock($socket) puts socket into nonblocking mode
                    636: sub nonblock {
                    637:     my $socket = shift;
                    638:     my $flags;
                    639: 
                    640:     
                    641:     $flags = fcntl($socket, F_GETFL, 0)
1.11      harris41  642:             or die "Can't get flags for socket: $!\n";
1.1       albertel  643:     fcntl($socket, F_SETFL, $flags | O_NONBLOCK)
1.11      harris41  644:             or die "Can't make socket nonblocking: $!\n";
1.8       harris41  645: }
1.1       albertel  646: 

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