Annotation of loncom/lonc, revision 1.37
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.37 ! foxr 8: # $Id: lonc,v 1.36 2002/03/27 04:07:02 foxr 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
1.29 www 47: # 2/19/02,02/22/02,02/25/02 Gerd Kortemeyer
1.33 foxr 48: # 3/07/02 Ron Fox
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.32 foxr 60: #use Net::Ping;
1.26 www 61: use LWP::UserAgent();
1.1 albertel 62:
1.30 www 63: $status='';
64: $lastlog='';
65: $conserver='SHELL';
1.32 foxr 66: $DEBUG = 0; # Set to 1 for annoyingly complete logs.
1.26 www 67:
1.8 harris41 68: # -------------------------------- Set signal handlers to record abnormal exits
69:
1.29 www 70: &status("Init exception handlers");
1.26 www 71: $SIG{QUIT}=\&catchexception;
1.8 harris41 72: $SIG{__DIE__}=\&catchexception;
73:
1.1 albertel 74: # ------------------------------------ Read httpd access.conf and get variables
1.29 www 75: &status("Read access.conf");
1.11 harris41 76: open (CONFIG,"/etc/httpd/conf/access.conf") || die "Can't read access.conf";
1.1 albertel 77:
78: while ($configline=<CONFIG>) {
79: if ($configline =~ /PerlSetVar/) {
80: my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.4 www 81: chomp($varvalue);
1.1 albertel 82: $perlvar{$varname}=$varvalue;
83: }
84: }
85: close(CONFIG);
1.7 www 86:
1.13 harris41 87: # ----------------------------- Make sure this process is running from user=www
1.29 www 88: &status("Check user ID");
1.13 harris41 89: my $wwwid=getpwnam('www');
90: if ($wwwid!=$<) {
91: $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
92: $subj="LON: $perlvar{'lonHostID'} User ID mismatch";
1.14 www 93: system("echo 'User ID mismatch. lonc must be run as user www.' |\
1.13 harris41 94: mailto $emailto -s '$subj' > /dev/null");
95: exit 1;
96: }
97:
1.7 www 98: # --------------------------------------------- Check if other instance running
99:
100: my $pidfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
101:
102: if (-e $pidfile) {
103: my $lfh=IO::File->new("$pidfile");
104: my $pide=<$lfh>;
105: chomp($pide);
1.11 harris41 106: if (kill 0 => $pide) { die "already running"; }
1.7 www 107: }
1.1 albertel 108:
109: # ------------------------------------------------------------- Read hosts file
110:
1.11 harris41 111: open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
1.1 albertel 112:
113: while ($configline=<CONFIG>) {
114: my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
115: chomp($ip);
1.28 www 116: if ($ip) {
117: $hostip{$id}=$ip;
118: $hostname{$id}=$name;
119: }
1.1 albertel 120: }
1.27 www 121:
1.1 albertel 122: close(CONFIG);
123:
124: # -------------------------------------------------------- Routines for forking
125:
126: %children = (); # keys are current child process IDs,
127: # values are hosts
128: %childpid = (); # the other way around
129:
130: %childatt = (); # number of attempts to start server
131: # for ID
132:
1.30 www 133: $childmaxattempts=5;
1.3 www 134:
1.1 albertel 135: # ---------------------------------------------------- Fork once and dissociate
1.29 www 136: &status("Fork and dissociate");
1.1 albertel 137: $fpid=fork;
138: exit if $fpid;
1.11 harris41 139: die "Couldn't fork: $!" unless defined ($fpid);
1.1 albertel 140:
1.11 harris41 141: POSIX::setsid() or die "Can't start new session: $!";
1.1 albertel 142:
1.30 www 143: $conserver='PARENT';
144:
1.1 albertel 145: # ------------------------------------------------------- Write our PID on disk
1.29 www 146: &status("Write PID");
1.1 albertel 147: $execdir=$perlvar{'lonDaemons'};
148: open (PIDSAVE,">$execdir/logs/lonc.pid");
149: print PIDSAVE "$$\n";
150: close(PIDSAVE);
1.5 www 151: &logthis("<font color=red>CRITICAL: ---------- Starting ----------</font>");
1.1 albertel 152:
153: # ----------------------------- Ignore signals generated during initial startup
154: $SIG{HUP}=$SIG{USR1}='IGNORE';
155: # ------------------------------------------------------- Now we are on our own
156:
157: # Fork off our children, one for every server
158:
1.18 www 159: &status("Forking ...");
160:
1.1 albertel 161: foreach $thisserver (keys %hostip) {
1.32 foxr 162: #if (&online($hostname{$thisserver})) {
1.26 www 163: make_new_child($thisserver);
1.32 foxr 164: #}
1.1 albertel 165: }
166:
167: &logthis("Done starting initial servers");
168: # ----------------------------------------------------- Install signal handlers
169:
1.32 foxr 170:
1.1 albertel 171: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
172: $SIG{HUP} = \&HUPSMAN;
173: $SIG{USR1} = \&USRMAN;
174:
175: # And maintain the population.
176: while (1) {
1.32 foxr 177: my $deadpid = wait; # Wait for the next child to die.
1.1 albertel 178: # See who died and start new one
1.18 www 179: &status("Woke up");
1.30 www 180: my $skipping='';
1.32 foxr 181:
182: if(exists($children{$deadpid})) {
183:
184: $thisserver = $children{$deadpid}; # Look name of dead guy's peer.
185:
186: delete($children{$deadpid}); # Get rid of dead hash entry.
187:
188: if($childatt{$thisserver} < $childmaxattempts) {
189: $childatt{$thisserver}++;
190: &logthis(
191: "<font color=yellow>INFO: Trying to reconnect for $thisserver "
192: ."($childatt{$thisserver} of $childmaxattempts attempts)</font>");
193: make_new_child($thisserver);
194:
195: }
196: else {
197: $skipping .= $thisserver.' ';
198: }
199: if($skipping) {
200: &logthis("<font color=blue>WARNING: Skipped $skipping</font>");
201:
202: }
1.30 www 203: }
1.32 foxr 204:
1.1 albertel 205: }
206:
207:
1.32 foxr 208:
1.1 albertel 209: sub make_new_child {
210:
1.30 www 211: $newserver=shift;
1.1 albertel 212: my $pid;
213: my $sigset;
1.30 www 214: &logthis("Attempting to start child for server $newserver");
1.1 albertel 215: # block signal for fork
216: $sigset = POSIX::SigSet->new(SIGINT);
217: sigprocmask(SIG_BLOCK, $sigset)
1.11 harris41 218: or die "Can't block SIGINT for fork: $!\n";
1.1 albertel 219:
1.11 harris41 220: die "fork: $!" unless defined ($pid = fork);
1.1 albertel 221:
222: if ($pid) {
223: # Parent records the child's birth and returns.
224: sigprocmask(SIG_UNBLOCK, $sigset)
1.11 harris41 225: or die "Can't unblock SIGINT for fork: $!\n";
1.30 www 226: $children{$pid} = $newserver;
1.32 foxr 227: $childpid{$newserver} = $pid;
1.1 albertel 228: return;
229: } else {
1.30 www 230: $conserver=$newserver;
1.1 albertel 231: # Child can *not* return from this subroutine.
232: $SIG{INT} = 'DEFAULT'; # make SIGINT kill us as it did before
1.18 www 233: $SIG{USR1}= \&logstatus;
234:
1.1 albertel 235: # unblock signals
236: sigprocmask(SIG_UNBLOCK, $sigset)
1.11 harris41 237: or die "Can't unblock SIGINT for fork: $!\n";
1.1 albertel 238:
239: # ----------------------------- This is the modified main program of non-forker
240:
241: $port = "$perlvar{'lonSockDir'}/$conserver";
242:
243: unlink($port);
1.18 www 244:
1.29 www 245: # -------------------------------------------------------------- Open other end
1.1 albertel 246:
1.29 www 247: &openremote($conserver);
1.32 foxr 248: &logthis("<font color=green> Connection to $conserver open </font>");
1.3 www 249: # ----------------------------------------- We're online, send delayed messages
1.18 www 250: &status("Checking for delayed messages");
1.32 foxr 251:
1.4 www 252: my @allbuffered;
1.3 www 253: my $path="$perlvar{'lonSockDir'}/delayed";
1.4 www 254: opendir(DIRHANDLE,$path);
255: @allbuffered=grep /\.$conserver$/, readdir DIRHANDLE;
256: closedir(DIRHANDLE);
1.3 www 257: my $dfname;
1.23 harris41 258: foreach (@allbuffered) {
1.30 www 259: &status("Sending delayed: $_");
1.4 www 260: $dfname="$path/$_";
1.32 foxr 261: if($DEBUG) { &logthis('Sending '.$dfname); }
1.3 www 262: my $wcmd;
263: {
264: my $dfh=IO::File->new($dfname);
1.4 www 265: $cmd=<$dfh>;
1.3 www 266: }
267: chomp($cmd);
268: my $bcmd=$cmd;
269: if ($cmd =~ /^encrypt\:/) {
270: my $rcmd=$cmd;
271: $rcmd =~ s/^encrypt\://;
272: chomp($rcmd);
273: my $cmdlength=length($rcmd);
274: $rcmd.=" ";
275: my $encrequest='';
276: for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
277: $encrequest.=
278: unpack("H16",$cipher->encrypt(substr($rcmd,$encidx,8)));
279: }
280: $cmd="enc:$cmdlength:$encrequest\n";
281: }
1.33 foxr 282: $answer = londtransaction($remotesock, $cmd, 60);
1.3 www 283: chomp($answer);
1.20 www 284:
285: if (($answer ne '') && ($@!~/timeout/)) {
1.3 www 286: unlink("$dfname");
1.30 www 287: &logthis("Delayed $cmd: >$answer<");
1.3 www 288: &logperm("S:$conserver:$bcmd");
289: }
1.23 harris41 290: }
1.32 foxr 291: if($DEBUG) { &logthis("<font color=green> Delayed transactions sent"); }
1.1 albertel 292:
293: # ------------------------------------------------------- Listen to UNIX socket
1.30 www 294: &status("Opening socket");
1.1 albertel 295: unless (
296: $server = IO::Socket::UNIX->new(Local => $port,
297: Type => SOCK_STREAM,
298: Listen => 10 )
1.5 www 299: ) {
300: my $st=120+int(rand(240));
301: &logthis(
302: "<font color=blue>WARNING: ".
1.33 foxr 303: "Can't make server socket ($st secs): .. exiting</font>");
1.5 www 304: sleep($st);
1.1 albertel 305: exit;
306: };
1.32 foxr 307:
1.1 albertel 308: # -----------------------------------------------------------------------------
309:
1.5 www 310: &logthis("<font color=green>$conserver online</font>");
311:
312: # -----------------------------------------------------------------------------
1.1 albertel 313: # begin with empty buffers
314: %inbuffer = ();
315: %outbuffer = ();
316: %ready = ();
1.35 foxr 317: %servers = (); # To be compatible with make filevector. indexed by
1.37 ! foxr 318: # File ids, values are sockets.
1.35 foxr 319: # note that the accept socket is omitted.
1.1 albertel 320:
321: tie %ready, 'Tie::RefHash';
322:
1.37 ! foxr 323: # nonblock($server);
! 324: # $select = IO::Select->new($server);
1.1 albertel 325:
326: # Main loop: check reads/accepts, check writes, check ready to process
1.37 ! foxr 327:
! 328: status("Main loop");
1.1 albertel 329: while (1) {
330: my $client;
331: my $rv;
332: my $data;
333:
1.35 foxr 334: my $infdset; # bit vec of fd's to select on input.
335:
336: my $outfdset; # Bit vec of fd's to select on output.
337:
338:
339: $infdset = MakeFileVector(\%servers);
340: $outfdset= MakeFileVector(\%outbuffer);
1.37 ! foxr 341: vec($infdset, $server->fileno, 1) = 1;
! 342: if($DEBUG) {
! 343: &logthis("Adding ".$server->fileno.
! 344: " to input select vector (listner)".
! 345: unpack("b*",$infdset)."\n");
1.1 albertel 346: }
1.37 ! foxr 347: DoSelect(\$infdset, \$outfdset); # Wait for input.
! 348: if($DEBUG) {
! 349: &logthis("Doselect completed!");
! 350: &logthis("ins = ".unpack("b*",$infdset)."\n");
! 351: &logthis("outs= ".unpack("b*",$outfdset)."\n");
! 352:
1.1 albertel 353: }
1.15 www 354:
1.37 ! foxr 355: # Checkfor new connections:
! 356: if (vec($infdset, $server->fileno, 1)) {
! 357: if($DEBUG) {
! 358: &logthis("New connection established");
! 359: }
! 360: # accept a new connection
! 361: &status("Accept new connection: $conserver");
! 362: $client = $server->accept();
! 363: if($DEBUG) {
! 364: &logthis("New client fd = ".$client->fileno."\n");
! 365: }
! 366: $servers{$client->fileno} = $client;
! 367: nonblock($client);
! 368: }
! 369: HandleInput($infdset, \%servers, \%inbuffer, \%outbuffer, \%ready);
! 370: HandleOutput($outfdset, \%servers, \%outbuffer, \%inbuffer,
! 371: \%ready);
! 372: # -------------------------------------------------------- Wow, connection lost
1.15 www 373:
1.37 ! foxr 374: }
! 375:
1.1 albertel 376: }
377: }
1.25 albertel 378:
1.1 albertel 379: # ------------------------------------------------------- End of make_new_child
380:
1.35 foxr 381:
382: #
383: # Make a vector of file descriptors to wait for in a select.
384: # parameters:
385: # \%fdhash -reference to a hash which has IO::Socket's as indices.
386: # We only care about the indices, not the values.
387: # A select vector is created from all indices of the hash.
388:
389: sub MakeFileVector
390: {
391: my $fdhash = shift;
392: my $selvar = "";
393:
1.37 ! foxr 394: foreach $socket (keys %$fdhash) {
! 395: if($DEBUG) {
! 396: &logthis("Adding ".$socket.
! 397: "to select vector. (client)\n");
! 398: }
! 399: vec($selvar, $socket, 1) = 1;
1.35 foxr 400: }
401: return $selvar;
402: }
403:
404:
405: #
406: # HandleOutput:
407: # Processes output on a buffered set of file descriptors which are
408: # ready to be read.
409: # Parameters:
1.37 ! foxr 410: # $selvector - Vector of file descriptors which are writable.
1.35 foxr 411: # \%sockets - Vector of socket references indexed by socket.
412: # \%buffers - Reference to a hash containing output buffers.
413: # Hashes are indexed by sockets. The file descriptors of some
414: # of those sockets will be present in $selvector.
415: # For each one of those, we will attempt to write the output
416: # buffer to the socket. Note that we will assume that
417: # the sockets are being run in non blocking mode.
418: # \%inbufs - Reference to hash containing input buffers.
419: # \%readys - Reference to hash containing flags for items with complete
420: # requests.
421: #
422: sub HandleOutput
423: {
424: my $selvector = shift;
425: my $sockets = shift;
426: my $buffers = shift;
427: my $inbufs = shift;
428: my $readys = shift;
1.37 ! foxr 429: my $sock;
1.35 foxr 430:
1.37 ! foxr 431: if($DEBUG) {
! 432: &logthis("HandleOutput entered\n");
! 433: }
! 434:
! 435: foreach $sock (keys %$sockets) {
1.35 foxr 436: my $socket = $sockets->{$sock};
1.37 ! foxr 437: if(vec($selvector, $sock, 1)) { # $socket is writable.
! 438: if($DEBUG) {
! 439: &logthis("Sending $buffers->{$sock} \n");
! 440: }
! 441: my $rv = $socket->send($buffers->{$sock}, 0);
1.35 foxr 442: $errno = $!;
443: unless ($buffers->{$sock} eq "con_lost\n") {
444: unless (defined $rv) { # Write failed... could be EINTR
445: unless ($errno == POSIX::EINTR) {
446: &logthis("Write failed on writable socket");
447: } # EINTR is not an error .. just retry.
448: next;
449: }
450: if( ($rv == length $buffers->{$sock}) ||
451: ($errno == POSIX::EWOULDBLOCK) ||
452: ($errno == POSIX::EAGAIN) || # same as above.
453: ($errno == POSIX::EINTR) || # signal during IO
454: ($errno == 0)) {
455: substr($buffers->{$sock}, 0, $rv)=""; # delete written part
456: delete $buffers->{$sock} unless length $buffers->{$sock};
457: } else {
458: # For some reason the write failed with an error code
459: # we didn't look for. Shutdown the socket.
460: &logthis("Unable to write data with ".$errno.": ".
461: "Dropping data: ".length($buffers->{$sock}).
462: ", $rv");
463: #
464: # kill off the buffers in the hash:
465:
466: delete $buffers->{$sock};
467: delete $inbufs->{$sock};
468: delete $readys->{$sock};
469:
1.37 ! foxr 470: close($socket); # Close the client socket.
1.35 foxr 471: next;
472: }
473: } else { # Kludgy way to mark lond connection lost.
474: &logthis(
475: "<font color=red>CRITICAL lond connection lost</font>");
476: status("Connection lost");
477: $remotesock->shutdown(2);
478: &logthis("Attempting to open a new connection");
1.37 ! foxr 479: &openremote($conserver);
1.35 foxr 480: }
481:
482: }
483: }
484:
485: }
486: #
487: # HandleInput - Deals with input on client sockets.
488: # Each socket has an associated input buffer.
489: # For each readable socket, the currently available
490: # data is appended to this buffer.
491: # If necessary, the buffer is created.
492: # On various failures, we may shutdown the client.
493: # Parameters:
494: # $selvec - Vector of readable sockets.
495: # \%sockets - Refers to the Hash of sockets indexed by sockets.
496: # Each of these may or may not have it's fd bit set
497: # in the $selvec.
498: # \%ibufs - Refers to the hash of input buffers indexed by socket.
499: # \%obufs - Hash of output buffers indexed by socket.
500: # \%ready - Hash of ready flags indicating the existence of a completed
501: # Request.
502: sub HandleInput
503: {
504:
505: # Marshall the parameters. Note that the hashes are actually
506: # references not values.
507:
508: my $selvec = shift;
509: my $sockets = shift;
510: my $ibufs = shift;
511: my $obufs = shift;
512: my $ready = shift;
1.37 ! foxr 513: my $sock;
1.35 foxr 514:
1.37 ! foxr 515: &logthis("Entered HandleInput\n");
! 516: foreach $sock (keys %$sockets) {
1.35 foxr 517: my $socket = $sockets->{$sock};
1.37 ! foxr 518: if(vec($selvec, $sock, 1)) { # Socket which is readable.
1.35 foxr 519:
520: # Attempt to read the data and do error management.
521: my $data = '';
1.37 ! foxr 522: my $rv = $socket->recv($data, POSIX::BUFSIZ, 0);
! 523: if($DEBUG) {
! 524: &logthis("Received $data from socket");
! 525: }
1.35 foxr 526: unless (defined($rv) && length $data) {
527:
528: # Read an end of file.. this is a disconnect from the peer.
529:
530: delete $sockets->{$sock};
531: delete $ibufs->{$sock};
532: delete $obufs->{$sock};
533: delete $ready->{$sock};
534:
535: status("Idle");
1.37 ! foxr 536: close $socket;
1.35 foxr 537: next;
538: }
539: # Append the read data to the input buffer. If the buffer
540: # now contains a \n the request is complete and we can
541: # mark this in the $ready hash (one request for each \n.)
542:
543: $ibufs->{$sock} .= $data;
544: while($ibufs->{$sock} =~ s/(.*\n)//) {
545: push(@{$ready->{$sock}}, $1);
546: }
547:
548: }
549: }
550: # Now handle any requests which are ready:
551:
552: foreach $client (keys %ready) {
553: handle($client);
1.36 foxr 554: }
555: }
556:
557: # DoSelect: does a select with no timeout. On signal (errno == EINTR),
558: # the select is retried until there are items in the returned
559: # vectors.
560: #
561: # Parameters:
562: # \$readvec - Reference to a vector of file descriptors to
563: # check for readability.
564: # \$writevec - Reference to a vector of file descriptors to check for
565: # writability.
566: # On exit, the referents are modified with vectors indicating which
567: # file handles are readable/writable.
568: #
569: sub DoSelect {
570: my $readvec = shift;
571: my $writevec= shift;
572: my $outs;
573: my $ins;
574:
575: while (1) {
1.37 ! foxr 576: my $nfds = select( $ins = $$readvec, $outs = $$writevec, undef, undef);
! 577: if($nfds) {
! 578: if($DEBUG) {
! 579: &logthis("select exited with ".$nfds." fds\n");
! 580: &logthis("ins = ".unpack("b*",$ins).
! 581: " readvec = ".unpack("b*",$$readvec)."\n");
! 582: &logthis("outs = ".unpack("b*",$outs).
! 583: " writevec = ".unpack("b*",$$writevec)."\n");
! 584: }
1.36 foxr 585: $$readvec = $ins;
586: $$writevec = $outs;
587: return;
588: } else {
1.37 ! foxr 589: if($DEBUG) {
! 590: &logthis("Select exited with no bits set in mask\n");
! 591: }
1.36 foxr 592: die "Select failed" unless $! == EINTR;
593: }
1.35 foxr 594: }
595: }
596:
1.1 albertel 597: # handle($socket) deals with all pending requests for $client
1.35 foxr 598: #
1.1 albertel 599: sub handle {
600: # requests are in $ready{$client}
601: # send output to $outbuffer{$client}
602: my $client = shift;
603: my $request;
604: foreach $request (@{$ready{$client}}) {
605: # ============================================================= Process request
606: # $request is the text of the request
607: # put text of reply into $outbuffer{$client}
1.29 www 608: # ------------------------------------------------------------ Is this the end?
1.33 foxr 609: chomp($request);
1.32 foxr 610: if($DEBUG) {
611: &logthis("<font color=green> Request $request processing starts</font>");
612: }
1.29 www 613: if ($request eq "close_connection_exit\n") {
1.30 www 614: &status("Request close connection");
1.29 www 615: &logthis(
1.32 foxr 616: "<font color=red>CRITICAL: Request Close Connection ... exiting</font>");
1.29 www 617: $remotesock->shutdown(2);
618: $server->close();
619: exit;
620: }
1.1 albertel 621: # -----------------------------------------------------------------------------
622: if ($request =~ /^encrypt\:/) {
623: my $cmd=$request;
624: $cmd =~ s/^encrypt\://;
625: chomp($cmd);
626: my $cmdlength=length($cmd);
627: $cmd.=" ";
628: my $encrequest='';
629: for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
630: $encrequest.=
631: unpack("H16",$cipher->encrypt(substr($cmd,$encidx,8)));
632: }
1.33 foxr 633: $request="enc:$cmdlength:$encrequest";
1.1 albertel 634: }
1.19 www 635: # --------------------------------------------------------------- Main exchange
1.33 foxr 636: $answer = londtransaction($remotesock, $request, 300);
637:
638: if($DEBUG) {
639: &logthis("<font color=green> Request data exchange complete");
640: }
641: if ($@=~/timeout/) {
642: $answer='';
643: &logthis(
644: "<font color=red>CRITICAL: Timeout: $request</font>");
645: }
1.19 www 646:
647:
1.1 albertel 648: if ($answer) {
649: if ($answer =~ /^enc/) {
650: my ($cmd,$cmdlength,$encinput)=split(/:/,$answer);
651: chomp($encinput);
652: $answer='';
653: for (my $encidx=0;$encidx<length($encinput);$encidx+=16) {
654: $answer.=$cipher->decrypt(
655: pack("H16",substr($encinput,$encidx,16))
656: );
657: }
658: $answer=substr($answer,0,$cmdlength);
659: $answer.="\n";
660: }
1.33 foxr 661: if($DEBUG) {
662: &logthis("sending $answer to client\n");
663: }
1.1 albertel 664: $outbuffer{$client} .= $answer;
665: } else {
666: $outbuffer{$client} .= "con_lost\n";
667: }
668:
1.30 www 669: &status("Completed: $request");
1.32 foxr 670: if($DEBUG) {
671: &logthis("<font color=green> Request processing complete</font>");
672: }
1.1 albertel 673: # ===================================================== Done processing request
674: }
675: delete $ready{$client};
676: # -------------------------------------------------------------- End non-forker
1.32 foxr 677: if($DEBUG) {
678: &logthis("<font color=green> requests for child handled</font>");
679: }
1.1 albertel 680: }
681: # ---------------------------------------------------------- End make_new_child
682:
683: # nonblock($socket) puts socket into nonblocking mode
684: sub nonblock {
685: my $socket = shift;
686: my $flags;
687:
688:
689: $flags = fcntl($socket, F_GETFL, 0)
1.11 harris41 690: or die "Can't get flags for socket: $!\n";
1.1 albertel 691: fcntl($socket, F_SETFL, $flags | O_NONBLOCK)
1.11 harris41 692: or die "Can't make socket nonblocking: $!\n";
1.29 www 693: }
694:
695:
696: sub openremote {
697: # ---------------------------------------------------- Client to network server
698:
699: my $conserver=shift;
700:
1.30 www 701: &status("Opening TCP");
1.32 foxr 702: my $st=120+int(rand(240)); # Sleep before opening:
1.29 www 703:
704: unless (
705: $remotesock = IO::Socket::INET->new(PeerAddr => $hostip{$conserver},
706: PeerPort => $perlvar{'londPort'},
707: Proto => "tcp",
708: Type => SOCK_STREAM)
709: ) {
1.32 foxr 710:
1.29 www 711: &logthis(
1.33 foxr 712: "<font color=blue>WARNING: Couldn't connect to $conserver ($st secs): </font>");
1.29 www 713: sleep($st);
714: exit;
715: };
716: # ----------------------------------------------------------------- Init dialog
717:
1.32 foxr 718: &logthis("<font color=green>INFO Connected to $conserver, initing </font>");
1.29 www 719: &status("Init dialogue: $conserver");
720:
1.33 foxr 721: $answer = londtransaction($remotesock, "init", 60);
722: chomp($answer);
723: $answer = londtransaction($remotesock, $answer, 60);
724: chomp($answer);
1.29 www 725:
726: if ($@=~/timeout/) {
1.32 foxr 727: &logthis("Timed out during init.. exiting");
1.29 www 728: exit;
729: }
730:
731: if ($answer ne 'ok') {
1.30 www 732: &logthis("Init reply: >$answer<");
1.29 www 733: my $st=120+int(rand(240));
734: &logthis(
1.30 www 735: "<font color=blue>WARNING: Init failed ($st secs)</font>");
1.29 www 736: sleep($st);
737: exit;
738: }
739:
740: sleep 5;
1.30 www 741: &status("Ponging");
1.29 www 742: print $remotesock "pong\n";
743: $answer=<$remotesock>;
744: chomp($answer);
1.30 www 745: if ($answer!~/^$conserver/) {
746: &logthis("Pong reply: >$answer<");
1.29 www 747: }
748: # ----------------------------------------------------------- Initialize cipher
749:
1.30 www 750: &status("Initialize cipher");
1.29 www 751: print $remotesock "ekey\n";
752: my $buildkey=<$remotesock>;
753: my $key=$conserver.$perlvar{'lonHostID'};
754: $key=~tr/a-z/A-Z/;
755: $key=~tr/G-P/0-9/;
756: $key=~tr/Q-Z/0-9/;
757: $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
758: $key=substr($key,0,32);
759: my $cipherkey=pack("H32",$key);
760: if ($cipher=new IDEA $cipherkey) {
1.30 www 761: &logthis("Secure connection initialized");
1.29 www 762: } else {
763: my $st=120+int(rand(240));
764: &logthis(
765: "<font color=blue>WARNING: ".
1.30 www 766: "Could not establish secure connection ($st secs)!</font>");
1.29 www 767: sleep($st);
768: exit;
769: }
1.32 foxr 770: &logthis("<font color=green> Remote open success </font>");
1.8 harris41 771: }
1.30 www 772:
773:
774:
775: # grabs exception and records it to log before exiting
776: sub catchexception {
777: my ($signal)=@_;
778: $SIG{QUIT}='DEFAULT';
779: $SIG{__DIE__}='DEFAULT';
780: chomp($signal);
781: &logthis("<font color=red>CRITICAL: "
782: ."ABNORMAL EXIT. Child $$ for server [$wasserver] died through "
1.33 foxr 783: ."\"$signal\" with parameter </font>");
784: die("Signal abend");
1.30 www 785: }
786:
787: # -------------------------------------- Routines to see if other box available
788:
1.32 foxr 789: #sub online {
790: # my $host=shift;
791: # &status("Pinging ".$host);
792: # my $p=Net::Ping->new("tcp",20);
793: # my $online=$p->ping("$host");
794: # $p->close();
795: # undef ($p);
796: # return $online;
797: #}
1.30 www 798:
799: sub connected {
800: my ($local,$remote)=@_;
801: &status("Checking connection $local to $remote");
802: $local=~s/\W//g;
803: $remote=~s/\W//g;
804:
805: unless ($hostname{$local}) { return 'local_unknown'; }
806: unless ($hostname{$remote}) { return 'remote_unknown'; }
807:
1.32 foxr 808: #unless (&online($hostname{$local})) { return 'local_offline'; }
1.30 www 809:
810: my $ua=new LWP::UserAgent;
811:
812: my $request=new HTTP::Request('GET',
813: "http://".$hostname{$local}.'/cgi-bin/ping.pl?'.$remote);
814:
815: my $response=$ua->request($request);
816:
817: unless ($response->is_success) { return 'local_error'; }
818:
819: my $reply=$response->content;
820: $reply=(split("\n",$reply))[0];
821: $reply=~s/\W//g;
822: if ($reply ne $remote) { return $reply; }
823: return 'ok';
824: }
825:
826:
827:
828: sub hangup {
829: foreach (keys %children) {
830: $wasserver=$children{$_};
831: &status("Closing $wasserver");
832: &logthis('Closing '.$wasserver.': '.&subreply('exit',$wasserver));
833: &status("Kill PID $_ for $wasserver");
834: kill ('INT',$_);
835: }
836: }
837:
838: sub HUNTSMAN { # signal handler for SIGINT
839: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
840: &hangup();
841: my $execdir=$perlvar{'lonDaemons'};
842: unlink("$execdir/logs/lonc.pid");
843: &logthis("<font color=red>CRITICAL: Shutting down</font>");
844: exit; # clean up with dignity
845: }
846:
847: sub HUPSMAN { # signal handler for SIGHUP
848: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
849: &hangup();
850: &logthis("<font color=red>CRITICAL: Restarting</font>");
851: unlink("$execdir/logs/lonc.pid");
852: my $execdir=$perlvar{'lonDaemons'};
853: exec("$execdir/lonc"); # here we go again
854: }
855:
856: sub checkchildren {
857: &initnewstatus();
858: &logstatus();
859: &logthis('Going to check on the children');
860: foreach (sort keys %children) {
861: sleep 1;
862: unless (kill 'USR1' => $_) {
863: &logthis ('<font color=red>CRITICAL: Child '.$_.' is dead</font>');
864: &logstatus($$.' is dead');
865: }
866: }
867: }
868:
869: sub USRMAN {
870: &logthis("USR1: Trying to establish connections again");
871: %childatt=();
872: &checkchildren();
873: }
874:
875: # -------------------------------------------------- Non-critical communication
876: sub subreply {
877: my ($cmd,$server)=@_;
878: my $answer='';
879: if ($server ne $perlvar{'lonHostID'}) {
880: my $peerfile="$perlvar{'lonSockDir'}/$server";
881: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
882: Type => SOCK_STREAM,
883: Timeout => 10)
884: or return "con_lost";
885:
886:
1.33 foxr 887: $answer = londtransaction($sclient, $cmd, 10);
888:
1.30 www 889: if ((!$answer) || ($@=~/timeout/)) { $answer="con_lost"; }
890: $SIG{ALRM}='DEFAULT';
891: $SIG{__DIE__}=\&catchexception;
892: } else { $answer='self_reply'; }
893: return $answer;
894: }
895:
896: # --------------------------------------------------------------------- Logging
897:
898: sub logthis {
899: my $message=shift;
900: my $execdir=$perlvar{'lonDaemons'};
901: my $fh=IO::File->new(">>$execdir/logs/lonc.log");
902: my $now=time;
903: my $local=localtime($now);
904: $lastlog=$local.': '.$message;
905: print $fh "$local ($$) [$conserver] [$status]: $message\n";
906: }
907:
1.33 foxr 908: #-------------------------------------- londtransaction:
909: #
910: # Performs a transaction with lond with timeout support.
911: # result = londtransaction(socket,request,timeout)
912: #
913: sub londtransaction {
914: my ($socket, $request, $tmo) = @_;
915:
916: if($DEBUG) {
917: &logthis("londtransaction request: $request");
918: }
919:
920: # Set the signal handlers: ALRM for timeout and disble the others.
921:
922: $SIG{ALRM} = sub { die "timeout" };
923: $SIG{__DIE__} = 'DEFAULT';
924:
925: # Disable all but alarm so that only that can interupt the
926: # send /receive.
927: #
928: my $sigset = POSIX::SigSet->new(QUIT, USR1, HUP, INT, TERM);
929: my $priorsigs = POSIX::SigSet->new;
930: unless (defined sigprocmask(SIG_BLOCK, $sigset, $priorsigs)) {
931: &logthis("<font color=red> CRITICAL -- londtransaction ".
932: "failed to block signals </font>");
933: die "could not block signals in londtransaction";
934: }
935: $answer = '';
936: #
937: # Send request to lond.
938: #
939: eval {
940: alarm($tmo);
941: print $socket "$request\n";
942: alarm(0);
943: };
944: # If request didn't timeout, try for the response.
945: #
946:
947: if ($@!~/timeout/) {
948: eval {
949: alarm($tmo);
950: $answer = <$socket>;
951: if($DEBUG) {
952: &logthis("Received $answer in londtransaction");
953: }
954: alarm(0);
955: };
956: } else {
957: if($DEBUG) {
958: &logthis("Timeout on send in londtransaction");
959: }
960: }
961: if( ($@ =~ /timeout/) && ($DEBUG)) {
962: &logthis("Timeout on receive in londtransaction");
963: }
964: #
965: # Restore the initial sigmask set.
966: #
967: unless (defined sigprocmask(SIG_UNBLOCK, $priorsigs)) {
968: &logthis("<font color=red> CRITICAL -- londtransaction ".
969: "failed to re-enable signal processing. </font>");
970: die "londtransaction failed to re-enable signals";
971: }
972: #
973: # go back to the prior handler set.
974: #
975: $SIG{ALRM} = 'DEFAULT';
976: $SIG{__DIE__} = \&cathcexception;
977:
978: # chomp $answer;
979: if ($DEBUG) {
980: &logthis("Returning $answer in londtransaction");
981: }
982: return $answer;
983:
984: }
1.30 www 985:
986: sub logperm {
987: my $message=shift;
988: my $execdir=$perlvar{'lonDaemons'};
989: my $now=time;
990: my $local=localtime($now);
991: my $fh=IO::File->new(">>$execdir/logs/lonnet.perm.log");
992: print $fh "$now:$message:$local\n";
993: }
994: # ------------------------------------------------------------------ Log status
995:
996: sub logstatus {
997: my $docdir=$perlvar{'lonDocRoot'};
998: my $fh=IO::File->new(">>$docdir/lon-status/loncstatus.txt");
999: print $fh $$."\t".$conserver."\t".$status."\t".$lastlog."\n";
1000: }
1001:
1002: sub initnewstatus {
1003: my $docdir=$perlvar{'lonDocRoot'};
1004: my $fh=IO::File->new(">$docdir/lon-status/loncstatus.txt");
1005: my $now=time;
1006: my $local=localtime($now);
1007: print $fh "LONC status $local - parent $$\n\n";
1008: }
1009:
1010: # -------------------------------------------------------------- Status setting
1011:
1012: sub status {
1013: my $what=shift;
1014: my $now=time;
1015: my $local=localtime($now);
1016: $status=$local.': '.$what;
1017: }
1018:
1019:
1.1 albertel 1020:
1.23 harris41 1021: # ----------------------------------- POD (plain old documentation, CPAN style)
1022:
1023: =head1 NAME
1024:
1025: lonc - LON TCP-MySQL-Server Daemon for handling database requests.
1026:
1027: =head1 SYNOPSIS
1028:
1.31 harris41 1029: Usage: B<lonc>
1030:
1.23 harris41 1031: Should only be run as user=www. This is a command-line script which
1.31 harris41 1032: is invoked by B<loncron>. There is no expectation that a typical user
1033: will manually start B<lonc> from the command-line. (In other words,
1034: DO NOT START B<lonc> YOURSELF.)
1.23 harris41 1035:
1036: =head1 DESCRIPTION
1037:
1038: Provides persistent TCP connections to the other servers in the network
1039: through multiplexed domain sockets
1040:
1.31 harris41 1041: B<lonc> forks off children processes that correspond to the other servers
1042: in the network. Management of these processes can be done at the
1043: parent process level or the child process level.
1044:
1.33 foxr 1045: After forking off the children, B<lonc> the B<parent>
1046: executes a main loop which simply waits for processes to exit.
1047: As a process exits, a new process managing a link to the same
1048: peer as the exiting process is created.
1049:
1.31 harris41 1050: B<logs/lonc.log> is the location of log messages.
1051:
1052: The process management is now explained in terms of linux shell commands,
1053: subroutines internal to this code, and signal assignments:
1054:
1055: =over 4
1056:
1057: =item *
1058:
1059: PID is stored in B<logs/lonc.pid>
1060:
1061: This is the process id number of the parent B<lonc> process.
1062:
1063: =item *
1064:
1065: SIGTERM and SIGINT
1066:
1067: Parent signal assignment:
1068: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
1069:
1070: Child signal assignment:
1071: $SIG{INT} = 'DEFAULT'; (and SIGTERM is DEFAULT also)
1072: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
1073: to restart a new child.)
1074:
1075: Command-line invocations:
1076: B<kill> B<-s> SIGTERM I<PID>
1077: B<kill> B<-s> SIGINT I<PID>
1078:
1079: Subroutine B<HUNTSMAN>:
1080: This is only invoked for the B<lonc> parent I<PID>.
1081: This kills all the children, and then the parent.
1082: The B<lonc.pid> file is cleared.
1083:
1084: =item *
1085:
1086: SIGHUP
1087:
1088: Current bug:
1089: This signal can only be processed the first time
1090: on the parent process. Subsequent SIGHUP signals
1091: have no effect.
1092:
1093: Parent signal assignment:
1094: $SIG{HUP} = \&HUPSMAN;
1095:
1096: Child signal assignment:
1097: none (nothing happens)
1098:
1099: Command-line invocations:
1100: B<kill> B<-s> SIGHUP I<PID>
1101:
1102: Subroutine B<HUPSMAN>:
1103: This is only invoked for the B<lonc> parent I<PID>,
1104: This kills all the children, and then the parent.
1105: The B<lonc.pid> file is cleared.
1106:
1107: =item *
1108:
1109: SIGUSR1
1110:
1111: Parent signal assignment:
1112: $SIG{USR1} = \&USRMAN;
1113:
1114: Child signal assignment:
1115: $SIG{USR1}= \&logstatus;
1116:
1117: Command-line invocations:
1118: B<kill> B<-s> SIGUSR1 I<PID>
1119:
1120: Subroutine B<USRMAN>:
1121: When invoked for the B<lonc> parent I<PID>,
1122: SIGUSR1 is sent to all the children, and the status of
1123: each connection is logged.
1124:
1.23 harris41 1125:
1.31 harris41 1126: =back
1.23 harris41 1127:
1128: =head1 PREREQUISITES
1129:
1130: POSIX
1131: IO::Socket
1132: IO::Select
1133: IO::File
1134: Socket
1135: Fcntl
1136: Tie::RefHash
1137: Crypt::IDEA
1138:
1139: =head1 COREQUISITES
1140:
1141: =head1 OSNAMES
1142:
1143: linux
1144:
1145: =head1 SCRIPT CATEGORIES
1146:
1147: Server/Process
1148:
1149: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>