File:  [LON-CAPA] / loncom / Attic / lonc
Revision 1.26: download - view: text, annotated - select for diffs
Tue Feb 19 21:12:22 2002 UTC (22 years, 2 months ago) by www
Branches: MAIN
CVS tags: HEAD
Testing - skip servers that do not ping.

    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.26 2002/02/19 21:12:22 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",10);
   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: }
  165: close(CONFIG);
  166: 
  167: # -------------------------------------------------------- Routines for forking
  168: 
  169: %children               = ();       # keys are current child process IDs,
  170:                                     # values are hosts
  171: %childpid               = ();       # the other way around
  172: 
  173: %childatt               = ();       # number of attempts to start server
  174:                                     # for ID
  175: 
  176: sub REAPER {                        # takes care of dead children
  177:     $SIG{CHLD} = \&REAPER;
  178:     my $pid = wait;
  179:     my $wasserver=$children{$pid};
  180:     &logthis("<font color=red>CRITICAL: "
  181:      ."Child $pid for server $wasserver died ($childatt{$wasserver})</font>");
  182:     delete $children{$pid};
  183:     delete $childpid{$wasserver};
  184:     my $port = "$perlvar{'lonSockDir'}/$wasserver";
  185:     unlink($port);
  186: }
  187: 
  188: sub HUNTSMAN {                      # signal handler for SIGINT
  189:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
  190:     foreach (keys %children) {
  191:         $wasserver=$children{$_};
  192:         &status("Closing $wasserver");
  193:         &logthis('Closing '.$wasserver.': '.&subreply('exit',$wasserver));
  194:         &status("Kill PID $_ for $wasserver");
  195: 	kill ('INT',$_);
  196:     }
  197:     my $execdir=$perlvar{'lonDaemons'};
  198:     unlink("$execdir/logs/lonc.pid");
  199:     &logthis("<font color=red>CRITICAL: Shutting down</font>");
  200:     exit;                           # clean up with dignity
  201: }
  202: 
  203: sub HUPSMAN {                      # signal handler for SIGHUP
  204:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
  205:     foreach (keys %children) {
  206:         $wasserver=$children{$_};
  207:         &status("Closing $wasserver");
  208:         &logthis('Closing '.$wasserver.': '.&subreply('exit',$wasserver));
  209:         &status("Kill PID $_ for $wasserver");
  210: 	kill ('INT',$_);
  211:     }
  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:     foreach $thisserver (keys %hostip) {
  234: 	$answer=subreply("ping",$thisserver);
  235:         &logthis("USR1: Ping $thisserver "
  236:         ."(pid >$childpid{$thisserver}<, $childatt{thisserver} attempts): "
  237:         ." >$answer<");
  238:     }
  239:     %childatt=();
  240:     &checkchildren();
  241: }
  242: 
  243: # -------------------------------------------------- Non-critical communication
  244: sub subreply { 
  245:  my ($cmd,$server)=@_;
  246:  my $answer='';
  247:  if ($server ne $perlvar{'lonHostID'}) { 
  248:     my $peerfile="$perlvar{'lonSockDir'}/$server";
  249:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  250:                                       Type    => SOCK_STREAM,
  251:                                       Timeout => 10)
  252:        or return "con_lost";
  253: 
  254: 
  255:     $SIG{ALRM}=sub { die "timeout" };
  256:     $SIG{__DIE__}='DEFAULT';
  257:     eval {
  258:      alarm(10);
  259:      print $sclient "$cmd\n";
  260:      $answer=<$sclient>;
  261:      chomp($answer);
  262:      alarm(0);
  263:     };
  264:     if ((!$answer) || ($@=~/timeout/)) { $answer="con_lost"; }
  265:     $SIG{ALRM}='DEFAULT';
  266:     $SIG{__DIE__}=\&catchexception;
  267:  } else { $answer='self_reply'; }
  268:  return $answer;
  269: }
  270: 
  271: # --------------------------------------------------------------------- Logging
  272: 
  273: sub logthis {
  274:     my $message=shift;
  275:     my $execdir=$perlvar{'lonDaemons'};
  276:     my $fh=IO::File->new(">>$execdir/logs/lonc.log");
  277:     my $now=time;
  278:     my $local=localtime($now);
  279:     $lastlog=$local.': '.$message;
  280:     print $fh "$local ($$): $message\n";
  281: }
  282: 
  283: 
  284: sub logperm {
  285:     my $message=shift;
  286:     my $execdir=$perlvar{'lonDaemons'};
  287:     my $now=time;
  288:     my $local=localtime($now);
  289:     my $fh=IO::File->new(">>$execdir/logs/lonnet.perm.log");
  290:     print $fh "$now:$message:$local\n";
  291: }
  292: # ------------------------------------------------------------------ Log status
  293: 
  294: sub logstatus {
  295:     my $docdir=$perlvar{'lonDocRoot'};
  296:     my $fh=IO::File->new(">>$docdir/lon-status/loncstatus.txt");
  297:     print $fh $$."\t".$status."\t".$lastlog."\n";
  298: }
  299: 
  300: sub initnewstatus {
  301:     my $docdir=$perlvar{'lonDocRoot'};
  302:     my $fh=IO::File->new(">$docdir/lon-status/loncstatus.txt");
  303:     my $now=time;
  304:     my $local=localtime($now);
  305:     print $fh "LONC status $local - parent $$\n\n";
  306: }
  307: 
  308: # -------------------------------------------------------------- Status setting
  309: 
  310: sub status {
  311:     my $what=shift;
  312:     my $now=time;
  313:     my $local=localtime($now);
  314:     $status=$local.': '.$what;
  315: }
  316: 
  317: 
  318: # ---------------------------------------------------- Fork once and dissociate
  319: 
  320: $fpid=fork;
  321: exit if $fpid;
  322: die "Couldn't fork: $!" unless defined ($fpid);
  323: 
  324: POSIX::setsid() or die "Can't start new session: $!";
  325: 
  326: # ------------------------------------------------------- Write our PID on disk
  327: 
  328: $execdir=$perlvar{'lonDaemons'};
  329: open (PIDSAVE,">$execdir/logs/lonc.pid");
  330: print PIDSAVE "$$\n";
  331: close(PIDSAVE);
  332: &logthis("<font color=red>CRITICAL: ---------- Starting ----------</font>");
  333: 
  334: # ----------------------------- Ignore signals generated during initial startup
  335: $SIG{HUP}=$SIG{USR1}='IGNORE';
  336: # ------------------------------------------------------- Now we are on our own
  337:     
  338: # Fork off our children, one for every server
  339: 
  340: &status("Forking ...");
  341: 
  342: foreach $thisserver (keys %hostip) {
  343:     if (&online($hostname{$thisserver})) {
  344:        make_new_child($thisserver);
  345:     }
  346: }
  347: 
  348: &logthis("Done starting initial servers");
  349: # ----------------------------------------------------- Install signal handlers
  350: 
  351: $SIG{CHLD} = \&REAPER;
  352: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
  353: $SIG{HUP}  = \&HUPSMAN;
  354: $SIG{USR1} = \&USRMAN;
  355: 
  356: # And maintain the population.
  357: while (1) {
  358:     &status("Sleeping");
  359:     sleep;                          # wait for a signal (i.e., child's death)
  360:                                     # See who died and start new one
  361:     &status("Woke up");
  362:     foreach $thisserver (keys %hostip) {
  363:         if (!$childpid{$thisserver}) {
  364: 	    if (($childatt{$thisserver}<$childmaxattempts) &&
  365:                 (&online($hostname{$thisserver}))) {
  366: 	       $childatt{$thisserver}++;
  367:                &logthis(
  368:    "<font color=yellow>INFO: Trying to reconnect for $thisserver "
  369:   ."($childatt{$thisserver} of $childmaxattempts attempts)</font>"); 
  370:                make_new_child($thisserver);
  371: 	   } else {
  372:                &logthis(
  373:    "<font color=yellow>INFO: Skipping $thisserver "
  374:   ."($childatt{$thisserver} of $childmaxattempts attempts)</font>");
  375:            } 
  376:                
  377:         }       
  378:     }
  379: }
  380: 
  381: 
  382: sub make_new_child {
  383:    
  384:     my $conserver=shift;
  385:     my $pid;
  386:     my $sigset;
  387:     &logthis("Attempting to start child for server $conserver");
  388:     # block signal for fork
  389:     $sigset = POSIX::SigSet->new(SIGINT);
  390:     sigprocmask(SIG_BLOCK, $sigset)
  391:         or die "Can't block SIGINT for fork: $!\n";
  392:     
  393:     die "fork: $!" unless defined ($pid = fork);
  394:     
  395:     if ($pid) {
  396:         # Parent records the child's birth and returns.
  397:         sigprocmask(SIG_UNBLOCK, $sigset)
  398:             or die "Can't unblock SIGINT for fork: $!\n";
  399:         $children{$pid} = $conserver;
  400:         $childpid{$conserver} = $pid;
  401:         return;
  402:     } else {
  403:         # Child can *not* return from this subroutine.
  404:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
  405:         $SIG{USR1}= \&logstatus;
  406:    
  407:         # unblock signals
  408:         sigprocmask(SIG_UNBLOCK, $sigset)
  409:             or die "Can't unblock SIGINT for fork: $!\n";
  410: 
  411: # ----------------------------- This is the modified main program of non-forker
  412: 
  413: $port = "$perlvar{'lonSockDir'}/$conserver";
  414: 
  415: unlink($port);
  416: 
  417: # ---------------------------------------------------- Client to network server
  418: 
  419: &status("Opening TCP: $conserver");
  420: 
  421: unless (
  422:   $remotesock = IO::Socket::INET->new(PeerAddr => $hostip{$conserver},
  423:                                       PeerPort => $perlvar{'londPort'},
  424:                                       Proto    => "tcp",
  425:                                       Type     => SOCK_STREAM)
  426:    ) { 
  427:        my $st=120+int(rand(240));
  428:        &logthis(
  429: "<font color=blue>WARNING: Couldn't connect $conserver ($st secs): $@</font>");
  430:        sleep($st);
  431:        exit; 
  432:      };
  433: # ----------------------------------------------------------------- Init dialog
  434: 
  435: &status("Init dialogue: $conserver");
  436: 
  437:      $SIG{ALRM}=sub { die "timeout" };
  438:      $SIG{__DIE__}='DEFAULT';
  439:      eval {
  440:          alarm(60);
  441: print $remotesock "init\n";
  442: $answer=<$remotesock>;
  443: print $remotesock "$answer";
  444: $answer=<$remotesock>;
  445: chomp($answer);
  446:           alarm(0);
  447:      };
  448:      $SIG{ALRM}='DEFAULT';
  449:      $SIG{__DIE__}=\&catchexception;
  450:  
  451:      if ($@=~/timeout/) {
  452: 	 &logthis("Timed out during init: $conserver");
  453:          exit;
  454:      }
  455: 
  456: 
  457: &logthis("Init reply for $conserver: >$answer<");
  458: if ($answer ne 'ok') {
  459:        my $st=120+int(rand(240));
  460:        &logthis(
  461: "<font color=blue>WARNING: Init failed $conserver ($st secs)</font>");
  462:        sleep($st);
  463:        exit; 
  464: }
  465: sleep 5;
  466: &status("Ponging $conserver");
  467: print $remotesock "pong\n";
  468: $answer=<$remotesock>;
  469: chomp($answer);
  470: &logthis("Pong reply for $conserver: >$answer<");
  471: # ----------------------------------------------------------- Initialize cipher
  472: 
  473: &status("Initialize cipher: $conserver");
  474: print $remotesock "ekey\n";
  475: my $buildkey=<$remotesock>;
  476: my $key=$conserver.$perlvar{'lonHostID'};
  477: $key=~tr/a-z/A-Z/;
  478: $key=~tr/G-P/0-9/;
  479: $key=~tr/Q-Z/0-9/;
  480: $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
  481: $key=substr($key,0,32);
  482: my $cipherkey=pack("H32",$key);
  483: if ($cipher=new IDEA $cipherkey) {
  484:    &logthis("Secure connection initialized: $conserver");
  485: } else {
  486:    my $st=120+int(rand(240));
  487:    &logthis(
  488:      "<font color=blue>WARNING: ".
  489:      "Could not establish secure connection, $conserver ($st secs)!</font>");
  490:    sleep($st);
  491:    exit;
  492: }
  493: 
  494: # ----------------------------------------- We're online, send delayed messages
  495:     &status("Checking for delayed messages");
  496:     my @allbuffered;
  497:     my $path="$perlvar{'lonSockDir'}/delayed";
  498:     opendir(DIRHANDLE,$path);
  499:     @allbuffered=grep /\.$conserver$/, readdir DIRHANDLE;
  500:     closedir(DIRHANDLE);
  501:     my $dfname;
  502:     foreach (@allbuffered) {
  503:         &status("Sending delayed $conserver $_");
  504:         $dfname="$path/$_";
  505:         &logthis($dfname);
  506:         my $wcmd;
  507:         {
  508:          my $dfh=IO::File->new($dfname);
  509:          $cmd=<$dfh>;
  510:         }
  511:         chomp($cmd);
  512:         my $bcmd=$cmd;
  513:         if ($cmd =~ /^encrypt\:/) {
  514: 	    my $rcmd=$cmd;
  515:             $rcmd =~ s/^encrypt\://;
  516:             chomp($rcmd);
  517:             my $cmdlength=length($rcmd);
  518:             $rcmd.="         ";
  519:             my $encrequest='';
  520:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
  521:                 $encrequest.=
  522:                     unpack("H16",$cipher->encrypt(substr($rcmd,$encidx,8)));
  523:             }
  524:             $cmd="enc:$cmdlength:$encrequest\n";
  525:         }
  526:     $SIG{ALRM}=sub { die "timeout" };
  527:     $SIG{__DIE__}='DEFAULT';
  528:     eval {
  529:         alarm(60);
  530:         print $remotesock "$cmd\n";
  531:         $answer=<$remotesock>;
  532: 	chomp($answer);
  533:         alarm(0);
  534:     };
  535:     $SIG{ALRM}='DEFAULT';
  536:     $SIG{__DIE__}=\&catchexception;
  537: 
  538:         if (($answer ne '') && ($@!~/timeout/)) {
  539: 	    unlink("$dfname");
  540:             &logthis("Delayed $cmd to $conserver: >$answer<");
  541:             &logperm("S:$conserver:$bcmd");
  542:         }        
  543:     }
  544: 
  545: # ------------------------------------------------------- Listen to UNIX socket
  546: &status("Opening socket $conserver");
  547: unless (
  548:   $server = IO::Socket::UNIX->new(Local  => $port,
  549:                                   Type   => SOCK_STREAM,
  550:                                   Listen => 10 )
  551:    ) { 
  552:        my $st=120+int(rand(240));
  553:        &logthis(
  554:          "<font color=blue>WARNING: ".
  555:          "Can't make server socket $conserver ($st secs): $@</font>");
  556:        sleep($st);
  557:        exit; 
  558:      };
  559: 
  560: # -----------------------------------------------------------------------------
  561: 
  562: &logthis("<font color=green>$conserver online</font>");
  563: 
  564: # -----------------------------------------------------------------------------
  565: # begin with empty buffers
  566: %inbuffer  = ();
  567: %outbuffer = ();
  568: %ready     = ();
  569: 
  570: tie %ready, 'Tie::RefHash';
  571: 
  572: nonblock($server);
  573: $select = IO::Select->new($server);
  574: 
  575: # Main loop: check reads/accepts, check writes, check ready to process
  576: while (1) {
  577:     my $client;
  578:     my $rv;
  579:     my $data;
  580: 
  581:     # check for new information on the connections we have
  582: 
  583:     # anything to read or accept?
  584:     foreach $client ($select->can_read(0.1)) {
  585: 
  586:         if ($client == $server) {
  587:             # accept a new connection
  588:             &status("Accept new connection: $conserver");
  589:             $client = $server->accept();
  590:             $select->add($client);
  591:             nonblock($client);
  592:         } else {
  593:             # read data
  594:             $data = '';
  595:             $rv   = $client->recv($data, POSIX::BUFSIZ, 0);
  596: 
  597:             unless (defined($rv) && length $data) {
  598:                 # This would be the end of file, so close the client
  599:                 delete $inbuffer{$client};
  600:                 delete $outbuffer{$client};
  601:                 delete $ready{$client};
  602: 
  603:                 &status("Idle $conserver");
  604:                 $select->remove($client);
  605:                 close $client;
  606:                 next;
  607:             }
  608: 
  609:             $inbuffer{$client} .= $data;
  610: 
  611:             # test whether the data in the buffer or the data we
  612:             # just read means there is a complete request waiting
  613:             # to be fulfilled.  If there is, set $ready{$client}
  614:             # to the requests waiting to be fulfilled.
  615:             while ($inbuffer{$client} =~ s/(.*\n)//) {
  616:                 push( @{$ready{$client}}, $1 );
  617:             }
  618:         }
  619:     }
  620: 
  621:     # Any complete requests to process?
  622:     foreach $client (keys %ready) {
  623:         handle($client);
  624:     }
  625: 
  626:     # Buffers to flush?
  627:     foreach $client ($select->can_write(1)) {
  628:         # Skip this client if we have nothing to say
  629:         next unless exists $outbuffer{$client};
  630: 
  631:         $rv = $client->send($outbuffer{$client}, 0);
  632:         unless (defined $rv) {
  633:             # Whine, but move on.
  634:             &logthis("I was told I could write, but I can't.\n");
  635:             next;
  636:         }
  637:         $errno=$!;
  638:         if (($rv == length $outbuffer{$client}) ||
  639:             ($errno == POSIX::EWOULDBLOCK) || ($errno == 0)) {
  640:             substr($outbuffer{$client}, 0, $rv) = '';
  641:             delete $outbuffer{$client} unless length $outbuffer{$client};
  642:         } else {
  643:             # Couldn't write all the data, and it wasn't because
  644:             # it would have blocked.  Shutdown and move on.
  645: 
  646: 	    &logthis("Dropping data with ".$errno.": ".
  647:                      length($outbuffer{$client}).", $rv");
  648: 
  649:             delete $inbuffer{$client};
  650:             delete $outbuffer{$client};
  651:             delete $ready{$client};
  652: 
  653:             $select->remove($client);
  654:             close($client);
  655:             next;
  656:         }
  657:     }
  658: }
  659: }
  660: 
  661: # ------------------------------------------------------- End of make_new_child
  662: 
  663: # handle($socket) deals with all pending requests for $client
  664: sub handle {
  665:     # requests are in $ready{$client}
  666:     # send output to $outbuffer{$client}
  667:     my $client = shift;
  668:     my $request;
  669: 
  670:     foreach $request (@{$ready{$client}}) {
  671: # ============================================================= Process request
  672:         # $request is the text of the request
  673:         # put text of reply into $outbuffer{$client}
  674: # -----------------------------------------------------------------------------
  675:         if ($request =~ /^encrypt\:/) {
  676: 	    my $cmd=$request;
  677:             $cmd =~ s/^encrypt\://;
  678:             chomp($cmd);
  679:             my $cmdlength=length($cmd);
  680:             $cmd.="         ";
  681:             my $encrequest='';
  682:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
  683:                 $encrequest.=
  684:                     unpack("H16",$cipher->encrypt(substr($cmd,$encidx,8)));
  685:             }
  686:             $request="enc:$cmdlength:$encrequest\n";
  687:         }
  688: # --------------------------------------------------------------- Main exchange
  689:     $SIG{ALRM}=sub { die "timeout" };
  690:     $SIG{__DIE__}='DEFAULT';
  691:     eval {
  692:         alarm(300);
  693:         &status("Sending $conserver: $request");
  694:         print $remotesock "$request";
  695:         &status("Waiting for reply from $conserver: $request");
  696:         $answer=<$remotesock>;
  697:         &status("Received reply: $request");
  698:         alarm(0);
  699:     };
  700:     if ($@=~/timeout/) { 
  701:        $answer='';
  702:        &logthis(
  703:         "<font color=red>CRITICAL: Timeout $conserver: $request</font>");
  704:     }  
  705:     $SIG{ALRM}='DEFAULT';
  706:     $SIG{__DIE__}=\&catchexception;
  707: 
  708: 
  709:         if ($answer) {
  710: 	   if ($answer =~ /^enc/) {
  711:                my ($cmd,$cmdlength,$encinput)=split(/:/,$answer);
  712:                chomp($encinput);
  713: 	       $answer='';
  714:                for (my $encidx=0;$encidx<length($encinput);$encidx+=16) {
  715:                   $answer.=$cipher->decrypt(
  716:                    pack("H16",substr($encinput,$encidx,16))
  717:                   );
  718: 	       }
  719: 	      $answer=substr($answer,0,$cmdlength);
  720: 	      $answer.="\n";
  721: 	   }
  722:            $outbuffer{$client} .= $answer;
  723:         } else {
  724:            $outbuffer{$client} .= "con_lost\n";
  725:         }
  726: 
  727: # ===================================================== Done processing request
  728:     }
  729:     delete $ready{$client};
  730:     &status("Completed $conserver: $request");
  731: # -------------------------------------------------------------- End non-forker
  732: }
  733: # ---------------------------------------------------------- End make_new_child
  734: }
  735: 
  736: # nonblock($socket) puts socket into nonblocking mode
  737: sub nonblock {
  738:     my $socket = shift;
  739:     my $flags;
  740: 
  741:     
  742:     $flags = fcntl($socket, F_GETFL, 0)
  743:             or die "Can't get flags for socket: $!\n";
  744:     fcntl($socket, F_SETFL, $flags | O_NONBLOCK)
  745:             or die "Can't make socket nonblocking: $!\n";
  746: }
  747: 
  748: # ----------------------------------- POD (plain old documentation, CPAN style)
  749: 
  750: =head1 NAME
  751: 
  752: lonc - LON TCP-MySQL-Server Daemon for handling database requests.
  753: 
  754: =head1 SYNOPSIS
  755: 
  756: Should only be run as user=www.  This is a command-line script which
  757: is invoked by loncron.
  758: 
  759: =head1 DESCRIPTION
  760: 
  761: Provides persistent TCP connections to the other servers in the network
  762: through multiplexed domain sockets
  763: 
  764:  PID in subdir logs/lonc.pid
  765:  kill kills
  766:  HUP restarts
  767:  USR1 tries to open connections again
  768: 
  769: =head1 README
  770: 
  771: Not yet written.
  772: 
  773: =head1 PREREQUISITES
  774: 
  775: POSIX
  776: IO::Socket
  777: IO::Select
  778: IO::File
  779: Socket
  780: Fcntl
  781: Tie::RefHash
  782: Crypt::IDEA
  783: 
  784: =head1 COREQUISITES
  785: 
  786: =head1 OSNAMES
  787: 
  788: linux
  789: 
  790: =head1 SCRIPT CATEGORIES
  791: 
  792: Server/Process
  793: 
  794: =cut

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