File:  [LON-CAPA] / loncom / lond
Revision 1.93: download - view: text, annotated - select for diffs
Mon Aug 26 14:30:53 2002 UTC (21 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- typo forgot to send back the return value in change auth

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

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