Annotation of loncom/lonc, revision 1.21

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.21    ! www        19: # 03/14/01,03/15,06/12,11/26,11/27,11/28 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.21    ! www       185: 
        !           186: 
1.19      www       187:     $SIG{ALRM}=sub { die "timeout" };
                    188:     $SIG{__DIE__}='DEFAULT';
                    189:     eval {
                    190:      alarm(10);
                    191:      print $sclient "$cmd\n";
1.21    ! www       192:      $answer=<$sclient>;
1.19      www       193:      chomp($answer);
                    194:      alarm(0);
                    195:     };
                    196:     if ((!$answer) || ($@=~/timeout/)) { $answer="con_lost"; }
                    197:     $SIG{ALRM}='DEFAULT';
                    198:     $SIG{__DIE__}=\&catchexception;
1.1       albertel  199:  } else { $answer='self_reply'; }
                    200:  return $answer;
                    201: }
                    202: 
                    203: # --------------------------------------------------------------------- Logging
                    204: 
                    205: sub logthis {
                    206:     my $message=shift;
                    207:     my $execdir=$perlvar{'lonDaemons'};
                    208:     my $fh=IO::File->new(">>$execdir/logs/lonc.log");
                    209:     my $now=time;
                    210:     my $local=localtime($now);
1.18      www       211:     $lastlog=$local.': '.$message;
1.1       albertel  212:     print $fh "$local ($$): $message\n";
                    213: }
                    214: 
1.3       www       215: 
                    216: sub logperm {
                    217:     my $message=shift;
                    218:     my $execdir=$perlvar{'lonDaemons'};
                    219:     my $now=time;
                    220:     my $local=localtime($now);
                    221:     my $fh=IO::File->new(">>$execdir/logs/lonnet.perm.log");
                    222:     print $fh "$now:$message:$local\n";
                    223: }
1.18      www       224: # ------------------------------------------------------------------ Log status
                    225: 
                    226: sub logstatus {
                    227:     my $docdir=$perlvar{'lonDocRoot'};
                    228:     my $fh=IO::File->new(">>$docdir/lon-status/loncstatus.txt");
                    229:     print $fh $$."\t".$status."\t".$lastlog."\n";
                    230: }
                    231: 
                    232: sub initnewstatus {
                    233:     my $docdir=$perlvar{'lonDocRoot'};
                    234:     my $fh=IO::File->new(">$docdir/lon-status/loncstatus.txt");
                    235:     my $now=time;
                    236:     my $local=localtime($now);
                    237:     print $fh "LONC status $local - parent $$\n\n";
                    238: }
                    239: 
                    240: # -------------------------------------------------------------- Status setting
                    241: 
                    242: sub status {
                    243:     my $what=shift;
                    244:     my $now=time;
                    245:     my $local=localtime($now);
                    246:     $status=$local.': '.$what;
                    247: }
                    248: 
1.3       www       249: 
1.1       albertel  250: # ---------------------------------------------------- Fork once and dissociate
                    251: 
                    252: $fpid=fork;
                    253: exit if $fpid;
1.11      harris41  254: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel  255: 
1.11      harris41  256: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel  257: 
                    258: # ------------------------------------------------------- Write our PID on disk
                    259: 
                    260: $execdir=$perlvar{'lonDaemons'};
                    261: open (PIDSAVE,">$execdir/logs/lonc.pid");
                    262: print PIDSAVE "$$\n";
                    263: close(PIDSAVE);
1.5       www       264: &logthis("<font color=red>CRITICAL: ---------- Starting ----------</font>");
1.1       albertel  265: 
                    266: # ----------------------------- Ignore signals generated during initial startup
                    267: $SIG{HUP}=$SIG{USR1}='IGNORE';
                    268: # ------------------------------------------------------- Now we are on our own
                    269:     
                    270: # Fork off our children, one for every server
                    271: 
1.18      www       272: &status("Forking ...");
                    273: 
1.1       albertel  274: foreach $thisserver (keys %hostip) {
                    275:     make_new_child($thisserver);
                    276: }
                    277: 
                    278: &logthis("Done starting initial servers");
                    279: # ----------------------------------------------------- Install signal handlers
                    280: 
                    281: $SIG{CHLD} = \&REAPER;
                    282: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                    283: $SIG{HUP}  = \&HUPSMAN;
                    284: $SIG{USR1} = \&USRMAN;
                    285: 
                    286: # And maintain the population.
                    287: while (1) {
1.18      www       288:     &status("Sleeping");
1.1       albertel  289:     sleep;                          # wait for a signal (i.e., child's death)
                    290:                                     # See who died and start new one
1.18      www       291:     &status("Woke up");
1.1       albertel  292:     foreach $thisserver (keys %hostip) {
                    293:         if (!$childpid{$thisserver}) {
1.17      www       294: 	    if ($childatt{$thisserver}<$childmaxattempts) {
1.6       www       295: 	       $childatt{$thisserver}++;
1.5       www       296:                &logthis(
                    297:    "<font color=yellow>INFO: Trying to reconnect for $thisserver "
1.6       www       298:   ."($childatt{$thisserver} of $childmaxattempts attempts)</font>"); 
1.1       albertel  299:                make_new_child($thisserver);
                    300: 	    }
                    301:         }       
                    302:     }
                    303: }
                    304: 
                    305: 
                    306: sub make_new_child {
                    307:    
                    308:     my $conserver=shift;
                    309:     my $pid;
                    310:     my $sigset;
                    311:     &logthis("Attempting to start child for server $conserver");
                    312:     # block signal for fork
                    313:     $sigset = POSIX::SigSet->new(SIGINT);
                    314:     sigprocmask(SIG_BLOCK, $sigset)
1.11      harris41  315:         or die "Can't block SIGINT for fork: $!\n";
1.1       albertel  316:     
1.11      harris41  317:     die "fork: $!" unless defined ($pid = fork);
1.1       albertel  318:     
                    319:     if ($pid) {
                    320:         # Parent records the child's birth and returns.
                    321:         sigprocmask(SIG_UNBLOCK, $sigset)
1.11      harris41  322:             or die "Can't unblock SIGINT for fork: $!\n";
1.1       albertel  323:         $children{$pid} = $conserver;
                    324:         $childpid{$conserver} = $pid;
                    325:         return;
                    326:     } else {
                    327:         # Child can *not* return from this subroutine.
                    328:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
1.18      www       329:         $SIG{USR1}= \&logstatus;
                    330:    
1.1       albertel  331:         # unblock signals
                    332:         sigprocmask(SIG_UNBLOCK, $sigset)
1.11      harris41  333:             or die "Can't unblock SIGINT for fork: $!\n";
1.1       albertel  334: 
                    335: # ----------------------------- This is the modified main program of non-forker
                    336: 
                    337: $port = "$perlvar{'lonSockDir'}/$conserver";
                    338: 
                    339: unlink($port);
1.18      www       340: 
1.1       albertel  341: # ---------------------------------------------------- Client to network server
1.18      www       342: 
                    343: &status("Opening TCP: $conserver");
                    344: 
1.1       albertel  345: unless (
                    346:   $remotesock = IO::Socket::INET->new(PeerAddr => $hostip{$conserver},
                    347:                                       PeerPort => $perlvar{'londPort'},
                    348:                                       Proto    => "tcp",
                    349:                                       Type     => SOCK_STREAM)
1.5       www       350:    ) { 
                    351:        my $st=120+int(rand(240));
                    352:        &logthis(
                    353: "<font color=blue>WARNING: Couldn't connect $conserver ($st secs): $@</font>");
                    354:        sleep($st);
1.1       albertel  355:        exit; 
                    356:      };
1.20      www       357: # ----------------------------------------------------------------- Init dialog
1.18      www       358: 
                    359: &status("Init dialogue: $conserver");
                    360: 
1.20      www       361:      $SIG{ALRM}=sub { die "timeout" };
                    362:      $SIG{__DIE__}='DEFAULT';
                    363:      eval {
                    364:          alarm(60);
1.2       www       365: print $remotesock "init\n";
                    366: $answer=<$remotesock>;
                    367: print $remotesock "$answer";
1.1       albertel  368: $answer=<$remotesock>;
                    369: chomp($answer);
1.20      www       370:           alarm(0);
                    371:      };
                    372:      $SIG{ALRM}='DEFAULT';
                    373:      $SIG{__DIE__}=\&catchexception;
                    374:  
                    375:      if ($@=~/timeout/) {
                    376: 	 &logthis("Timed out during init: $conserver");
                    377:          exit;
                    378:      }
                    379: 
                    380: 
1.2       www       381: &logthis("Init reply for $conserver: >$answer<");
1.17      www       382: if ($answer ne 'ok') {
                    383:        my $st=120+int(rand(240));
                    384:        &logthis(
                    385: "<font color=blue>WARNING: Init failed $conserver ($st secs)</font>");
                    386:        sleep($st);
                    387:        exit; 
                    388: }
1.1       albertel  389: sleep 5;
1.18      www       390: &status("Ponging $conserver");
1.1       albertel  391: print $remotesock "pong\n";
                    392: $answer=<$remotesock>;
                    393: chomp($answer);
                    394: &logthis("Pong reply for $conserver: >$answer<");
                    395: # ----------------------------------------------------------- Initialize cipher
                    396: 
1.18      www       397: &status("Initialize cipher: $conserver");
1.1       albertel  398: print $remotesock "ekey\n";
                    399: my $buildkey=<$remotesock>;
                    400: my $key=$conserver.$perlvar{'lonHostID'};
                    401: $key=~tr/a-z/A-Z/;
                    402: $key=~tr/G-P/0-9/;
                    403: $key=~tr/Q-Z/0-9/;
                    404: $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
                    405: $key=substr($key,0,32);
                    406: my $cipherkey=pack("H32",$key);
                    407: if ($cipher=new IDEA $cipherkey) {
1.12      harris41  408:    &logthis("Secure connection initialized: $conserver");
1.1       albertel  409: } else {
1.5       www       410:    my $st=120+int(rand(240));
                    411:    &logthis(
                    412:      "<font color=blue>WARNING: ".
                    413:      "Could not establish secure connection, $conserver ($st secs)!</font>");
                    414:    sleep($st);
                    415:    exit;
1.1       albertel  416: }
                    417: 
1.3       www       418: # ----------------------------------------- We're online, send delayed messages
1.18      www       419:     &status("Checking for delayed messages");
1.4       www       420:     my @allbuffered;
1.3       www       421:     my $path="$perlvar{'lonSockDir'}/delayed";
1.4       www       422:     opendir(DIRHANDLE,$path);
                    423:     @allbuffered=grep /\.$conserver$/, readdir DIRHANDLE;
                    424:     closedir(DIRHANDLE);
1.3       www       425:     my $dfname;
1.4       www       426:     map {
1.18      www       427:         &status("Sending delayed $conserver $_");
1.4       www       428:         $dfname="$path/$_";
                    429:         &logthis($dfname);
1.3       www       430:         my $wcmd;
                    431:         {
                    432:          my $dfh=IO::File->new($dfname);
1.4       www       433:          $cmd=<$dfh>;
1.3       www       434:         }
                    435:         chomp($cmd);
                    436:         my $bcmd=$cmd;
                    437:         if ($cmd =~ /^encrypt\:/) {
                    438: 	    my $rcmd=$cmd;
                    439:             $rcmd =~ s/^encrypt\://;
                    440:             chomp($rcmd);
                    441:             my $cmdlength=length($rcmd);
                    442:             $rcmd.="         ";
                    443:             my $encrequest='';
                    444:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                    445:                 $encrequest.=
                    446:                     unpack("H16",$cipher->encrypt(substr($rcmd,$encidx,8)));
                    447:             }
                    448:             $cmd="enc:$cmdlength:$encrequest\n";
                    449:         }
1.20      www       450:     $SIG{ALRM}=sub { die "timeout" };
                    451:     $SIG{__DIE__}='DEFAULT';
                    452:     eval {
                    453:         alarm(60);
1.3       www       454:         print $remotesock "$cmd\n";
                    455:         $answer=<$remotesock>;
                    456: 	chomp($answer);
1.20      www       457:         alarm(0);
                    458:     };
                    459:     $SIG{ALRM}='DEFAULT';
                    460:     $SIG{__DIE__}=\&catchexception;
                    461: 
                    462:         if (($answer ne '') && ($@!~/timeout/)) {
1.3       www       463: 	    unlink("$dfname");
1.4       www       464:             &logthis("Delayed $cmd to $conserver: >$answer<");
1.3       www       465:             &logperm("S:$conserver:$bcmd");
                    466:         }        
1.4       www       467:     } @allbuffered;
1.1       albertel  468: 
                    469: # ------------------------------------------------------- Listen to UNIX socket
1.18      www       470: &status("Opening socket $conserver");
1.1       albertel  471: unless (
                    472:   $server = IO::Socket::UNIX->new(Local  => $port,
                    473:                                   Type   => SOCK_STREAM,
                    474:                                   Listen => 10 )
1.5       www       475:    ) { 
                    476:        my $st=120+int(rand(240));
                    477:        &logthis(
                    478:          "<font color=blue>WARNING: ".
                    479:          "Can't make server socket $conserver ($st secs): $@</font>");
                    480:        sleep($st);
1.1       albertel  481:        exit; 
                    482:      };
                    483: 
                    484: # -----------------------------------------------------------------------------
                    485: 
1.5       www       486: &logthis("<font color=green>$conserver online</font>");
                    487: 
                    488: # -----------------------------------------------------------------------------
1.1       albertel  489: # begin with empty buffers
                    490: %inbuffer  = ();
                    491: %outbuffer = ();
                    492: %ready     = ();
                    493: 
                    494: tie %ready, 'Tie::RefHash';
                    495: 
                    496: nonblock($server);
                    497: $select = IO::Select->new($server);
                    498: 
                    499: # Main loop: check reads/accepts, check writes, check ready to process
                    500: while (1) {
                    501:     my $client;
                    502:     my $rv;
                    503:     my $data;
                    504: 
                    505:     # check for new information on the connections we have
                    506: 
                    507:     # anything to read or accept?
1.16      www       508:     foreach $client ($select->can_read(0.1)) {
1.1       albertel  509: 
                    510:         if ($client == $server) {
                    511:             # accept a new connection
1.18      www       512:             &status("Accept new connection: $conserver");
1.1       albertel  513:             $client = $server->accept();
                    514:             $select->add($client);
                    515:             nonblock($client);
                    516:         } else {
                    517:             # read data
                    518:             $data = '';
                    519:             $rv   = $client->recv($data, POSIX::BUFSIZ, 0);
                    520: 
                    521:             unless (defined($rv) && length $data) {
                    522:                 # This would be the end of file, so close the client
                    523:                 delete $inbuffer{$client};
                    524:                 delete $outbuffer{$client};
                    525:                 delete $ready{$client};
                    526: 
1.18      www       527:                 &status("Idle $conserver");
1.1       albertel  528:                 $select->remove($client);
                    529:                 close $client;
                    530:                 next;
                    531:             }
                    532: 
                    533:             $inbuffer{$client} .= $data;
                    534: 
                    535:             # test whether the data in the buffer or the data we
                    536:             # just read means there is a complete request waiting
                    537:             # to be fulfilled.  If there is, set $ready{$client}
                    538:             # to the requests waiting to be fulfilled.
                    539:             while ($inbuffer{$client} =~ s/(.*\n)//) {
                    540:                 push( @{$ready{$client}}, $1 );
                    541:             }
                    542:         }
                    543:     }
                    544: 
                    545:     # Any complete requests to process?
                    546:     foreach $client (keys %ready) {
                    547:         handle($client);
                    548:     }
                    549: 
                    550:     # Buffers to flush?
                    551:     foreach $client ($select->can_write(1)) {
                    552:         # Skip this client if we have nothing to say
                    553:         next unless exists $outbuffer{$client};
                    554: 
                    555:         $rv = $client->send($outbuffer{$client}, 0);
                    556:         unless (defined $rv) {
                    557:             # Whine, but move on.
1.15      www       558:             &logthis("I was told I could write, but I can't.\n");
1.1       albertel  559:             next;
                    560:         }
1.15      www       561:         $errno=$!;
1.1       albertel  562:         if (($rv == length $outbuffer{$client}) ||
1.15      www       563:             ($errno == POSIX::EWOULDBLOCK) || ($errno == 0)) {
1.1       albertel  564:             substr($outbuffer{$client}, 0, $rv) = '';
                    565:             delete $outbuffer{$client} unless length $outbuffer{$client};
                    566:         } else {
                    567:             # Couldn't write all the data, and it wasn't because
                    568:             # it would have blocked.  Shutdown and move on.
1.15      www       569: 
                    570: 	    &logthis("Dropping data with ".$errno.": ".
                    571:                      length($outbuffer{$client}).", $rv");
                    572: 
1.1       albertel  573:             delete $inbuffer{$client};
                    574:             delete $outbuffer{$client};
                    575:             delete $ready{$client};
                    576: 
                    577:             $select->remove($client);
                    578:             close($client);
                    579:             next;
                    580:         }
                    581:     }
                    582: }
                    583: }
                    584: 
                    585: # ------------------------------------------------------- End of make_new_child
                    586: 
                    587: # handle($socket) deals with all pending requests for $client
                    588: sub handle {
                    589:     # requests are in $ready{$client}
                    590:     # send output to $outbuffer{$client}
                    591:     my $client = shift;
                    592:     my $request;
                    593: 
                    594:     foreach $request (@{$ready{$client}}) {
                    595: # ============================================================= Process request
                    596:         # $request is the text of the request
                    597:         # put text of reply into $outbuffer{$client}
                    598: # -----------------------------------------------------------------------------
                    599:         if ($request =~ /^encrypt\:/) {
                    600: 	    my $cmd=$request;
                    601:             $cmd =~ s/^encrypt\://;
                    602:             chomp($cmd);
                    603:             my $cmdlength=length($cmd);
                    604:             $cmd.="         ";
                    605:             my $encrequest='';
                    606:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                    607:                 $encrequest.=
                    608:                     unpack("H16",$cipher->encrypt(substr($cmd,$encidx,8)));
                    609:             }
                    610:             $request="enc:$cmdlength:$encrequest\n";
                    611:         }
1.19      www       612: # --------------------------------------------------------------- Main exchange
                    613:     $SIG{ALRM}=sub { die "timeout" };
                    614:     $SIG{__DIE__}='DEFAULT';
                    615:     eval {
                    616:         alarm(300);
1.18      www       617:         &status("Sending $conserver: $request");
1.1       albertel  618:         print $remotesock "$request";
1.18      www       619:         &status("Waiting for reply from $conserver: $request");
1.1       albertel  620:         $answer=<$remotesock>;
1.18      www       621:         &status("Received reply: $request");
1.19      www       622:         alarm(0);
                    623:     };
                    624:     if ($@=~/timeout/) { 
                    625:        $answer='';
                    626:        &logthis(
                    627:         "<font color=red>CRITICAL: Timeout $conserver: $request</font>");
                    628:     }  
                    629:     $SIG{ALRM}='DEFAULT';
                    630:     $SIG{__DIE__}=\&catchexception;
                    631: 
                    632: 
1.1       albertel  633:         if ($answer) {
                    634: 	   if ($answer =~ /^enc/) {
                    635:                my ($cmd,$cmdlength,$encinput)=split(/:/,$answer);
                    636:                chomp($encinput);
                    637: 	       $answer='';
                    638:                for (my $encidx=0;$encidx<length($encinput);$encidx+=16) {
                    639:                   $answer.=$cipher->decrypt(
                    640:                    pack("H16",substr($encinput,$encidx,16))
                    641:                   );
                    642: 	       }
                    643: 	      $answer=substr($answer,0,$cmdlength);
                    644: 	      $answer.="\n";
                    645: 	   }
                    646:            $outbuffer{$client} .= $answer;
                    647:         } else {
                    648:            $outbuffer{$client} .= "con_lost\n";
                    649:         }
                    650: 
                    651: # ===================================================== Done processing request
                    652:     }
                    653:     delete $ready{$client};
1.18      www       654:     &status("Completed $conserver: $request");
1.1       albertel  655: # -------------------------------------------------------------- End non-forker
                    656: }
                    657: # ---------------------------------------------------------- End make_new_child
                    658: }
                    659: 
                    660: # nonblock($socket) puts socket into nonblocking mode
                    661: sub nonblock {
                    662:     my $socket = shift;
                    663:     my $flags;
                    664: 
                    665:     
                    666:     $flags = fcntl($socket, F_GETFL, 0)
1.11      harris41  667:             or die "Can't get flags for socket: $!\n";
1.1       albertel  668:     fcntl($socket, F_SETFL, $flags | O_NONBLOCK)
1.11      harris41  669:             or die "Can't make socket nonblocking: $!\n";
1.8       harris41  670: }
1.1       albertel  671: 

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