File:  [LON-CAPA] / loncom / Attic / lonc
Revision 1.27: download - view: text, annotated - select for diffs
Tue Feb 19 21:49:12 2002 UTC (22 years, 3 months ago) by www
Branches: MAIN
CVS tags: HEAD
Removing old garbage

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

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