File:  [LON-CAPA] / loncom / lond
Revision 1.95: download - view: text, annotated - select for diffs
Mon Sep 9 14:04:02 2002 UTC (21 years, 7 months ago) by harris41
Branches: MAIN
CVS tags: HEAD
loncapa_apache.conf should not be directly specified (and certainly not
before loncapa.conf)

    1: #!/usr/bin/perl
    2: # The LearningOnline Network
    3: # lond "LON Daemon" Server (port "LOND" 5663)
    4: #
    5: # $Id: lond,v 1.95 2002/09/09 14:04:02 harris41 Exp $
    6: #
    7: # Copyright Michigan State University Board of Trustees
    8: #
    9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
   10: #
   11: # LON-CAPA is free software; you can redistribute it and/or modify
   12: # it under the terms of the GNU General Public License as published by
   13: # the Free Software Foundation; either version 2 of the License, or
   14: # (at your option) any later version.
   15: #
   16: # LON-CAPA is distributed in the hope that it will be useful,
   17: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   18: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   19: # GNU General Public License for more details.
   20: #
   21: # You should have received a copy of the GNU General Public License
   22: # along with LON-CAPA; if not, write to the Free Software
   23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   24: #
   25: # /home/httpd/html/adm/gpl.txt
   26: #
   27: # http://www.lon-capa.org/
   28: #
   29: # 5/26/99,6/4,6/10,6/11,6/14,6/15,6/26,6/28,6/30,
   30: # 7/8,7/9,7/10,7/12,7/17,7/19,9/21,
   31: # 10/7,10/8,10/9,10/11,10/13,10/15,11/4,11/16,
   32: # 12/7,12/15,01/06,01/11,01/12,01/14,2/8,
   33: # 03/07,05/31 Gerd Kortemeyer
   34: # 06/26 Scott Harrison
   35: # 06/29,06/30,07/14,07/15,07/17,07/20,07/25,09/18 Gerd Kortemeyer
   36: # 12/05 Scott Harrison
   37: # 12/05,12/13,12/29 Gerd Kortemeyer
   38: # YEAR=2001
   39: # Jan 01 Scott Harrison
   40: # 02/12 Gerd Kortemeyer
   41: # 03/15 Scott Harrison
   42: # 03/24 Gerd Kortemeyer
   43: # 04/02 Scott Harrison
   44: # 05/11,05/28,08/30 Gerd Kortemeyer
   45: # 9/30,10/22,11/13,11/15,11/16 Scott Harrison
   46: # 11/26,11/27 Gerd Kortemeyer
   47: # 12/20 Scott Harrison
   48: # 12/22 Gerd Kortemeyer
   49: # YEAR=2002
   50: # 01/20/02,02/05 Gerd Kortemeyer
   51: # 02/05 Guy Albertelli
   52: # 02/07 Scott Harrison
   53: # 02/12 Gerd Kortemeyer
   54: # 02/19 Matthew Hall
   55: # 02/25 Gerd Kortemeyer
   56: # 05/11 Scott Harrison
   57: ###
   58: 
   59: # based on "Perl Cookbook" ISBN 1-56592-243-3
   60: # preforker - server who forks first
   61: # runs as a daemon
   62: # HUPs
   63: # uses IDEA encryption
   64: 
   65: use lib '/home/httpd/lib/perl/';
   66: use LONCAPA::Configuration;
   67: 
   68: use IO::Socket;
   69: use IO::File;
   70: use Apache::File;
   71: use Symbol;
   72: use POSIX;
   73: use Crypt::IDEA;
   74: use LWP::UserAgent();
   75: use GDBM_File;
   76: use Authen::Krb4;
   77: use Authen::Krb5;
   78: use lib '/home/httpd/lib/perl/';
   79: use localauth;
   80: 
   81: my $DEBUG = 0;		       # Non zero to enable debug log entries.
   82: 
   83: my $status='';
   84: my $lastlog='';
   85: 
   86: # grabs exception and records it to log before exiting
   87: sub catchexception {
   88:     my ($error)=@_;
   89:     $SIG{'QUIT'}='DEFAULT';
   90:     $SIG{__DIE__}='DEFAULT';
   91:     &logthis("<font color=red>CRITICAL: "
   92:      ."ABNORMAL EXIT. Child $$ for server $wasserver died through "
   93:      ."a crash with this error msg->[$error]</font>");
   94:     &logthis('Famous last words: '.$status.' - '.$lastlog);
   95:     if ($client) { print $client "error: $error\n"; }
   96:     $server->close();
   97:     die($error);
   98: }
   99: 
  100: sub timeout {
  101:     &logthis("<font color=ref>CRITICAL: TIME OUT ".$$."</font>");
  102:     &catchexception('Timeout');
  103: }
  104: # -------------------------------- Set signal handlers to record abnormal exits
  105: 
  106: $SIG{'QUIT'}=\&catchexception;
  107: $SIG{__DIE__}=\&catchexception;
  108: 
  109: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
  110: &status("Read loncapa.conf and loncapa_apache.conf");
  111: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
  112: my %perlvar=%{$perlvarref};
  113: undef $perlvarref;
  114: 
  115: # ----------------------------- Make sure this process is running from user=www
  116: my $wwwid=getpwnam('www');
  117: if ($wwwid!=$<) {
  118:    $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
  119:    $subj="LON: $perlvar{'lonHostID'} User ID mismatch";
  120:    system("echo 'User ID mismatch.  lond must be run as user www.' |\
  121:  mailto $emailto -s '$subj' > /dev/null");
  122:    exit 1;
  123: }
  124: 
  125: # --------------------------------------------- Check if other instance running
  126: 
  127: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
  128: 
  129: if (-e $pidfile) {
  130:    my $lfh=IO::File->new("$pidfile");
  131:    my $pide=<$lfh>;
  132:    chomp($pide);
  133:    if (kill 0 => $pide) { die "already running"; }
  134: }
  135: 
  136: $PREFORK=4; # number of children to maintain, at least four spare
  137: 
  138: # ------------------------------------------------------------- Read hosts file
  139: 
  140: open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
  141: 
  142: while ($configline=<CONFIG>) {
  143:     my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
  144:     chomp($ip); $ip=~s/\D+$//;
  145:     $hostid{$ip}=$id;
  146:     if ($id eq $perlvar{'lonHostID'}) { $thisserver=$name; }
  147:     $PREFORK++;
  148: }
  149: close(CONFIG);
  150: 
  151: # establish SERVER socket, bind and listen.
  152: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
  153:                                 Type      => SOCK_STREAM,
  154:                                 Proto     => 'tcp',
  155:                                 Reuse     => 1,
  156:                                 Listen    => 10 )
  157:   or die "making socket: $@\n";
  158: 
  159: # --------------------------------------------------------- Do global variables
  160: 
  161: # global variables
  162: 
  163: $MAX_CLIENTS_PER_CHILD  = 50;        # number of clients each child should 
  164:                                     # process
  165: %children               = ();       # keys are current child process IDs
  166: $children               = 0;        # current number of children
  167: 
  168: sub REAPER {                        # takes care of dead children
  169:     $SIG{CHLD} = \&REAPER;
  170:     my $pid = wait;
  171:     if (defined($children{$pid})) {
  172: 	&logthis("Child $pid died");
  173: 	$children --;
  174: 	delete $children{$pid};
  175:     } else {
  176: 	&logthis("Unknown Child $pid died");
  177:     }
  178: }
  179: 
  180: sub HUNTSMAN {                      # signal handler for SIGINT
  181:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
  182:     kill 'INT' => keys %children;
  183:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
  184:     my $execdir=$perlvar{'lonDaemons'};
  185:     unlink("$execdir/logs/lond.pid");
  186:     &logthis("<font color=red>CRITICAL: Shutting down</font>");
  187:     exit;                           # clean up with dignity
  188: }
  189: 
  190: sub HUPSMAN {                      # signal handler for SIGHUP
  191:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
  192:     kill 'INT' => keys %children;
  193:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
  194:     &logthis("<font color=red>CRITICAL: Restarting</font>");
  195:     unlink("$execdir/logs/lond.pid");
  196:     my $execdir=$perlvar{'lonDaemons'};
  197:     exec("$execdir/lond");         # here we go again
  198: }
  199: 
  200: sub checkchildren {
  201:     &initnewstatus();
  202:     &logstatus();
  203:     &logthis('Going to check on the children');
  204:     $docdir=$perlvar{'lonDocRoot'};
  205:     foreach (sort keys %children) {
  206: 	sleep 1;
  207:         unless (kill 'USR1' => $_) {
  208: 	    &logthis ('Child '.$_.' is dead');
  209:             &logstatus($$.' is dead');
  210:         } 
  211:     }
  212:     sleep 5;
  213:     foreach (sort keys %children) {
  214:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
  215: 	    &logthis('Child '.$_.' did not respond');
  216: 	    kill 9 => $_;
  217: 	    $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
  218: 	    $subj="LON: $perlvar{'lonHostID'} killed lond process $_";
  219: 	    my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
  220: 	    $execdir=$perlvar{'lonDaemons'};
  221: 	    $result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`
  222:         }
  223:     }
  224: }
  225: 
  226: # --------------------------------------------------------------------- Logging
  227: 
  228: sub logthis {
  229:     my $message=shift;
  230:     my $execdir=$perlvar{'lonDaemons'};
  231:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
  232:     my $now=time;
  233:     my $local=localtime($now);
  234:     $lastlog=$local.': '.$message;
  235:     print $fh "$local ($$): $message\n";
  236: }
  237: 
  238: # ------------------------- Conditional log if $DEBUG true.
  239: sub Debug {
  240:     my $message = shift;
  241:     if($DEBUG) {
  242: 	&logthis($message);
  243:     }
  244: }
  245: # ------------------------------------------------------------------ Log status
  246: 
  247: sub logstatus {
  248:     my $docdir=$perlvar{'lonDocRoot'};
  249:     {
  250:     my $fh=IO::File->new(">>$docdir/lon-status/londstatus.txt");
  251:     print $fh $$."\t".$status."\t".$lastlog."\n";
  252:     $fh->close();
  253:     }
  254:     {
  255: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
  256:         print $fh $status."\n".$lastlog."\n".time;
  257:         $fh->close();
  258:     }
  259: }
  260: 
  261: sub initnewstatus {
  262:     my $docdir=$perlvar{'lonDocRoot'};
  263:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
  264:     my $now=time;
  265:     my $local=localtime($now);
  266:     print $fh "LOND status $local - parent $$\n\n";
  267:     opendir(DIR,"$docdir/lon-status/londchld");
  268:     while ($filename=readdir(DIR)) {
  269:         unlink("$docdir/lon-status/londchld/$filename");
  270:     }
  271:     closedir(DIR);
  272: }
  273: 
  274: # -------------------------------------------------------------- Status setting
  275: 
  276: sub status {
  277:     my $what=shift;
  278:     my $now=time;
  279:     my $local=localtime($now);
  280:     $status=$local.': '.$what;
  281: }
  282: 
  283: # -------------------------------------------------------- Escape Special Chars
  284: 
  285: sub escape {
  286:     my $str=shift;
  287:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
  288:     return $str;
  289: }
  290: 
  291: # ----------------------------------------------------- Un-Escape Special Chars
  292: 
  293: sub unescape {
  294:     my $str=shift;
  295:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  296:     return $str;
  297: }
  298: 
  299: # ----------------------------------------------------------- Send USR1 to lonc
  300: 
  301: sub reconlonc {
  302:     my $peerfile=shift;
  303:     &logthis("Trying to reconnect for $peerfile");
  304:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  305:     if (my $fh=IO::File->new("$loncfile")) {
  306: 	my $loncpid=<$fh>;
  307:         chomp($loncpid);
  308:         if (kill 0 => $loncpid) {
  309: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  310:             kill USR1 => $loncpid;
  311:             sleep 5;
  312:             if (-e "$peerfile") { return; }
  313:             &logthis("$peerfile still not there, give it another try");
  314:             sleep 10;
  315:             if (-e "$peerfile") { return; }
  316:             &logthis(
  317:  "<font color=blue>WARNING: $peerfile still not there, giving up</font>");
  318:         } else {
  319: 	    &logthis(
  320:               "<font color=red>CRITICAL: "
  321:              ."lonc at pid $loncpid not responding, giving up</font>");
  322:         }
  323:     } else {
  324:       &logthis('<font color=red>CRITICAL: lonc not running, giving up</font>');
  325:     }
  326: }
  327: 
  328: # -------------------------------------------------- Non-critical communication
  329: 
  330: sub subreply {
  331:     my ($cmd,$server)=@_;
  332:     my $peerfile="$perlvar{'lonSockDir'}/$server";
  333:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  334:                                       Type    => SOCK_STREAM,
  335:                                       Timeout => 10)
  336:        or return "con_lost";
  337:     print $sclient "$cmd\n";
  338:     my $answer=<$sclient>;
  339:     chomp($answer);
  340:     if (!$answer) { $answer="con_lost"; }
  341:     return $answer;
  342: }
  343: 
  344: sub reply {
  345:   my ($cmd,$server)=@_;
  346:   my $answer;
  347:   if ($server ne $perlvar{'lonHostID'}) { 
  348:     $answer=subreply($cmd,$server);
  349:     if ($answer eq 'con_lost') {
  350: 	$answer=subreply("ping",$server);
  351:         if ($answer ne $server) {
  352: 	    &logthis("sub reply: answer != server");
  353:            &reconlonc("$perlvar{'lonSockDir'}/$server");
  354:         }
  355:         $answer=subreply($cmd,$server);
  356:     }
  357:   } else {
  358:     $answer='self_reply';
  359:   } 
  360:   return $answer;
  361: }
  362: 
  363: # -------------------------------------------------------------- Talk to lonsql
  364: 
  365: sub sqlreply {
  366:     my ($cmd)=@_;
  367:     my $answer=subsqlreply($cmd);
  368:     if ($answer eq 'con_lost') { $answer=subsqlreply($cmd); }
  369:     return $answer;
  370: }
  371: 
  372: sub subsqlreply {
  373:     my ($cmd)=@_;
  374:     my $unixsock="mysqlsock";
  375:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
  376:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  377:                                       Type    => SOCK_STREAM,
  378:                                       Timeout => 10)
  379:        or return "con_lost";
  380:     print $sclient "$cmd\n";
  381:     my $answer=<$sclient>;
  382:     chomp($answer);
  383:     if (!$answer) { $answer="con_lost"; }
  384:     return $answer;
  385: }
  386: 
  387: # -------------------------------------------- Return path to profile directory
  388: 
  389: sub propath {
  390:     my ($udom,$uname)=@_;
  391:     $udom=~s/\W//g;
  392:     $uname=~s/\W//g;
  393:     my $subdir=$uname.'__';
  394:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
  395:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
  396:     return $proname;
  397: } 
  398: 
  399: # --------------------------------------- Is this the home server of an author?
  400: 
  401: sub ishome {
  402:     my $author=shift;
  403:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  404:     my ($udom,$uname)=split(/\//,$author);
  405:     my $proname=propath($udom,$uname);
  406:     if (-e $proname) {
  407: 	return 'owner';
  408:     } else {
  409:         return 'not_owner';
  410:     }
  411: }
  412: 
  413: # ======================================================= Continue main program
  414: # ---------------------------------------------------- Fork once and dissociate
  415: 
  416: $fpid=fork;
  417: exit if $fpid;
  418: die "Couldn't fork: $!" unless defined ($fpid);
  419: 
  420: POSIX::setsid() or die "Can't start new session: $!";
  421: 
  422: # ------------------------------------------------------- Write our PID on disk
  423: 
  424: $execdir=$perlvar{'lonDaemons'};
  425: open (PIDSAVE,">$execdir/logs/lond.pid");
  426: print PIDSAVE "$$\n";
  427: close(PIDSAVE);
  428: &logthis("<font color=red>CRITICAL: ---------- Starting ----------</font>");
  429: &status('Starting');
  430: 
  431: # ------------------------------------------------------- Now we are on our own
  432:     
  433: # Fork off our children.
  434: for (1 .. $PREFORK) {
  435:     make_new_child();
  436: }
  437: 
  438: # ----------------------------------------------------- Install signal handlers
  439: 
  440: &status('Forked children');
  441: 
  442: $SIG{CHLD} = \&REAPER;
  443: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
  444: $SIG{HUP}  = \&HUPSMAN;
  445: $SIG{USR1} = \&checkchildren;
  446: 
  447: # And maintain the population.
  448: while (1) {
  449:     &status('Sleeping');
  450:     sleep;                          # wait for a signal (i.e., child's death)
  451:     &logthis('Woke up');
  452:     &status('Woke up');
  453:     for ($i = $children; $i < $PREFORK; $i++) {
  454:         make_new_child();           # top up the child pool
  455:     }
  456: }
  457: 
  458: sub make_new_child {
  459:     my $pid;
  460:     my $cipher;
  461:     my $sigset;
  462:     &logthis("Attempting to start child");    
  463:     # block signal for fork
  464:     $sigset = POSIX::SigSet->new(SIGINT);
  465:     sigprocmask(SIG_BLOCK, $sigset)
  466:         or die "Can't block SIGINT for fork: $!\n";
  467:     
  468:     die "fork: $!" unless defined ($pid = fork);
  469:     
  470:     if ($pid) {
  471:         # Parent records the child's birth and returns.
  472:         sigprocmask(SIG_UNBLOCK, $sigset)
  473:             or die "Can't unblock SIGINT for fork: $!\n";
  474:         $children{$pid} = 1;
  475:         $children++;
  476:         &status('Started child '.$pid);
  477:         return;
  478:     } else {
  479:         # Child can *not* return from this subroutine.
  480:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
  481:         $SIG{USR1}= \&logstatus;
  482:         $SIG{ALRM}= \&timeout;
  483:         $lastlog='Forked ';
  484:         $status='Forked';
  485: 
  486:         # unblock signals
  487:         sigprocmask(SIG_UNBLOCK, $sigset)
  488:             or die "Can't unblock SIGINT for fork: $!\n";
  489: 
  490:         $tmpsnum=0;
  491: #---------------------------------------------------- kerberos 5 initialization
  492:         &Authen::Krb5::init_context();
  493:         &Authen::Krb5::init_ets();
  494: 
  495:         # handle connections until we've reached $MAX_CLIENTS_PER_CHILD
  496:         for ($i=0; $i < $MAX_CLIENTS_PER_CHILD; $i++) {
  497:             &status('Idle, waiting for connection');
  498:             $client = $server->accept()     or last;
  499:             &status('Accepted connection');
  500: # =============================================================================
  501:             # do something with the connection
  502: # -----------------------------------------------------------------------------
  503: 	    $client->sockopt(SO_KEEPALIVE, 1);# Enable monitoring of
  504: 	                                      # connection liveness.
  505:             # see if we know client and check for spoof IP by challenge
  506:             my $caller=getpeername($client);
  507:             my ($port,$iaddr)=unpack_sockaddr_in($caller);
  508:             my $clientip=inet_ntoa($iaddr);
  509:             my $clientrec=($hostid{$clientip} ne undef);
  510:             &logthis(
  511: "<font color=yellow>INFO: Connection $i, $clientip ($hostid{$clientip})</font>"
  512:             );
  513:             &status("Connecting $clientip ($hostid{$clientip})"); 
  514:             my $clientok;
  515:             if ($clientrec) {
  516: 	      &status("Waiting for init from $clientip ($hostid{$clientip})");
  517: 	      my $remotereq=<$client>;
  518:               $remotereq=~s/\W//g;
  519:               if ($remotereq eq 'init') {
  520: 		  my $challenge="$$".time;
  521:                   print $client "$challenge\n";
  522:                   &status(
  523:            "Waiting for challenge reply from $clientip ($hostid{$clientip})"); 
  524:                   $remotereq=<$client>;
  525:                   $remotereq=~s/\W//g;
  526:                   if ($challenge eq $remotereq) {
  527: 		      $clientok=1;
  528:                       print $client "ok\n";
  529:                   } else {
  530: 		      &logthis(
  531:  "<font color=blue>WARNING: $clientip did not reply challenge</font>");
  532:                       &status('No challenge reply '.$clientip);
  533:                   }
  534:               } else {
  535: 		  &logthis(
  536:                     "<font color=blue>WARNING: "
  537:                    ."$clientip failed to initialize: >$remotereq< </font>");
  538:                   &status('No init '.$clientip);
  539:               }
  540: 	    } else {
  541:               &logthis(
  542:  "<font color=blue>WARNING: Unknown client $clientip</font>");
  543:               &status('Hung up on '.$clientip);
  544:             }
  545:             if ($clientok) {
  546: # ---------------- New known client connecting, could mean machine online again
  547: 
  548: 	      &reconlonc("$perlvar{'lonSockDir'}/$hostid{$clientip}");
  549:               &logthis(
  550:        "<font color=green>Established connection: $hostid{$clientip}</font>");
  551:               &status('Will listen to '.$hostid{$clientip});
  552: # ------------------------------------------------------------ Process requests
  553:               while (my $userinput=<$client>) {
  554:                 chomp($userinput);
  555: 		Debug("Request = $userinput\n");
  556:                 &status('Processing '.$hostid{$clientip}.': '.$userinput);
  557:                 my $wasenc=0;
  558:                 alarm(120);
  559: # ------------------------------------------------------------ See if encrypted
  560: 		if ($userinput =~ /^enc/) {
  561: 		  if ($cipher) {
  562:                     my ($cmd,$cmdlength,$encinput)=split(/:/,$userinput);
  563: 		    $userinput='';
  564:                     for (my $encidx=0;$encidx<length($encinput);$encidx+=16) {
  565:                        $userinput.=
  566: 			   $cipher->decrypt(
  567:                             pack("H16",substr($encinput,$encidx,16))
  568:                            );
  569: 		    }
  570: 		    $userinput=substr($userinput,0,$cmdlength);
  571:                     $wasenc=1;
  572: 		}
  573: 	      }
  574: 	  
  575: # ------------------------------------------------------------- Normal commands
  576: # ------------------------------------------------------------------------ ping
  577: 		   if ($userinput =~ /^ping/) {
  578:                        print $client "$perlvar{'lonHostID'}\n";
  579: # ------------------------------------------------------------------------ pong
  580: 		   } elsif ($userinput =~ /^pong/) {
  581:                        $reply=reply("ping",$hostid{$clientip});
  582:                        print $client "$perlvar{'lonHostID'}:$reply\n"; 
  583: # ------------------------------------------------------------------------ ekey
  584: 		   } elsif ($userinput =~ /^ekey/) {
  585:                        my $buildkey=time.$$.int(rand 100000);
  586:                        $buildkey=~tr/1-6/A-F/;
  587:                        $buildkey=int(rand 100000).$buildkey.int(rand 100000);
  588:                        my $key=$perlvar{'lonHostID'}.$hostid{$clientip};
  589:                        $key=~tr/a-z/A-Z/;
  590:                        $key=~tr/G-P/0-9/;
  591:                        $key=~tr/Q-Z/0-9/;
  592:                        $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
  593:                        $key=substr($key,0,32);
  594:                        my $cipherkey=pack("H32",$key);
  595:                        $cipher=new IDEA $cipherkey;
  596:                        print $client "$buildkey\n"; 
  597: # ------------------------------------------------------------------------ load
  598: 		   } elsif ($userinput =~ /^load/) {
  599:                        my $loadavg;
  600:                        {
  601:                           my $loadfile=IO::File->new('/proc/loadavg');
  602:                           $loadavg=<$loadfile>;
  603:                        }
  604:                        $loadavg =~ s/\s.*//g;
  605:                        my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
  606: 		       print $client "$loadpercent\n";
  607: # ----------------------------------------------------------------- currentauth
  608: 		   } elsif ($userinput =~ /^currentauth/) {
  609: 		     if ($wasenc==1) {
  610:                        my ($cmd,$udom,$uname)=split(/:/,$userinput);
  611: 		       my $result = GetAuthType($udom, $uname);
  612: 		       if($result eq "nouser") {
  613: 			   print $client "unknown_user\n";
  614: 		       }
  615: 		       else {
  616: 			   print $client "$result\n"
  617: 		       }
  618: 		     } else {
  619: 		       print $client "refused\n";
  620: 		     }
  621: # ------------------------------------------------------------------------ auth
  622:                    } elsif ($userinput =~ /^auth/) {
  623: 		     if ($wasenc==1) {
  624:                        my ($cmd,$udom,$uname,$upass)=split(/:/,$userinput);
  625:                        chomp($upass);
  626:                        $upass=unescape($upass);
  627:                        my $proname=propath($udom,$uname);
  628:                        my $passfilename="$proname/passwd";
  629:                        if (-e $passfilename) {
  630:                           my $pf = IO::File->new($passfilename);
  631:                           my $realpasswd=<$pf>;
  632:                           chomp($realpasswd);
  633:                           my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
  634:                           my $pwdcorrect=0;
  635:                           if ($howpwd eq 'internal') {
  636: 			      $pwdcorrect=
  637: 				  (crypt($upass,$contentpwd) eq $contentpwd);
  638:                           } elsif ($howpwd eq 'unix') {
  639:                               $contentpwd=(getpwnam($uname))[1];
  640: 			      my $pwauth_path="/usr/local/sbin/pwauth";
  641: 			      unless ($contentpwd eq 'x') {
  642: 				  $pwdcorrect=
  643:                                     (crypt($upass,$contentpwd) eq $contentpwd);
  644: 			      }
  645: 			      elsif (-e $pwauth_path) {
  646: 				  open PWAUTH, "|$pwauth_path" or
  647: 				      die "Cannot invoke authentication";
  648: 				  print PWAUTH "$uname\n$upass\n";
  649: 				  close PWAUTH;
  650: 				  $pwdcorrect=!$?;
  651: 			      }
  652:                           } elsif ($howpwd eq 'krb4') {
  653:                              $null=pack("C",0);
  654: 			     unless ($upass=~/$null/) {
  655:                               $pwdcorrect=(
  656:                                  Authen::Krb4::get_pw_in_tkt($uname,"",
  657:                                         $contentpwd,'krbtgt',$contentpwd,1,
  658: 							     $upass) == 0);
  659: 			     } else { $pwdcorrect=0; }
  660:                           } elsif ($howpwd eq 'krb5') {
  661: 			      $null=pack("C",0);
  662: 			      unless ($upass=~/$null/) {
  663: 				  my $krbclient=&Authen::Krb5::parse_name($uname.'@'.$contentpwd);
  664: 				  my $krbservice="krbtgt/".$contentpwd."\@".$contentpwd;
  665: 				  my $krbserver=&Authen::Krb5::parse_name($krbservice);
  666: 				  my $credentials=&Authen::Krb5::cc_default();
  667: 				  $credentials->initialize($krbclient);
  668: 				  my $krbreturn = 
  669: 				    &Authen::Krb5::get_in_tkt_with_password(
  670: 				     $krbclient,$krbserver,$upass,$credentials);
  671: #				  unless ($krbreturn) {
  672: #				      &logthis("Krb5 Error: ".
  673: #					       &Authen::Krb5::error());
  674: #				  }
  675: 				  $pwdcorrect = ($krbreturn == 1);
  676: 			   } else { $pwdcorrect=0; }
  677:                           } elsif ($howpwd eq 'localauth') {
  678: 			    $pwdcorrect=&localauth::localauth($uname,$upass,
  679: 							      $contentpwd);
  680: 			  }
  681:                           if ($pwdcorrect) {
  682:                              print $client "authorized\n";
  683:                           } else {
  684:                              print $client "non_authorized\n";
  685:                           }  
  686: 		       } else {
  687:                           print $client "unknown_user\n";
  688:                        }
  689: 		     } else {
  690: 		       print $client "refused\n";
  691: 		     }
  692: # ---------------------------------------------------------------------- passwd
  693:                    } elsif ($userinput =~ /^passwd/) {
  694: 		     if ($wasenc==1) {
  695:                        my 
  696:                        ($cmd,$udom,$uname,$upass,$npass)=split(/:/,$userinput);
  697:                        chomp($npass);
  698:                        $upass=&unescape($upass);
  699:                        $npass=&unescape($npass);
  700: 		       &logthis("Trying to change password for $uname");
  701: 		       my $proname=propath($udom,$uname);
  702:                        my $passfilename="$proname/passwd";
  703:                        if (-e $passfilename) {
  704: 			   my $realpasswd;
  705:                           { my $pf = IO::File->new($passfilename);
  706: 			    $realpasswd=<$pf>; }
  707:                           chomp($realpasswd);
  708:                           my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
  709:                           if ($howpwd eq 'internal') {
  710: 			   if (crypt($upass,$contentpwd) eq $contentpwd) {
  711: 			     my $salt=time;
  712:                              $salt=substr($salt,6,2);
  713: 			     my $ncpass=crypt($npass,$salt);
  714:                              { my $pf = IO::File->new(">$passfilename");
  715:  	  		       print $pf "internal:$ncpass\n"; }             
  716: 			     &logthis("Result of password change for $uname: pwchange_success");
  717:                              print $client "ok\n";
  718:                            } else {
  719:                              print $client "non_authorized\n";
  720:                            }
  721:                           } elsif ($howpwd eq 'unix') {
  722: 			      # Unix means we have to access /etc/password
  723: 			      # one way or another.
  724: 			      # First: Make sure the current password is
  725: 			      #        correct
  726: 			      $contentpwd=(getpwnam($uname))[1];
  727: 			      my $pwdcorrect = "0";
  728: 			      my $pwauth_path="/usr/local/sbin/pwauth";
  729: 			      unless ($contentpwd eq 'x') {
  730: 				  $pwdcorrect=
  731:                                     (crypt($upass,$contentpwd) eq $contentpwd);
  732: 			      } elsif (-e $pwauth_path) {
  733: 				  open PWAUTH, "|$pwauth_path" or
  734: 				      die "Cannot invoke authentication";
  735: 				  print PWAUTH "$uname\n$upass\n";
  736: 				  close PWAUTH;
  737: 				  $pwdcorrect=!$?;
  738: 			      }
  739: 			     if ($pwdcorrect) {
  740: 				 my $execdir=$perlvar{'lonDaemons'};
  741: 				 my $pf = IO::File->new("|$execdir/lcpasswd");
  742: 				 print $pf "$uname\n$npass\n$npass\n";
  743: 				 close $pf;
  744: 				 my $result = ($?>0 ? 'pwchange_failure' 
  745: 					       : 'ok');
  746: 				 &logthis("Result of password change for $uname: $result");
  747: 				 print $client "$result\n";
  748: 			     } else {
  749: 				 print $client "non_authorized\n";
  750: 			     }
  751: 			  } else {
  752:                             print $client "auth_mode_error\n";
  753:                           }  
  754: 		       } else {
  755:                           print $client "unknown_user\n";
  756:                        }
  757: 		     } else {
  758: 		       print $client "refused\n";
  759: 		     }
  760: # -------------------------------------------------------------------- makeuser
  761:                    } elsif ($userinput =~ /^makeuser/) {
  762: 		     &Debug("Make user received");
  763:     	             my $oldumask=umask(0077);
  764: 		     if ($wasenc==1) {
  765:                        my 
  766:                        ($cmd,$udom,$uname,$umode,$npass)=split(/:/,$userinput);
  767: 		       &Debug("cmd =".$cmd." $udom =".$udom.
  768: 				    " uname=".$uname);
  769:                        chomp($npass);
  770:                        $npass=&unescape($npass);
  771:                        my $proname=propath($udom,$uname);
  772:                        my $passfilename="$proname/passwd";
  773: 		       &Debug("Password file created will be:".
  774: 				    $passfilename);
  775:                        if (-e $passfilename) {
  776: 			   print $client "already_exists\n";
  777:                        } elsif ($udom ne $perlvar{'lonDefDomain'}) {
  778:                            print $client "not_right_domain\n";
  779:                        } else {
  780:                            @fpparts=split(/\//,$proname);
  781:                            $fpnow=$fpparts[0].'/'.$fpparts[1].'/'.$fpparts[2];
  782:                            $fperror='';
  783:                            for ($i=3;$i<=$#fpparts;$i++) {
  784:                                $fpnow.='/'.$fpparts[$i]; 
  785:                                unless (-e $fpnow) {
  786: 				   unless (mkdir($fpnow,0777)) {
  787:                                       $fperror="error:$!";
  788:                                    }
  789:                                }
  790:                            }
  791:                            unless ($fperror) {
  792: 			       my $result=&make_passwd_file($umode,$npass,
  793: 							    $passfilename);
  794: 			       print $client $result;
  795:                            } else {
  796:                                print $client "$fperror\n";
  797:                            }
  798:                        }
  799: 		     } else {
  800: 		       print $client "refused\n";
  801: 		     }
  802: 		     umask($oldumask);
  803: # -------------------------------------------------------------- changeuserauth
  804:                    } elsif ($userinput =~ /^changeuserauth/) {
  805: 		       &Debug("Changing authorization");
  806: 		      if ($wasenc==1) {
  807:                        my 
  808: 		       ($cmd,$udom,$uname,$umode,$npass)=split(/:/,$userinput);
  809:                        chomp($npass);
  810: 		       &Debug("cmd = ".$cmd." domain= ".$udom.
  811: 			      "uname =".$uname." umode= ".$umode);
  812:                        $npass=&unescape($npass);
  813:                        my $proname=&propath($udom,$uname);
  814:                        my $passfilename="$proname/passwd";
  815: 		       if ($udom ne $perlvar{'lonDefDomain'}) {
  816:                            print $client "not_right_domain\n";
  817:                        } else {
  818: 			   my $result=&make_passwd_file($umode,$npass,
  819: 							$passfilename);
  820: 			   print $client $result;
  821:                        }
  822: 		     } else {
  823: 		       print $client "refused\n";
  824: 		     }
  825: # ------------------------------------------------------------------------ home
  826:                    } elsif ($userinput =~ /^home/) {
  827:                        my ($cmd,$udom,$uname)=split(/:/,$userinput);
  828:                        chomp($uname);
  829:                        my $proname=propath($udom,$uname);
  830:                        if (-e $proname) {
  831:                           print $client "found\n";
  832:                        } else {
  833: 			  print $client "not_found\n";
  834:                        }
  835: # ---------------------------------------------------------------------- update
  836:                    } elsif ($userinput =~ /^update/) {
  837:                        my ($cmd,$fname)=split(/:/,$userinput);
  838:                        my $ownership=ishome($fname);
  839:                        if ($ownership eq 'not_owner') {
  840:                         if (-e $fname) {
  841:                           my ($dev,$ino,$mode,$nlink,
  842:                               $uid,$gid,$rdev,$size,
  843:                               $atime,$mtime,$ctime,
  844:                               $blksize,$blocks)=stat($fname);
  845:                           $now=time;
  846:                           $since=$now-$atime;
  847:                           if ($since>$perlvar{'lonExpire'}) {
  848:                               $reply=
  849:                                     reply("unsub:$fname","$hostid{$clientip}");
  850:                               unlink("$fname");
  851:                           } else {
  852: 			     my $transname="$fname.in.transfer";
  853:                              my $remoteurl=
  854:                                     reply("sub:$fname","$hostid{$clientip}");
  855:                              my $response;
  856:                               {
  857:                              my $ua=new LWP::UserAgent;
  858:                              my $request=new HTTP::Request('GET',"$remoteurl");
  859:                              $response=$ua->request($request,$transname);
  860: 			      }
  861:                              if ($response->is_error()) {
  862: 				 unlink($transname);
  863:                                  my $message=$response->status_line;
  864:                                  &logthis(
  865:                                   "LWP GET: $message for $fname ($remoteurl)");
  866:                              } else {
  867: 	                         if ($remoteurl!~/\.meta$/) {
  868:                                   my $ua=new LWP::UserAgent;
  869:                                   my $mrequest=
  870:                                    new HTTP::Request('GET',$remoteurl.'.meta');
  871:                                   my $mresponse=
  872:                                    $ua->request($mrequest,$fname.'.meta');
  873:                                   if ($mresponse->is_error()) {
  874: 		                    unlink($fname.'.meta');
  875:                                   }
  876: 	                         }
  877:                                  rename($transname,$fname);
  878: 			     }
  879:                           }
  880:                           print $client "ok\n";
  881:                         } else {
  882:                           print $client "not_found\n";
  883:                         }
  884: 		       } else {
  885: 			print $client "rejected\n";
  886:                        }
  887: # -------------------------------------- fetch a user file from a remote server
  888:                    } elsif ($userinput =~ /^fetchuserfile/) {
  889:                       my ($cmd,$fname)=split(/:/,$userinput);
  890: 		      my ($udom,$uname,$ufile)=split(/\//,$fname);
  891:                       my $udir=propath($udom,$uname).'/userfiles';
  892:                       unless (-e $udir) { mkdir($udir,0770); }
  893:                        if (-e $udir) {
  894:                        $ufile=~s/^[\.\~]+//;
  895:                        $ufile=~s/\///g;
  896:                        my $transname=$udir.'/'.$ufile;
  897:                        my $remoteurl='http://'.$clientip.'/userfiles/'.$fname;
  898:                              my $response;
  899:                               {
  900:                              my $ua=new LWP::UserAgent;
  901:                              my $request=new HTTP::Request('GET',"$remoteurl");
  902:                              $response=$ua->request($request,$transname);
  903: 			      }
  904:                              if ($response->is_error()) {
  905: 				 unlink($transname);
  906:                                  my $message=$response->status_line;
  907:                                  &logthis(
  908:                                   "LWP GET: $message for $fname ($remoteurl)");
  909: 				 print $client "failed\n";
  910:                              } else {
  911:                                  print $client "ok\n";
  912:                              }
  913:                      } else {
  914:                        print $client "not_home\n";
  915:                      } 
  916: # ------------------------------------------ authenticate access to a user file
  917:                    } elsif ($userinput =~ /^tokenauthuserfile/) {
  918:                        my ($cmd,$fname,$session)=split(/:/,$userinput);
  919:                        chomp($session);
  920:                        $reply='non_auth';
  921:                        if (open(ENVIN,$perlvar{'lonIDsDir'}.'/'.
  922:                                       $session.'.id')) {
  923:                         while ($line=<ENVIN>) {
  924: 			   if ($line=~/userfile\.$fname\=/) { $reply='ok'; }
  925:                         }
  926:                         close(ENVIN);
  927:                         print $client $reply."\n";
  928: 		       } else {
  929: 			print $client "invalid_token\n";
  930:                        }
  931: # ----------------------------------------------------------------- unsubscribe
  932:                    } elsif ($userinput =~ /^unsub/) {
  933:                        my ($cmd,$fname)=split(/:/,$userinput);
  934:                        if (-e $fname) {
  935: 			   print $client &unsub($client,$fname,$clientip);
  936:                        } else {
  937: 			   print $client "not_found\n";
  938:                        }
  939: # ------------------------------------------------------------------- subscribe
  940:                    } elsif ($userinput =~ /^sub/) {
  941: 		       print $client &subscribe($userinput,$clientip);
  942: # ------------------------------------------------------------------------- log
  943:                    } elsif ($userinput =~ /^log/) {
  944:                        my ($cmd,$udom,$uname,$what)=split(/:/,$userinput);
  945:                        chomp($what);
  946:                        my $proname=propath($udom,$uname);
  947:                        my $now=time;
  948:                        {
  949: 			 my $hfh;
  950: 			 if ($hfh=IO::File->new(">>$proname/activity.log")) { 
  951:                             print $hfh "$now:$hostid{$clientip}:$what\n";
  952:                             print $client "ok\n"; 
  953: 			} else {
  954:                             print $client "error:$!\n";
  955: 		        }
  956: 		       }
  957: # ------------------------------------------------------------------------- put
  958:                    } elsif ($userinput =~ /^put/) {
  959:                       my ($cmd,$udom,$uname,$namespace,$what)
  960:                           =split(/:/,$userinput);
  961:                       $namespace=~s/\//\_/g;
  962:                       $namespace=~s/\W//g;
  963:                       if ($namespace ne 'roles') {
  964:                        chomp($what);
  965:                        my $proname=propath($udom,$uname);
  966:                        my $now=time;
  967:                        unless ($namespace=~/^nohist\_/) {
  968: 			   my $hfh;
  969: 			   if (
  970:                              $hfh=IO::File->new(">>$proname/$namespace.hist")
  971: 			       ) { print $hfh "P:$now:$what\n"; }
  972: 		       }
  973:                        my @pairs=split(/\&/,$what);
  974:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT,0640)) {
  975:                            foreach $pair (@pairs) {
  976: 			       ($key,$value)=split(/=/,$pair);
  977:                                $hash{$key}=$value;
  978:                            }
  979: 			   if (untie(%hash)) {
  980:                               print $client "ok\n";
  981:                            } else {
  982:                               print $client "error:$!\n";
  983:                            }
  984:                        } else {
  985:                            print $client "error:$!\n";
  986:                        }
  987: 		      } else {
  988:                           print $client "refused\n";
  989:                       }
  990: # -------------------------------------------------------------------- rolesput
  991:                    } elsif ($userinput =~ /^rolesput/) {
  992: 		       &Debug("rolesput");
  993: 		    if ($wasenc==1) {
  994:                        my ($cmd,$exedom,$exeuser,$udom,$uname,$what)
  995:                           =split(/:/,$userinput);
  996: 		       &Debug("cmd = ".$cmd." exedom= ".$exedom.
  997: 				    "user = ".$exeuser." udom=".$udom.
  998: 				    "what = ".$what);
  999:                        my $namespace='roles';
 1000:                        chomp($what);
 1001:                        my $proname=propath($udom,$uname);
 1002:                        my $now=time;
 1003:                        {
 1004: 			   my $hfh;
 1005: 			   if (
 1006:                              $hfh=IO::File->new(">>$proname/$namespace.hist")
 1007: 			       ) { 
 1008:                                   print $hfh "P:$now:$exedom:$exeuser:$what\n";
 1009:                                  }
 1010: 		       }
 1011:                        my @pairs=split(/\&/,$what);
 1012:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT,0640)) {
 1013:                            foreach $pair (@pairs) {
 1014: 			       ($key,$value)=split(/=/,$pair);
 1015: 			       &ManagePermissions($key, $udom, $uname,
 1016: 						  &GetAuthType( $udom, 
 1017: 								$uname));
 1018:                                $hash{$key}=$value;
 1019: 			       
 1020:                            }
 1021: 			   if (untie(%hash)) {
 1022:                               print $client "ok\n";
 1023:                            } else {
 1024:                               print $client "error:$!\n";
 1025:                            }
 1026:                        } else {
 1027:                            print $client "error:$!\n";
 1028:                        }
 1029: 		      } else {
 1030:                           print $client "refused\n";
 1031:                       }
 1032: # ------------------------------------------------------------------------- get
 1033:                    } elsif ($userinput =~ /^get/) {
 1034:                        my ($cmd,$udom,$uname,$namespace,$what)
 1035:                           =split(/:/,$userinput);
 1036:                        $namespace=~s/\//\_/g;
 1037:                        $namespace=~s/\W//g;
 1038:                        chomp($what);
 1039:                        my @queries=split(/\&/,$what);
 1040:                        my $proname=propath($udom,$uname);
 1041:                        my $qresult='';
 1042:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER,0640)) {
 1043:                            for ($i=0;$i<=$#queries;$i++) {
 1044:                                $qresult.="$hash{$queries[$i]}&";
 1045:                            }
 1046: 			   if (untie(%hash)) {
 1047: 		              $qresult=~s/\&$//;
 1048:                               print $client "$qresult\n";
 1049:                            } else {
 1050:                               print $client "error:$!\n";
 1051:                            }
 1052:                        } else {
 1053:                            print $client "error:$!\n";
 1054:                        }
 1055: # ------------------------------------------------------------------------ eget
 1056:                    } elsif ($userinput =~ /^eget/) {
 1057:                        my ($cmd,$udom,$uname,$namespace,$what)
 1058:                           =split(/:/,$userinput);
 1059:                        $namespace=~s/\//\_/g;
 1060:                        $namespace=~s/\W//g;
 1061:                        chomp($what);
 1062:                        my @queries=split(/\&/,$what);
 1063:                        my $proname=propath($udom,$uname);
 1064:                        my $qresult='';
 1065:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER,0640)) {
 1066:                            for ($i=0;$i<=$#queries;$i++) {
 1067:                                $qresult.="$hash{$queries[$i]}&";
 1068:                            }
 1069: 			   if (untie(%hash)) {
 1070: 		              $qresult=~s/\&$//;
 1071:                               if ($cipher) {
 1072:                                 my $cmdlength=length($qresult);
 1073:                                 $qresult.="         ";
 1074:                                 my $encqresult='';
 1075:                                 for 
 1076: 				(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 1077:                                  $encqresult.=
 1078:                                  unpack("H16",
 1079:                                  $cipher->encrypt(substr($qresult,$encidx,8)));
 1080:                                 }
 1081:                                 print $client "enc:$cmdlength:$encqresult\n";
 1082: 			      } else {
 1083: 			        print $client "error:no_key\n";
 1084:                               }
 1085:                            } else {
 1086:                               print $client "error:$!\n";
 1087:                            }
 1088:                        } else {
 1089:                            print $client "error:$!\n";
 1090:                        }
 1091: # ------------------------------------------------------------------------- del
 1092:                    } elsif ($userinput =~ /^del/) {
 1093:                        my ($cmd,$udom,$uname,$namespace,$what)
 1094:                           =split(/:/,$userinput);
 1095:                        $namespace=~s/\//\_/g;
 1096:                        $namespace=~s/\W//g;
 1097:                        chomp($what);
 1098:                        my $proname=propath($udom,$uname);
 1099:                        my $now=time;
 1100:                        unless ($namespace=~/^nohist\_/) {
 1101: 			   my $hfh;
 1102: 			   if (
 1103:                              $hfh=IO::File->new(">>$proname/$namespace.hist")
 1104: 			       ) { print $hfh "D:$now:$what\n"; }
 1105: 		       }
 1106:                        my @keys=split(/\&/,$what);
 1107:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT,0640)) {
 1108:                            foreach $key (@keys) {
 1109:                                delete($hash{$key});
 1110:                            }
 1111: 			   if (untie(%hash)) {
 1112:                               print $client "ok\n";
 1113:                            } else {
 1114:                               print $client "error:$!\n";
 1115:                            }
 1116:                        } else {
 1117:                            print $client "error:$!\n";
 1118:                        }
 1119: # ------------------------------------------------------------------------ keys
 1120:                    } elsif ($userinput =~ /^keys/) {
 1121:                        my ($cmd,$udom,$uname,$namespace)
 1122:                           =split(/:/,$userinput);
 1123:                        $namespace=~s/\//\_/g;
 1124:                        $namespace=~s/\W//g;
 1125:                        my $proname=propath($udom,$uname);
 1126:                        my $qresult='';
 1127:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER,0640)) {
 1128:                            foreach $key (keys %hash) {
 1129:                                $qresult.="$key&";
 1130:                            }
 1131: 			   if (untie(%hash)) {
 1132: 		              $qresult=~s/\&$//;
 1133:                               print $client "$qresult\n";
 1134:                            } else {
 1135:                               print $client "error:$!\n";
 1136:                            }
 1137:                        } else {
 1138:                            print $client "error:$!\n";
 1139:                        }
 1140: # ------------------------------------------------------------------------ dump
 1141:                    } elsif ($userinput =~ /^dump/) {
 1142:                        my ($cmd,$udom,$uname,$namespace,$regexp)
 1143:                           =split(/:/,$userinput);
 1144:                        $namespace=~s/\//\_/g;
 1145:                        $namespace=~s/\W//g;
 1146:                        if (defined($regexp)) {
 1147:                           $regexp=&unescape($regexp);
 1148: 		       } else {
 1149:                           $regexp='.';
 1150: 		       }
 1151:                        my $proname=propath($udom,$uname);
 1152:                        my $qresult='';
 1153:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER,0640)) {
 1154:                            study($regexp);
 1155:                            foreach $key (keys %hash) {
 1156:                                my $unescapeKey = &unescape($key);
 1157:                                if (eval('$unescapeKey=~/$regexp/')) {
 1158:                                   $qresult.="$key=$hash{$key}&";
 1159:                               }
 1160:                            }
 1161: 			   if (untie(%hash)) {
 1162: 		              $qresult=~s/\&$//;
 1163:                               print $client "$qresult\n";
 1164:                            } else {
 1165:                               print $client "error:$!\n";
 1166:                            }
 1167:                        } else {
 1168:                            print $client "error:$!\n";
 1169:                        }
 1170: # ----------------------------------------------------------------------- store
 1171:                    } elsif ($userinput =~ /^store/) {
 1172:                       my ($cmd,$udom,$uname,$namespace,$rid,$what)
 1173:                           =split(/:/,$userinput);
 1174:                       $namespace=~s/\//\_/g;
 1175:                       $namespace=~s/\W//g;
 1176:                       if ($namespace ne 'roles') {
 1177:                        chomp($what);
 1178:                        my $proname=propath($udom,$uname);
 1179:                        my $now=time;
 1180:                        unless ($namespace=~/^nohist\_/) {
 1181: 			   my $hfh;
 1182: 			   if (
 1183:                              $hfh=IO::File->new(">>$proname/$namespace.hist")
 1184: 			       ) { print $hfh "P:$now:$rid:$what\n"; }
 1185: 		       }
 1186:                        my @pairs=split(/\&/,$what);
 1187:                          
 1188:     if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT,0640)) {
 1189:                            my @previouskeys=split(/&/,$hash{"keys:$rid"});
 1190:                            my $key;
 1191:                            $hash{"version:$rid"}++;
 1192:                            my $version=$hash{"version:$rid"};
 1193:                            my $allkeys=''; 
 1194:                            foreach $pair (@pairs) {
 1195: 			       ($key,$value)=split(/=/,$pair);
 1196:                                $allkeys.=$key.':';
 1197:                                $hash{"$version:$rid:$key"}=$value;
 1198:                            }
 1199:                            $hash{"$version:$rid:timestamp"}=$now;
 1200:                            $allkeys.='timestamp';
 1201:                            $hash{"$version:keys:$rid"}=$allkeys;
 1202: 			   if (untie(%hash)) {
 1203:                               print $client "ok\n";
 1204:                            } else {
 1205:                               print $client "error:$!\n";
 1206:                            }
 1207:                        } else {
 1208:                            print $client "error:$!\n";
 1209:                        }
 1210: 		      } else {
 1211:                           print $client "refused\n";
 1212:                       }
 1213: # --------------------------------------------------------------------- restore
 1214:                    } elsif ($userinput =~ /^restore/) {
 1215:                        my ($cmd,$udom,$uname,$namespace,$rid)
 1216:                           =split(/:/,$userinput);
 1217:                        $namespace=~s/\//\_/g;
 1218:                        $namespace=~s/\W//g;
 1219:                        chomp($rid);
 1220:                        my $proname=propath($udom,$uname);
 1221:                        my $qresult='';
 1222:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER,0640)) {
 1223:                 	   my $version=$hash{"version:$rid"};
 1224:                            $qresult.="version=$version&";
 1225:                            my $scope;
 1226:                            for ($scope=1;$scope<=$version;$scope++) {
 1227: 			      my $vkeys=$hash{"$scope:keys:$rid"};
 1228:                               my @keys=split(/:/,$vkeys);
 1229:                               my $key;
 1230:                               $qresult.="$scope:keys=$vkeys&";
 1231:                               foreach $key (@keys) {
 1232: 	     $qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
 1233:                               }                                  
 1234:                            }
 1235: 			   if (untie(%hash)) {
 1236: 		              $qresult=~s/\&$//;
 1237:                               print $client "$qresult\n";
 1238:                            } else {
 1239:                               print $client "error:$!\n";
 1240:                            }
 1241:                        } else {
 1242:                            print $client "error:$!\n";
 1243:                        }
 1244: # -------------------------------------------------------------------- chatsend
 1245:                    } elsif ($userinput =~ /^chatsend/) {
 1246:                        my ($cmd,$cdom,$cnum,$newpost)=split(/\:/,$userinput);
 1247:                        &chatadd($cdom,$cnum,$newpost);
 1248:                        print $client "ok\n";
 1249: # -------------------------------------------------------------------- chatretr
 1250:                    } elsif ($userinput =~ /^chatretr/) {
 1251:                        my ($cmd,$cdom,$cnum)=split(/\:/,$userinput);
 1252:                        my $reply='';
 1253:                        foreach (&getchat($cdom,$cnum)) {
 1254: 			   $reply.=&escape($_).':';
 1255:                        }
 1256:                        $reply=~s/\:$//;
 1257:                        print $client $reply."\n";
 1258: # ------------------------------------------------------------------- querysend
 1259:                    } elsif ($userinput =~ /^querysend/) {
 1260:                        my ($cmd,$query,
 1261: 			   $arg1,$arg2,$arg3)=split(/\:/,$userinput);
 1262: 		       $query=~s/\n*$//g;
 1263: 		       print $client "".
 1264: 			       sqlreply("$hostid{$clientip}\&$query".
 1265: 					"\&$arg1"."\&$arg2"."\&$arg3")."\n";
 1266: # ------------------------------------------------------------------ queryreply
 1267:                    } elsif ($userinput =~ /^queryreply/) {
 1268:                        my ($cmd,$id,$reply)=split(/:/,$userinput); 
 1269: 		       my $store;
 1270:                        my $execdir=$perlvar{'lonDaemons'};
 1271:                        if ($store=IO::File->new(">$execdir/tmp/$id")) {
 1272: 			   $reply=~s/\&/\n/g;
 1273: 			   print $store $reply;
 1274: 			   close $store;
 1275: 			   my $store2=IO::File->new(">$execdir/tmp/$id.end");
 1276: 			   print $store2 "done\n";
 1277: 			   close $store2;
 1278: 			   print $client "ok\n";
 1279: 		       }
 1280: 		       else {
 1281: 			   print $client "error:$!\n";
 1282: 		       }
 1283: # ----------------------------------------------------------------------- idput
 1284:                    } elsif ($userinput =~ /^idput/) {
 1285:                        my ($cmd,$udom,$what)=split(/:/,$userinput);
 1286:                        chomp($what);
 1287:                        $udom=~s/\W//g;
 1288:                        my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
 1289:                        my $now=time;
 1290:                        {
 1291: 			   my $hfh;
 1292: 			   if (
 1293:                              $hfh=IO::File->new(">>$proname.hist")
 1294: 			       ) { print $hfh "P:$now:$what\n"; }
 1295: 		       }
 1296:                        my @pairs=split(/\&/,$what);
 1297:                  if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT,0640)) {
 1298:                            foreach $pair (@pairs) {
 1299: 			       ($key,$value)=split(/=/,$pair);
 1300:                                $hash{$key}=$value;
 1301:                            }
 1302: 			   if (untie(%hash)) {
 1303:                               print $client "ok\n";
 1304:                            } else {
 1305:                               print $client "error:$!\n";
 1306:                            }
 1307:                        } else {
 1308:                            print $client "error:$!\n";
 1309:                        }
 1310: # ----------------------------------------------------------------------- idget
 1311:                    } elsif ($userinput =~ /^idget/) {
 1312:                        my ($cmd,$udom,$what)=split(/:/,$userinput);
 1313:                        chomp($what);
 1314:                        $udom=~s/\W//g;
 1315:                        my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
 1316:                        my @queries=split(/\&/,$what);
 1317:                        my $qresult='';
 1318:                  if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER,0640)) {
 1319:                            for ($i=0;$i<=$#queries;$i++) {
 1320:                                $qresult.="$hash{$queries[$i]}&";
 1321:                            }
 1322: 			   if (untie(%hash)) {
 1323: 		              $qresult=~s/\&$//;
 1324:                               print $client "$qresult\n";
 1325:                            } else {
 1326:                               print $client "error:$!\n";
 1327:                            }
 1328:                        } else {
 1329:                            print $client "error:$!\n";
 1330:                        }
 1331: # ---------------------------------------------------------------------- tmpput
 1332:                    } elsif ($userinput =~ /^tmpput/) {
 1333:                        my ($cmd,$what)=split(/:/,$userinput);
 1334: 		       my $store;
 1335:                        $tmpsnum++;
 1336:                        my $id=$$.'_'.$clientip.'_'.$tmpsnum;
 1337:                        $id=~s/\W/\_/g;
 1338:                        $what=~s/\n//g;
 1339:                        my $execdir=$perlvar{'lonDaemons'};
 1340:                        if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
 1341: 			   print $store $what;
 1342: 			   close $store;
 1343: 			   print $client "$id\n";
 1344: 		       }
 1345: 		       else {
 1346: 			   print $client "error:$!\n";
 1347: 		       }
 1348: 
 1349: # ---------------------------------------------------------------------- tmpget
 1350:                    } elsif ($userinput =~ /^tmpget/) {
 1351:                        my ($cmd,$id)=split(/:/,$userinput);
 1352:                        chomp($id);
 1353:                        $id=~s/\W/\_/g;
 1354:                        my $store;
 1355:                        my $execdir=$perlvar{'lonDaemons'};
 1356:                        if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
 1357:                            my $reply=<$store>;
 1358: 			   print $client "$reply\n";
 1359:                            close $store;
 1360: 		       }
 1361: 		       else {
 1362: 			   print $client "error:$!\n";
 1363: 		       }
 1364: 
 1365: # -------------------------------------------------------------------------- ls
 1366:                    } elsif ($userinput =~ /^ls/) {
 1367:                        my ($cmd,$ulsdir)=split(/:/,$userinput);
 1368:                        my $ulsout='';
 1369:                        my $ulsfn;
 1370:                        if (-e $ulsdir) {
 1371:                            if(-d $ulsdir) {
 1372:                                if (opendir(LSDIR,$ulsdir)) {
 1373:                                    while ($ulsfn=readdir(LSDIR)) {
 1374:                                        my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1375:                                        $ulsout.=$ulsfn.'&'.
 1376:                                                 join('&',@ulsstats).':';
 1377:                                    }
 1378:                                    closedir(LSDIR);
 1379:                                }
 1380:                            } else {
 1381:                                my @ulsstats=stat($ulsdir);
 1382:                                $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1383:                            }
 1384:                        } else {
 1385:                           $ulsout='no_such_dir';
 1386:                        }
 1387:                        if ($ulsout eq '') { $ulsout='empty'; }
 1388:                        print $client "$ulsout\n";
 1389: # ------------------------------------------------------------------ Hanging up
 1390:                    } elsif (($userinput =~ /^exit/) ||
 1391:                             ($userinput =~ /^init/)) {
 1392:                        &logthis(
 1393:       "Client $clientip ($hostid{$clientip}) hanging up: $userinput");
 1394:                        print $client "bye\n";
 1395:                        $client->close();
 1396: 		       last;
 1397: # ------------------------------------------------------------- unknown command
 1398:                    } else {
 1399:                        # unknown command
 1400:                        print $client "unknown_cmd\n";
 1401:                    }
 1402: # -------------------------------------------------------------------- complete
 1403: 		   alarm(0);
 1404:                    &status('Listening to '.$hostid{$clientip});
 1405: 	       }
 1406: # --------------------------------------------- client unknown or fishy, refuse
 1407:             } else {
 1408: 	        print $client "refused\n";
 1409:                 $client->close();
 1410:                 &logthis("<font color=blue>WARNING: "
 1411:                 ."Rejected client $clientip, closing connection</font>");
 1412:             }
 1413: 	}              
 1414: 
 1415: # =============================================================================
 1416:        
 1417: 	&logthis("<font color=red>CRITICAL: "
 1418: 		 ."Disconnect from $clientip ($hostid{$clientip})</font>");    
 1419:         # tidy up gracefully and finish
 1420:     
 1421:         $server->close();
 1422: 
 1423:         # this exit is VERY important, otherwise the child will become
 1424:         # a producer of more and more children, forking yourself into
 1425:         # process death.
 1426:         exit;
 1427:     }
 1428: }
 1429: 
 1430: 
 1431: #
 1432: #   Checks to see if the input roleput request was to set
 1433: # an author role.  If so, invokes the lchtmldir script to set
 1434: # up a correct public_html 
 1435: # Parameters:
 1436: #    request   - The request sent to the rolesput subchunk.
 1437: #                We're looking for  /domain/_au
 1438: #    domain    - The domain in which the user is having roles doctored.
 1439: #    user      - Name of the user for which the role is being put.
 1440: #    authtype  - The authentication type associated with the user.
 1441: #
 1442: sub ManagePermissions
 1443: {
 1444:     my $request = shift;
 1445:     my $domain  = shift;
 1446:     my $user    = shift;
 1447:     my $authtype= shift;
 1448: 
 1449:     # See if the request is of the form /$domain/_au
 1450: 
 1451:     if($request =~ /^(\/$domain\/_au)$/) { # It's an author rolesput...
 1452: 	my $execdir = $perlvar{'lonDaemons'};
 1453: 	my $userhome= "/home/$user" ;
 1454: 	Debug("system $execdir/lchtmldir $userhome $system $authtype");
 1455: 	system("$execdir/lchtmldir $userhome $user $authtype");
 1456:     }
 1457: }
 1458: #
 1459: #   GetAuthType - Determines the authorization type of a user in a domain.
 1460: 
 1461: #     Returns the authorization type or nouser if there is no such user.
 1462: #
 1463: sub GetAuthType 
 1464: {
 1465:     my $domain = shift;
 1466:     my $user   = shift;
 1467: 
 1468:     Debug("GetAuthType( $domain, $user ) \n");
 1469:     my $proname    = &propath($domain, $user); 
 1470:     my $passwdfile = "$proname/passwd";
 1471:     if( -e $passwdfile ) {
 1472: 	my $pf = IO::File->new($passwdfile);
 1473: 	my $realpassword = <$pf>;
 1474: 	chomp($realpassword);
 1475: 	Debug("Password info = $realpassword\n");
 1476: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
 1477: 	Debug("Authtype = $authtype, content = $contentpwd\n");
 1478: 	my $availinfo = '';
 1479: 	if($authtype eq 'krb4' or $authtype eq 'krb5') {
 1480: 	    $availinfo = $contentpwd;
 1481: 	}
 1482: 
 1483: 	return "$authtype:$availinfo";
 1484:     }
 1485:     else {
 1486: 	Debug("Returning nouser");
 1487: 	return "nouser";
 1488:     }
 1489: }
 1490: 
 1491: sub addline {
 1492:     my ($fname,$hostid,$ip,$newline)=@_;
 1493:     my $contents;
 1494:     my $found=0;
 1495:     my $expr='^'.$hostid.':'.$ip.':';
 1496:     $expr =~ s/\./\\\./g;
 1497:     if ($sh=IO::File->new("$fname.subscription")) {
 1498: 	while (my $subline=<$sh>) {
 1499: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
 1500: 	}
 1501: 	$sh->close();
 1502:     }
 1503:     $sh=IO::File->new(">$fname.subscription");
 1504:     if ($contents) { print $sh $contents; }
 1505:     if ($newline) { print $sh $newline; }
 1506:     $sh->close();
 1507:     return $found;
 1508: }
 1509: 
 1510: sub getchat {
 1511:     my ($cdom,$cname)=@_;
 1512:     my %hash;
 1513:     my $proname=&propath($cdom,$cname);
 1514:     my @entries=();
 1515:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
 1516: 	    &GDBM_READER(),0640)) {
 1517: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
 1518: 	untie %hash;
 1519:     }
 1520:     return @entries;
 1521: }
 1522: 
 1523: sub chatadd {
 1524:     my ($cdom,$cname,$newchat)=@_;
 1525:     my %hash;
 1526:     my $proname=&propath($cdom,$cname);
 1527:     my @entries=();
 1528:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
 1529: 	    &GDBM_WRCREAT(),0640)) {
 1530: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
 1531: 	my $time=time;
 1532: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
 1533: 	my ($thentime,$idnum)=split(/\_/,$lastid);
 1534: 	my $newid=$time.'_000000';
 1535: 	if ($thentime==$time) {
 1536: 	    $idnum=~s/^0+//;
 1537: 	    $idnum++;
 1538: 	    $idnum=substr('000000'.$idnum,-6,6);
 1539: 	    $newid=$time.'_'.$idnum;
 1540: 	}
 1541: 	$hash{$newid}=$newchat;
 1542: 	my $expired=$time-3600;
 1543: 	foreach (keys %hash) {
 1544: 	    my ($thistime)=($_=~/(\d+)\_/);
 1545: 	    if ($thistime<$expired) {
 1546: 		delete $hash{$_};
 1547: 	    }
 1548: 	}
 1549: 	untie %hash;
 1550:     }
 1551: }
 1552: 
 1553: sub unsub {
 1554:     my ($fname,$clientip)=@_;
 1555:     my $result;
 1556:     if (unlink("$fname.$hostid{$clientip}")) {
 1557: 	$result="ok\n";
 1558:     } else {
 1559: 	$result="not_subscribed\n";
 1560:     }
 1561:     if (-e "$fname.subscription") {
 1562: 	my $found=&addline($fname,$hostid{$clientip},$clientip,'');
 1563: 	if ($found) { $result="ok\n"; }
 1564:     } else {
 1565: 	if ($result != "ok\n") { $result="not_subscribed\n"; }
 1566:     }
 1567:     return $result;
 1568: }
 1569: 
 1570: sub subscribe {
 1571:     my ($userinput,$clientip)=@_;
 1572:     my $result;
 1573:     my ($cmd,$fname)=split(/:/,$userinput);
 1574:     my $ownership=&ishome($fname);
 1575:     if ($ownership eq 'owner') {
 1576: 	if (-e $fname) {
 1577: 	    if (-d $fname) {
 1578: 		$result="directory\n";
 1579: 	    } else {
 1580: 		if (-e "$fname.$hostid{$clientip}") {&unsub($fname,$clientip);}
 1581: 		$now=time;
 1582: 		my $found=&addline($fname,$hostid{$clientip},$clientip,
 1583: 				   "$hostid{$clientip}:$clientip:$now\n");
 1584: 		if ($found) { $result="$fname\n"; }
 1585: 		# if they were subscribed to only meta data, delete that
 1586:                 # subscription, when you subscribe to a file you also get
 1587:                 # the metadata
 1588: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
 1589: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
 1590: 		$fname="http://$thisserver/".$fname;
 1591: 		$result="$fname\n";
 1592: 	    }
 1593: 	} else {
 1594: 	    $result="not_found\n";
 1595: 	}
 1596:     } else {
 1597: 	$result="rejected\n";
 1598:     }
 1599:     return $result;
 1600: }
 1601: 
 1602: sub make_passwd_file {
 1603:     my ($umode,$npass,$passfilename)=@_;
 1604:     my $result="ok\n";
 1605:     if ($umode eq 'krb4' or $umode eq 'krb5') {
 1606: 	{
 1607: 	    my $pf = IO::File->new(">$passfilename");
 1608: 	    print $pf "$umode:$npass\n";
 1609: 	}
 1610:     } elsif ($umode eq 'internal') {
 1611: 	my $salt=time;
 1612: 	$salt=substr($salt,6,2);
 1613: 	my $ncpass=crypt($npass,$salt);
 1614: 	{
 1615: 	    &Debug("Creating internal auth");
 1616: 	    my $pf = IO::File->new(">$passfilename");
 1617: 	    print $pf "internal:$ncpass\n"; 
 1618: 	}
 1619:     } elsif ($umode eq 'localauth') {
 1620: 	{
 1621: 	    my $pf = IO::File->new(">$passfilename");
 1622: 	    print $pf "localauth:$npass\n";
 1623: 	}
 1624:     } elsif ($umode eq 'unix') {
 1625: 	{
 1626: 	    my $execpath="$perlvar{'lonDaemons'}/"."lcuseradd";
 1627: 	    {
 1628: 		&Debug("Executing external: ".$execpath);
 1629: 		my $se = IO::File->new("|$execpath");
 1630: 		print $se "$uname\n";
 1631: 		print $se "$npass\n";
 1632: 		print $se "$npass\n";
 1633: 	    }
 1634: 	    my $pf = IO::File->new(">$passfilename");
 1635: 	    print $pf "unix:\n";
 1636: 	}
 1637:     } elsif ($umode eq 'none') {
 1638: 	{
 1639: 	    my $pf = IO::File->new(">$passfilename");
 1640: 	    print $pf "none:\n";
 1641: 	}
 1642:     } else {
 1643: 	$result="auth_mode_error\n";
 1644:     }
 1645:     return $result;
 1646: }
 1647: 
 1648: # ----------------------------------- POD (plain old documentation, CPAN style)
 1649: 
 1650: =head1 NAME
 1651: 
 1652: lond - "LON Daemon" Server (port "LOND" 5663)
 1653: 
 1654: =head1 SYNOPSIS
 1655: 
 1656: Usage: B<lond>
 1657: 
 1658: Should only be run as user=www.  This is a command-line script which
 1659: is invoked by B<loncron>.  There is no expectation that a typical user
 1660: will manually start B<lond> from the command-line.  (In other words,
 1661: DO NOT START B<lond> YOURSELF.)
 1662: 
 1663: =head1 DESCRIPTION
 1664: 
 1665: There are two characteristics associated with the running of B<lond>,
 1666: PROCESS MANAGEMENT (starting, stopping, handling child processes)
 1667: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
 1668: subscriptions, etc).  These are described in two large
 1669: sections below.
 1670: 
 1671: B<PROCESS MANAGEMENT>
 1672: 
 1673: Preforker - server who forks first. Runs as a daemon. HUPs.
 1674: Uses IDEA encryption
 1675: 
 1676: B<lond> forks off children processes that correspond to the other servers
 1677: in the network.  Management of these processes can be done at the
 1678: parent process level or the child process level.
 1679: 
 1680: B<logs/lond.log> is the location of log messages.
 1681: 
 1682: The process management is now explained in terms of linux shell commands,
 1683: subroutines internal to this code, and signal assignments:
 1684: 
 1685: =over 4
 1686: 
 1687: =item *
 1688: 
 1689: PID is stored in B<logs/lond.pid>
 1690: 
 1691: This is the process id number of the parent B<lond> process.
 1692: 
 1693: =item *
 1694: 
 1695: SIGTERM and SIGINT
 1696: 
 1697: Parent signal assignment:
 1698:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 1699: 
 1700: Child signal assignment:
 1701:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
 1702: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
 1703:  to restart a new child.)
 1704: 
 1705: Command-line invocations:
 1706:  B<kill> B<-s> SIGTERM I<PID>
 1707:  B<kill> B<-s> SIGINT I<PID>
 1708: 
 1709: Subroutine B<HUNTSMAN>:
 1710:  This is only invoked for the B<lond> parent I<PID>.
 1711: This kills all the children, and then the parent.
 1712: The B<lonc.pid> file is cleared.
 1713: 
 1714: =item *
 1715: 
 1716: SIGHUP
 1717: 
 1718: Current bug:
 1719:  This signal can only be processed the first time
 1720: on the parent process.  Subsequent SIGHUP signals
 1721: have no effect.
 1722: 
 1723: Parent signal assignment:
 1724:  $SIG{HUP}  = \&HUPSMAN;
 1725: 
 1726: Child signal assignment:
 1727:  none (nothing happens)
 1728: 
 1729: Command-line invocations:
 1730:  B<kill> B<-s> SIGHUP I<PID>
 1731: 
 1732: Subroutine B<HUPSMAN>:
 1733:  This is only invoked for the B<lond> parent I<PID>,
 1734: This kills all the children, and then the parent.
 1735: The B<lond.pid> file is cleared.
 1736: 
 1737: =item *
 1738: 
 1739: SIGUSR1
 1740: 
 1741: Parent signal assignment:
 1742:  $SIG{USR1} = \&USRMAN;
 1743: 
 1744: Child signal assignment:
 1745:  $SIG{USR1}= \&logstatus;
 1746: 
 1747: Command-line invocations:
 1748:  B<kill> B<-s> SIGUSR1 I<PID>
 1749: 
 1750: Subroutine B<USRMAN>:
 1751:  When invoked for the B<lond> parent I<PID>,
 1752: SIGUSR1 is sent to all the children, and the status of
 1753: each connection is logged.
 1754: 
 1755: =item *
 1756: 
 1757: SIGCHLD
 1758: 
 1759: Parent signal assignment:
 1760:  $SIG{CHLD} = \&REAPER;
 1761: 
 1762: Child signal assignment:
 1763:  none
 1764: 
 1765: Command-line invocations:
 1766:  B<kill> B<-s> SIGCHLD I<PID>
 1767: 
 1768: Subroutine B<REAPER>:
 1769:  This is only invoked for the B<lond> parent I<PID>.
 1770: Information pertaining to the child is removed.
 1771: The socket port is cleaned up.
 1772: 
 1773: =back
 1774: 
 1775: B<SERVER-SIDE ACTIVITIES>
 1776: 
 1777: Server-side information can be accepted in an encrypted or non-encrypted
 1778: method.
 1779: 
 1780: =over 4
 1781: 
 1782: =item ping
 1783: 
 1784: Query a client in the hosts.tab table; "Are you there?"
 1785: 
 1786: =item pong
 1787: 
 1788: Respond to a ping query.
 1789: 
 1790: =item ekey
 1791: 
 1792: Read in encrypted key, make cipher.  Respond with a buildkey.
 1793: 
 1794: =item load
 1795: 
 1796: Respond with CPU load based on a computation upon /proc/loadavg.
 1797: 
 1798: =item currentauth
 1799: 
 1800: Reply with current authentication information (only over an
 1801: encrypted channel).
 1802: 
 1803: =item auth
 1804: 
 1805: Only over an encrypted channel, reply as to whether a user's
 1806: authentication information can be validated.
 1807: 
 1808: =item passwd
 1809: 
 1810: Allow for a password to be set.
 1811: 
 1812: =item makeuser
 1813: 
 1814: Make a user.
 1815: 
 1816: =item passwd
 1817: 
 1818: Allow for authentication mechanism and password to be changed.
 1819: 
 1820: =item home
 1821: 
 1822: Respond to a question "are you the home for a given user?"
 1823: 
 1824: =item update
 1825: 
 1826: Update contents of a subscribed resource.
 1827: 
 1828: =item unsubscribe
 1829: 
 1830: The server is unsubscribing from a resource.
 1831: 
 1832: =item subscribe
 1833: 
 1834: The server is subscribing to a resource.
 1835: 
 1836: =item log
 1837: 
 1838: Place in B<logs/lond.log>
 1839: 
 1840: =item put
 1841: 
 1842: stores hash in namespace
 1843: 
 1844: =item rolesput
 1845: 
 1846: put a role into a user's environment
 1847: 
 1848: =item get
 1849: 
 1850: returns hash with keys from array
 1851: reference filled in from namespace
 1852: 
 1853: =item eget
 1854: 
 1855: returns hash with keys from array
 1856: reference filled in from namesp (encrypts the return communication)
 1857: 
 1858: =item rolesget
 1859: 
 1860: get a role from a user's environment
 1861: 
 1862: =item del
 1863: 
 1864: deletes keys out of array from namespace
 1865: 
 1866: =item keys
 1867: 
 1868: returns namespace keys
 1869: 
 1870: =item dump
 1871: 
 1872: dumps the complete (or key matching regexp) namespace into a hash
 1873: 
 1874: =item store
 1875: 
 1876: stores hash permanently
 1877: for this url; hashref needs to be given and should be a \%hashname; the
 1878: remaining args aren't required and if they aren't passed or are '' they will
 1879: be derived from the ENV
 1880: 
 1881: =item restore
 1882: 
 1883: returns a hash for a given url
 1884: 
 1885: =item querysend
 1886: 
 1887: Tells client about the lonsql process that has been launched in response
 1888: to a sent query.
 1889: 
 1890: =item queryreply
 1891: 
 1892: Accept information from lonsql and make appropriate storage in temporary
 1893: file space.
 1894: 
 1895: =item idput
 1896: 
 1897: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
 1898: for each student, defined perhaps by the institutional Registrar.)
 1899: 
 1900: =item idget
 1901: 
 1902: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
 1903: for each student, defined perhaps by the institutional Registrar.)
 1904: 
 1905: =item tmpput
 1906: 
 1907: Accept and store information in temporary space.
 1908: 
 1909: =item tmpget
 1910: 
 1911: Send along temporarily stored information.
 1912: 
 1913: =item ls
 1914: 
 1915: List part of a user's directory.
 1916: 
 1917: =item Hanging up (exit or init)
 1918: 
 1919: What to do when a client tells the server that they (the client)
 1920: are leaving the network.
 1921: 
 1922: =item unknown command
 1923: 
 1924: If B<lond> is sent an unknown command (not in the list above),
 1925: it replys to the client "unknown_cmd".
 1926: 
 1927: =item UNKNOWN CLIENT
 1928: 
 1929: If the anti-spoofing algorithm cannot verify the client,
 1930: the client is rejected (with a "refused" message sent
 1931: to the client, and the connection is closed.
 1932: 
 1933: =back
 1934: 
 1935: =head1 PREREQUISITES
 1936: 
 1937: IO::Socket
 1938: IO::File
 1939: Apache::File
 1940: Symbol
 1941: POSIX
 1942: Crypt::IDEA
 1943: LWP::UserAgent()
 1944: GDBM_File
 1945: Authen::Krb4
 1946: Authen::Krb5
 1947: 
 1948: =head1 COREQUISITES
 1949: 
 1950: =head1 OSNAMES
 1951: 
 1952: linux
 1953: 
 1954: =head1 SCRIPT CATEGORIES
 1955: 
 1956: Server/Process
 1957: 
 1958: =cut

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