Annotation of loncom/lonc, revision 1.27

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: #
1.27    ! www         8: # $Id: lonc,v 1.26 2002/02/19 21:12:22 www Exp $
1.22      www         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: #
1.1       albertel   32: # PID in subdir logs/lonc.pid
                     33: # kill kills
                     34: # HUP restarts
                     35: # USR1 tries to open connections again
                     36: 
1.2       www        37: # 6/4/99,6/5,6/7,6/8,6/9,6/10,6/11,6/12,7/14,7/19,
1.5       www        38: # 10/8,10/9,10/15,11/18,12/22,
1.10      www        39: # 2/8,7/25 Gerd Kortemeyer
                     40: # 12/05 Scott Harrison
                     41: # 12/05 Gerd Kortemeyer
1.23      harris41   42: # YEAR=2001
1.14      www        43: # 01/10/01 Scott Harrison
1.21      www        44: # 03/14/01,03/15,06/12,11/26,11/27,11/28 Gerd Kortemeyer
1.23      harris41   45: # 12/20 Scott Harrison
1.26      www        46: # YEAR=2002
                     47: # 2/19/02
1.10      www        48: # 
1.1       albertel   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;
1.26      www        60: use Net::Ping;
                     61: use LWP::UserAgent();
1.1       albertel   62: 
1.18      www        63: my $status='';
                     64: my $lastlog='';
                     65: 
1.9       harris41   66: # grabs exception and records it to log before exiting
                     67: sub catchexception {
                     68:     my ($signal)=@_;
1.10      www        69:     $SIG{'QUIT'}='DEFAULT';
                     70:     $SIG{__DIE__}='DEFAULT';
1.9       harris41   71:     &logthis("<font color=red>CRITICAL: "
                     72:      ."ABNORMAL EXIT. Child $$ for server $wasserver died through "
1.11      harris41   73:      ."\"$signal\" with this parameter->[$@]</font>");
1.9       harris41   74:     die($@);
                     75: }
                     76: 
1.17      www        77: $childmaxattempts=5;
1.5       www        78: 
1.26      www        79: # -------------------------------------- Routines to see if other box available
                     80: 
                     81: sub online {
                     82:     my $host=shift;
1.27    ! www        83:     my $p=Net::Ping->new("tcp",20);
1.26      www        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: 
1.8       harris41  117: # -------------------------------- Set signal handlers to record abnormal exits
                    118: 
1.26      www       119: $SIG{QUIT}=\&catchexception;
1.8       harris41  120: $SIG{__DIE__}=\&catchexception;
                    121: 
1.1       albertel  122: # ------------------------------------ Read httpd access.conf and get variables
                    123: 
1.11      harris41  124: open (CONFIG,"/etc/httpd/conf/access.conf") || die "Can't read access.conf";
1.1       albertel  125: 
                    126: while ($configline=<CONFIG>) {
                    127:     if ($configline =~ /PerlSetVar/) {
                    128: 	my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.4       www       129:         chomp($varvalue);
1.1       albertel  130:         $perlvar{$varname}=$varvalue;
                    131:     }
                    132: }
                    133: close(CONFIG);
1.7       www       134: 
1.13      harris41  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";
1.14      www       140:    system("echo 'User ID mismatch.  lonc must be run as user www.' |\
1.13      harris41  141:  mailto $emailto -s '$subj' > /dev/null");
                    142:    exit 1;
                    143: }
                    144: 
1.7       www       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);
1.11      harris41  153:    if (kill 0 => $pide) { die "already running"; }
1.7       www       154: }
1.1       albertel  155: 
                    156: # ------------------------------------------------------------- Read hosts file
                    157: 
1.11      harris41  158: open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
1.1       albertel  159: 
                    160: while ($configline=<CONFIG>) {
                    161:     my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
                    162:     chomp($ip);
                    163:     $hostip{$id}=$ip;
1.27    ! www       164:     $hostname{$id}=$name;
1.1       albertel  165: }
1.27    ! www       166: 
1.1       albertel  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};
1.6       www       182:     &logthis("<font color=red>CRITICAL: "
                    183:      ."Child $pid for server $wasserver died ($childatt{$wasserver})</font>");
1.1       albertel  184:     delete $children{$pid};
                    185:     delete $childpid{$wasserver};
                    186:     my $port = "$perlvar{'lonSockDir'}/$wasserver";
                    187:     unlink($port);
                    188: }
                    189: 
1.27    ! www       190: sub hangup {
1.23      harris41  191:     foreach (keys %children) {
1.17      www       192:         $wasserver=$children{$_};
1.18      www       193:         &status("Closing $wasserver");
1.17      www       194:         &logthis('Closing '.$wasserver.': '.&subreply('exit',$wasserver));
1.18      www       195:         &status("Kill PID $_ for $wasserver");
1.17      www       196: 	kill ('INT',$_);
1.23      harris41  197:     }
1.27    ! www       198: }
        !           199: 
        !           200: sub HUNTSMAN {                      # signal handler for SIGINT
        !           201:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
        !           202:     &hangup();
1.1       albertel  203:     my $execdir=$perlvar{'lonDaemons'};
                    204:     unlink("$execdir/logs/lonc.pid");
1.5       www       205:     &logthis("<font color=red>CRITICAL: Shutting down</font>");
1.1       albertel  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
1.27    ! www       211:     &hangup();
1.5       www       212:     &logthis("<font color=red>CRITICAL: Restarting</font>");
1.12      harris41  213:     unlink("$execdir/logs/lonc.pid");
1.1       albertel  214:     my $execdir=$perlvar{'lonDaemons'};
                    215:     exec("$execdir/lonc");         # here we go again
                    216: }
                    217: 
1.18      www       218: sub checkchildren {
                    219:     &initnewstatus();
                    220:     &logstatus();
                    221:     &logthis('Going to check on the children');
1.23      harris41  222:     foreach (sort keys %children) {
1.18      www       223: 	sleep 1;
                    224:         unless (kill 'USR1' => $_) {
                    225: 	    &logthis ('Child '.$_.' is dead');
                    226:             &logstatus($$.' is dead');
                    227:         } 
1.23      harris41  228:     }
1.18      www       229: }
                    230: 
1.1       albertel  231: sub USRMAN {
                    232:     &logthis("USR1: Trying to establish connections again");
1.6       www       233:     %childatt=();
1.18      www       234:     &checkchildren();
1.1       albertel  235: }
                    236: 
                    237: # -------------------------------------------------- Non-critical communication
                    238: sub subreply { 
                    239:  my ($cmd,$server)=@_;
1.5       www       240:  my $answer='';
1.1       albertel  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";
1.21      www       247: 
                    248: 
1.19      www       249:     $SIG{ALRM}=sub { die "timeout" };
                    250:     $SIG{__DIE__}='DEFAULT';
                    251:     eval {
                    252:      alarm(10);
                    253:      print $sclient "$cmd\n";
1.21      www       254:      $answer=<$sclient>;
1.19      www       255:      chomp($answer);
                    256:      alarm(0);
                    257:     };
                    258:     if ((!$answer) || ($@=~/timeout/)) { $answer="con_lost"; }
                    259:     $SIG{ALRM}='DEFAULT';
                    260:     $SIG{__DIE__}=\&catchexception;
1.1       albertel  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);
1.18      www       273:     $lastlog=$local.': '.$message;
1.1       albertel  274:     print $fh "$local ($$): $message\n";
                    275: }
                    276: 
1.3       www       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: }
1.18      www       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: 
1.3       www       311: 
1.1       albertel  312: # ---------------------------------------------------- Fork once and dissociate
                    313: 
                    314: $fpid=fork;
                    315: exit if $fpid;
1.11      harris41  316: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel  317: 
1.11      harris41  318: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel  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);
1.5       www       326: &logthis("<font color=red>CRITICAL: ---------- Starting ----------</font>");
1.1       albertel  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: 
1.18      www       334: &status("Forking ...");
                    335: 
1.1       albertel  336: foreach $thisserver (keys %hostip) {
1.26      www       337:     if (&online($hostname{$thisserver})) {
                    338:        make_new_child($thisserver);
                    339:     }
1.1       albertel  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) {
1.18      www       352:     &status("Sleeping");
1.1       albertel  353:     sleep;                          # wait for a signal (i.e., child's death)
                    354:                                     # See who died and start new one
1.18      www       355:     &status("Woke up");
1.1       albertel  356:     foreach $thisserver (keys %hostip) {
                    357:         if (!$childpid{$thisserver}) {
1.26      www       358: 	    if (($childatt{$thisserver}<$childmaxattempts) &&
                    359:                 (&online($hostname{$thisserver}))) {
1.6       www       360: 	       $childatt{$thisserver}++;
1.5       www       361:                &logthis(
                    362:    "<font color=yellow>INFO: Trying to reconnect for $thisserver "
1.6       www       363:   ."($childatt{$thisserver} of $childmaxattempts attempts)</font>"); 
1.1       albertel  364:                make_new_child($thisserver);
1.26      www       365: 	   } else {
                    366:                &logthis(
                    367:    "<font color=yellow>INFO: Skipping $thisserver "
                    368:   ."($childatt{$thisserver} of $childmaxattempts attempts)</font>");
                    369:            } 
                    370:                
1.1       albertel  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)
1.11      harris41  385:         or die "Can't block SIGINT for fork: $!\n";
1.1       albertel  386:     
1.11      harris41  387:     die "fork: $!" unless defined ($pid = fork);
1.1       albertel  388:     
                    389:     if ($pid) {
                    390:         # Parent records the child's birth and returns.
                    391:         sigprocmask(SIG_UNBLOCK, $sigset)
1.11      harris41  392:             or die "Can't unblock SIGINT for fork: $!\n";
1.1       albertel  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
1.18      www       399:         $SIG{USR1}= \&logstatus;
                    400:    
1.1       albertel  401:         # unblock signals
                    402:         sigprocmask(SIG_UNBLOCK, $sigset)
1.11      harris41  403:             or die "Can't unblock SIGINT for fork: $!\n";
1.1       albertel  404: 
                    405: # ----------------------------- This is the modified main program of non-forker
                    406: 
                    407: $port = "$perlvar{'lonSockDir'}/$conserver";
                    408: 
                    409: unlink($port);
1.18      www       410: 
1.1       albertel  411: # ---------------------------------------------------- Client to network server
1.18      www       412: 
                    413: &status("Opening TCP: $conserver");
                    414: 
1.1       albertel  415: unless (
                    416:   $remotesock = IO::Socket::INET->new(PeerAddr => $hostip{$conserver},
                    417:                                       PeerPort => $perlvar{'londPort'},
                    418:                                       Proto    => "tcp",
                    419:                                       Type     => SOCK_STREAM)
1.5       www       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);
1.1       albertel  425:        exit; 
                    426:      };
1.20      www       427: # ----------------------------------------------------------------- Init dialog
1.18      www       428: 
                    429: &status("Init dialogue: $conserver");
                    430: 
1.20      www       431:      $SIG{ALRM}=sub { die "timeout" };
                    432:      $SIG{__DIE__}='DEFAULT';
                    433:      eval {
                    434:          alarm(60);
1.2       www       435: print $remotesock "init\n";
                    436: $answer=<$remotesock>;
                    437: print $remotesock "$answer";
1.1       albertel  438: $answer=<$remotesock>;
                    439: chomp($answer);
1.20      www       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: 
1.2       www       451: &logthis("Init reply for $conserver: >$answer<");
1.17      www       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: }
1.1       albertel  459: sleep 5;
1.18      www       460: &status("Ponging $conserver");
1.1       albertel  461: print $remotesock "pong\n";
                    462: $answer=<$remotesock>;
                    463: chomp($answer);
                    464: &logthis("Pong reply for $conserver: >$answer<");
                    465: # ----------------------------------------------------------- Initialize cipher
                    466: 
1.18      www       467: &status("Initialize cipher: $conserver");
1.1       albertel  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) {
1.12      harris41  478:    &logthis("Secure connection initialized: $conserver");
1.1       albertel  479: } else {
1.5       www       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;
1.1       albertel  486: }
                    487: 
1.3       www       488: # ----------------------------------------- We're online, send delayed messages
1.18      www       489:     &status("Checking for delayed messages");
1.4       www       490:     my @allbuffered;
1.3       www       491:     my $path="$perlvar{'lonSockDir'}/delayed";
1.4       www       492:     opendir(DIRHANDLE,$path);
                    493:     @allbuffered=grep /\.$conserver$/, readdir DIRHANDLE;
                    494:     closedir(DIRHANDLE);
1.3       www       495:     my $dfname;
1.23      harris41  496:     foreach (@allbuffered) {
1.18      www       497:         &status("Sending delayed $conserver $_");
1.4       www       498:         $dfname="$path/$_";
                    499:         &logthis($dfname);
1.3       www       500:         my $wcmd;
                    501:         {
                    502:          my $dfh=IO::File->new($dfname);
1.4       www       503:          $cmd=<$dfh>;
1.3       www       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:         }
1.20      www       520:     $SIG{ALRM}=sub { die "timeout" };
                    521:     $SIG{__DIE__}='DEFAULT';
                    522:     eval {
                    523:         alarm(60);
1.3       www       524:         print $remotesock "$cmd\n";
                    525:         $answer=<$remotesock>;
                    526: 	chomp($answer);
1.20      www       527:         alarm(0);
                    528:     };
                    529:     $SIG{ALRM}='DEFAULT';
                    530:     $SIG{__DIE__}=\&catchexception;
                    531: 
                    532:         if (($answer ne '') && ($@!~/timeout/)) {
1.3       www       533: 	    unlink("$dfname");
1.4       www       534:             &logthis("Delayed $cmd to $conserver: >$answer<");
1.3       www       535:             &logperm("S:$conserver:$bcmd");
                    536:         }        
1.23      harris41  537:     }
1.1       albertel  538: 
                    539: # ------------------------------------------------------- Listen to UNIX socket
1.18      www       540: &status("Opening socket $conserver");
1.1       albertel  541: unless (
                    542:   $server = IO::Socket::UNIX->new(Local  => $port,
                    543:                                   Type   => SOCK_STREAM,
                    544:                                   Listen => 10 )
1.5       www       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);
1.1       albertel  551:        exit; 
                    552:      };
                    553: 
                    554: # -----------------------------------------------------------------------------
                    555: 
1.5       www       556: &logthis("<font color=green>$conserver online</font>");
                    557: 
                    558: # -----------------------------------------------------------------------------
1.1       albertel  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?
1.16      www       578:     foreach $client ($select->can_read(0.1)) {
1.1       albertel  579: 
                    580:         if ($client == $server) {
                    581:             # accept a new connection
1.18      www       582:             &status("Accept new connection: $conserver");
1.1       albertel  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: 
1.18      www       597:                 &status("Idle $conserver");
1.1       albertel  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) {
1.25      albertel  617:         handle($client);
1.1       albertel  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};
1.25      albertel  624: 
1.1       albertel  625:         $rv = $client->send($outbuffer{$client}, 0);
                    626:         unless (defined $rv) {
                    627:             # Whine, but move on.
1.15      www       628:             &logthis("I was told I could write, but I can't.\n");
1.1       albertel  629:             next;
                    630:         }
1.15      www       631:         $errno=$!;
1.1       albertel  632:         if (($rv == length $outbuffer{$client}) ||
1.15      www       633:             ($errno == POSIX::EWOULDBLOCK) || ($errno == 0)) {
1.1       albertel  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.
1.15      www       639: 
                    640: 	    &logthis("Dropping data with ".$errno.": ".
                    641:                      length($outbuffer{$client}).", $rv");
                    642: 
1.1       albertel  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: }
1.25      albertel  654: 
1.1       albertel  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:         }
1.19      www       682: # --------------------------------------------------------------- Main exchange
                    683:     $SIG{ALRM}=sub { die "timeout" };
                    684:     $SIG{__DIE__}='DEFAULT';
                    685:     eval {
                    686:         alarm(300);
1.18      www       687:         &status("Sending $conserver: $request");
1.1       albertel  688:         print $remotesock "$request";
1.18      www       689:         &status("Waiting for reply from $conserver: $request");
1.1       albertel  690:         $answer=<$remotesock>;
1.18      www       691:         &status("Received reply: $request");
1.19      www       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: 
1.1       albertel  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};
1.18      www       724:     &status("Completed $conserver: $request");
1.1       albertel  725: # -------------------------------------------------------------- End non-forker
                    726: }
                    727: # ---------------------------------------------------------- End make_new_child
1.25      albertel  728: }
1.1       albertel  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)
1.11      harris41  737:             or die "Can't get flags for socket: $!\n";
1.1       albertel  738:     fcntl($socket, F_SETFL, $flags | O_NONBLOCK)
1.11      harris41  739:             or die "Can't make socket nonblocking: $!\n";
1.8       harris41  740: }
1.1       albertel  741: 
1.23      harris41  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>