Annotation of loncom/lonc, revision 1.26

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.26    ! www         8: # $Id: lonc,v 1.25 2002/02/06 14:15:37 albertel 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;
        !            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: 
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;
                    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};
1.6       www       180:     &logthis("<font color=red>CRITICAL: "
                    181:      ."Child $pid for server $wasserver died ($childatt{$wasserver})</font>");
1.1       albertel  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
1.23      harris41  190:     foreach (keys %children) {
1.17      www       191:         $wasserver=$children{$_};
1.18      www       192:         &status("Closing $wasserver");
1.17      www       193:         &logthis('Closing '.$wasserver.': '.&subreply('exit',$wasserver));
1.18      www       194:         &status("Kill PID $_ for $wasserver");
1.17      www       195: 	kill ('INT',$_);
1.23      harris41  196:     }
1.1       albertel  197:     my $execdir=$perlvar{'lonDaemons'};
                    198:     unlink("$execdir/logs/lonc.pid");
1.5       www       199:     &logthis("<font color=red>CRITICAL: Shutting down</font>");
1.1       albertel  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
1.23      harris41  205:     foreach (keys %children) {
1.17      www       206:         $wasserver=$children{$_};
1.18      www       207:         &status("Closing $wasserver");
1.17      www       208:         &logthis('Closing '.$wasserver.': '.&subreply('exit',$wasserver));
1.18      www       209:         &status("Kill PID $_ for $wasserver");
1.17      www       210: 	kill ('INT',$_);
1.23      harris41  211:     }
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");
                    233:     foreach $thisserver (keys %hostip) {
                    234: 	$answer=subreply("ping",$thisserver);
1.6       www       235:         &logthis("USR1: Ping $thisserver "
                    236:         ."(pid >$childpid{$thisserver}<, $childatt{thisserver} attempts): "
                    237:         ." >$answer<");
1.1       albertel  238:     }
1.6       www       239:     %childatt=();
1.18      www       240:     &checkchildren();
1.1       albertel  241: }
                    242: 
                    243: # -------------------------------------------------- Non-critical communication
                    244: sub subreply { 
                    245:  my ($cmd,$server)=@_;
1.5       www       246:  my $answer='';
1.1       albertel  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";
1.21      www       253: 
                    254: 
1.19      www       255:     $SIG{ALRM}=sub { die "timeout" };
                    256:     $SIG{__DIE__}='DEFAULT';
                    257:     eval {
                    258:      alarm(10);
                    259:      print $sclient "$cmd\n";
1.21      www       260:      $answer=<$sclient>;
1.19      www       261:      chomp($answer);
                    262:      alarm(0);
                    263:     };
                    264:     if ((!$answer) || ($@=~/timeout/)) { $answer="con_lost"; }
                    265:     $SIG{ALRM}='DEFAULT';
                    266:     $SIG{__DIE__}=\&catchexception;
1.1       albertel  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);
1.18      www       279:     $lastlog=$local.': '.$message;
1.1       albertel  280:     print $fh "$local ($$): $message\n";
                    281: }
                    282: 
1.3       www       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: }
1.18      www       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: 
1.3       www       317: 
1.1       albertel  318: # ---------------------------------------------------- Fork once and dissociate
                    319: 
                    320: $fpid=fork;
                    321: exit if $fpid;
1.11      harris41  322: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel  323: 
1.11      harris41  324: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel  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);
1.5       www       332: &logthis("<font color=red>CRITICAL: ---------- Starting ----------</font>");
1.1       albertel  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: 
1.18      www       340: &status("Forking ...");
                    341: 
1.1       albertel  342: foreach $thisserver (keys %hostip) {
1.26    ! www       343:     if (&online($hostname{$thisserver})) {
        !           344:        make_new_child($thisserver);
        !           345:     }
1.1       albertel  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) {
1.18      www       358:     &status("Sleeping");
1.1       albertel  359:     sleep;                          # wait for a signal (i.e., child's death)
                    360:                                     # See who died and start new one
1.18      www       361:     &status("Woke up");
1.1       albertel  362:     foreach $thisserver (keys %hostip) {
                    363:         if (!$childpid{$thisserver}) {
1.26    ! www       364: 	    if (($childatt{$thisserver}<$childmaxattempts) &&
        !           365:                 (&online($hostname{$thisserver}))) {
1.6       www       366: 	       $childatt{$thisserver}++;
1.5       www       367:                &logthis(
                    368:    "<font color=yellow>INFO: Trying to reconnect for $thisserver "
1.6       www       369:   ."($childatt{$thisserver} of $childmaxattempts attempts)</font>"); 
1.1       albertel  370:                make_new_child($thisserver);
1.26    ! www       371: 	   } else {
        !           372:                &logthis(
        !           373:    "<font color=yellow>INFO: Skipping $thisserver "
        !           374:   ."($childatt{$thisserver} of $childmaxattempts attempts)</font>");
        !           375:            } 
        !           376:                
1.1       albertel  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)
1.11      harris41  391:         or die "Can't block SIGINT for fork: $!\n";
1.1       albertel  392:     
1.11      harris41  393:     die "fork: $!" unless defined ($pid = fork);
1.1       albertel  394:     
                    395:     if ($pid) {
                    396:         # Parent records the child's birth and returns.
                    397:         sigprocmask(SIG_UNBLOCK, $sigset)
1.11      harris41  398:             or die "Can't unblock SIGINT for fork: $!\n";
1.1       albertel  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
1.18      www       405:         $SIG{USR1}= \&logstatus;
                    406:    
1.1       albertel  407:         # unblock signals
                    408:         sigprocmask(SIG_UNBLOCK, $sigset)
1.11      harris41  409:             or die "Can't unblock SIGINT for fork: $!\n";
1.1       albertel  410: 
                    411: # ----------------------------- This is the modified main program of non-forker
                    412: 
                    413: $port = "$perlvar{'lonSockDir'}/$conserver";
                    414: 
                    415: unlink($port);
1.18      www       416: 
1.1       albertel  417: # ---------------------------------------------------- Client to network server
1.18      www       418: 
                    419: &status("Opening TCP: $conserver");
                    420: 
1.1       albertel  421: unless (
                    422:   $remotesock = IO::Socket::INET->new(PeerAddr => $hostip{$conserver},
                    423:                                       PeerPort => $perlvar{'londPort'},
                    424:                                       Proto    => "tcp",
                    425:                                       Type     => SOCK_STREAM)
1.5       www       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);
1.1       albertel  431:        exit; 
                    432:      };
1.20      www       433: # ----------------------------------------------------------------- Init dialog
1.18      www       434: 
                    435: &status("Init dialogue: $conserver");
                    436: 
1.20      www       437:      $SIG{ALRM}=sub { die "timeout" };
                    438:      $SIG{__DIE__}='DEFAULT';
                    439:      eval {
                    440:          alarm(60);
1.2       www       441: print $remotesock "init\n";
                    442: $answer=<$remotesock>;
                    443: print $remotesock "$answer";
1.1       albertel  444: $answer=<$remotesock>;
                    445: chomp($answer);
1.20      www       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: 
1.2       www       457: &logthis("Init reply for $conserver: >$answer<");
1.17      www       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: }
1.1       albertel  465: sleep 5;
1.18      www       466: &status("Ponging $conserver");
1.1       albertel  467: print $remotesock "pong\n";
                    468: $answer=<$remotesock>;
                    469: chomp($answer);
                    470: &logthis("Pong reply for $conserver: >$answer<");
                    471: # ----------------------------------------------------------- Initialize cipher
                    472: 
1.18      www       473: &status("Initialize cipher: $conserver");
1.1       albertel  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) {
1.12      harris41  484:    &logthis("Secure connection initialized: $conserver");
1.1       albertel  485: } else {
1.5       www       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;
1.1       albertel  492: }
                    493: 
1.3       www       494: # ----------------------------------------- We're online, send delayed messages
1.18      www       495:     &status("Checking for delayed messages");
1.4       www       496:     my @allbuffered;
1.3       www       497:     my $path="$perlvar{'lonSockDir'}/delayed";
1.4       www       498:     opendir(DIRHANDLE,$path);
                    499:     @allbuffered=grep /\.$conserver$/, readdir DIRHANDLE;
                    500:     closedir(DIRHANDLE);
1.3       www       501:     my $dfname;
1.23      harris41  502:     foreach (@allbuffered) {
1.18      www       503:         &status("Sending delayed $conserver $_");
1.4       www       504:         $dfname="$path/$_";
                    505:         &logthis($dfname);
1.3       www       506:         my $wcmd;
                    507:         {
                    508:          my $dfh=IO::File->new($dfname);
1.4       www       509:          $cmd=<$dfh>;
1.3       www       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:         }
1.20      www       526:     $SIG{ALRM}=sub { die "timeout" };
                    527:     $SIG{__DIE__}='DEFAULT';
                    528:     eval {
                    529:         alarm(60);
1.3       www       530:         print $remotesock "$cmd\n";
                    531:         $answer=<$remotesock>;
                    532: 	chomp($answer);
1.20      www       533:         alarm(0);
                    534:     };
                    535:     $SIG{ALRM}='DEFAULT';
                    536:     $SIG{__DIE__}=\&catchexception;
                    537: 
                    538:         if (($answer ne '') && ($@!~/timeout/)) {
1.3       www       539: 	    unlink("$dfname");
1.4       www       540:             &logthis("Delayed $cmd to $conserver: >$answer<");
1.3       www       541:             &logperm("S:$conserver:$bcmd");
                    542:         }        
1.23      harris41  543:     }
1.1       albertel  544: 
                    545: # ------------------------------------------------------- Listen to UNIX socket
1.18      www       546: &status("Opening socket $conserver");
1.1       albertel  547: unless (
                    548:   $server = IO::Socket::UNIX->new(Local  => $port,
                    549:                                   Type   => SOCK_STREAM,
                    550:                                   Listen => 10 )
1.5       www       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);
1.1       albertel  557:        exit; 
                    558:      };
                    559: 
                    560: # -----------------------------------------------------------------------------
                    561: 
1.5       www       562: &logthis("<font color=green>$conserver online</font>");
                    563: 
                    564: # -----------------------------------------------------------------------------
1.1       albertel  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?
1.16      www       584:     foreach $client ($select->can_read(0.1)) {
1.1       albertel  585: 
                    586:         if ($client == $server) {
                    587:             # accept a new connection
1.18      www       588:             &status("Accept new connection: $conserver");
1.1       albertel  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: 
1.18      www       603:                 &status("Idle $conserver");
1.1       albertel  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) {
1.25      albertel  623:         handle($client);
1.1       albertel  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};
1.25      albertel  630: 
1.1       albertel  631:         $rv = $client->send($outbuffer{$client}, 0);
                    632:         unless (defined $rv) {
                    633:             # Whine, but move on.
1.15      www       634:             &logthis("I was told I could write, but I can't.\n");
1.1       albertel  635:             next;
                    636:         }
1.15      www       637:         $errno=$!;
1.1       albertel  638:         if (($rv == length $outbuffer{$client}) ||
1.15      www       639:             ($errno == POSIX::EWOULDBLOCK) || ($errno == 0)) {
1.1       albertel  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.
1.15      www       645: 
                    646: 	    &logthis("Dropping data with ".$errno.": ".
                    647:                      length($outbuffer{$client}).", $rv");
                    648: 
1.1       albertel  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: }
1.25      albertel  660: 
1.1       albertel  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:         }
1.19      www       688: # --------------------------------------------------------------- Main exchange
                    689:     $SIG{ALRM}=sub { die "timeout" };
                    690:     $SIG{__DIE__}='DEFAULT';
                    691:     eval {
                    692:         alarm(300);
1.18      www       693:         &status("Sending $conserver: $request");
1.1       albertel  694:         print $remotesock "$request";
1.18      www       695:         &status("Waiting for reply from $conserver: $request");
1.1       albertel  696:         $answer=<$remotesock>;
1.18      www       697:         &status("Received reply: $request");
1.19      www       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: 
1.1       albertel  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};
1.18      www       730:     &status("Completed $conserver: $request");
1.1       albertel  731: # -------------------------------------------------------------- End non-forker
                    732: }
                    733: # ---------------------------------------------------------- End make_new_child
1.25      albertel  734: }
1.1       albertel  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)
1.11      harris41  743:             or die "Can't get flags for socket: $!\n";
1.1       albertel  744:     fcntl($socket, F_SETFL, $flags | O_NONBLOCK)
1.11      harris41  745:             or die "Can't make socket nonblocking: $!\n";
1.8       harris41  746: }
1.1       albertel  747: 
1.23      harris41  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>