File:  [LON-CAPA] / loncom / lond
Revision 1.92: download - view: text, annotated - select for diffs
Thu Aug 22 21:37:35 2002 UTC (21 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
-removing some debug info

    1: #!/usr/bin/perl
    2: # The LearningOnline Network
    3: # lond "LON Daemon" Server (port "LOND" 5663)
    4: #
    5: # $Id: lond,v 1.92 2002/08/22 21:37:35 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: 			   &make_passwd_file($umode,$npass,$passfilename);
  818: 			   print $client $result;
  819:                        }
  820: 		     } else {
  821: 		       print $client "refused\n";
  822: 		     }
  823: # ------------------------------------------------------------------------ home
  824:                    } elsif ($userinput =~ /^home/) {
  825:                        my ($cmd,$udom,$uname)=split(/:/,$userinput);
  826:                        chomp($uname);
  827:                        my $proname=propath($udom,$uname);
  828:                        if (-e $proname) {
  829:                           print $client "found\n";
  830:                        } else {
  831: 			  print $client "not_found\n";
  832:                        }
  833: # ---------------------------------------------------------------------- update
  834:                    } elsif ($userinput =~ /^update/) {
  835:                        my ($cmd,$fname)=split(/:/,$userinput);
  836:                        my $ownership=ishome($fname);
  837:                        if ($ownership eq 'not_owner') {
  838:                         if (-e $fname) {
  839:                           my ($dev,$ino,$mode,$nlink,
  840:                               $uid,$gid,$rdev,$size,
  841:                               $atime,$mtime,$ctime,
  842:                               $blksize,$blocks)=stat($fname);
  843:                           $now=time;
  844:                           $since=$now-$atime;
  845:                           if ($since>$perlvar{'lonExpire'}) {
  846:                               $reply=
  847:                                     reply("unsub:$fname","$hostid{$clientip}");
  848:                               unlink("$fname");
  849:                           } else {
  850: 			     my $transname="$fname.in.transfer";
  851:                              my $remoteurl=
  852:                                     reply("sub:$fname","$hostid{$clientip}");
  853:                              my $response;
  854:                               {
  855:                              my $ua=new LWP::UserAgent;
  856:                              my $request=new HTTP::Request('GET',"$remoteurl");
  857:                              $response=$ua->request($request,$transname);
  858: 			      }
  859:                              if ($response->is_error()) {
  860: 				 unlink($transname);
  861:                                  my $message=$response->status_line;
  862:                                  &logthis(
  863:                                   "LWP GET: $message for $fname ($remoteurl)");
  864:                              } else {
  865: 	                         if ($remoteurl!~/\.meta$/) {
  866:                                   my $ua=new LWP::UserAgent;
  867:                                   my $mrequest=
  868:                                    new HTTP::Request('GET',$remoteurl.'.meta');
  869:                                   my $mresponse=
  870:                                    $ua->request($mrequest,$fname.'.meta');
  871:                                   if ($mresponse->is_error()) {
  872: 		                    unlink($fname.'.meta');
  873:                                   }
  874: 	                         }
  875:                                  rename($transname,$fname);
  876: 			     }
  877:                           }
  878:                           print $client "ok\n";
  879:                         } else {
  880:                           print $client "not_found\n";
  881:                         }
  882: 		       } else {
  883: 			print $client "rejected\n";
  884:                        }
  885: # -------------------------------------- fetch a user file from a remote server
  886:                    } elsif ($userinput =~ /^fetchuserfile/) {
  887:                       my ($cmd,$fname)=split(/:/,$userinput);
  888: 		      my ($udom,$uname,$ufile)=split(/\//,$fname);
  889:                       my $udir=propath($udom,$uname).'/userfiles';
  890:                       unless (-e $udir) { mkdir($udir,0770); }
  891:                        if (-e $udir) {
  892:                        $ufile=~s/^[\.\~]+//;
  893:                        $ufile=~s/\///g;
  894:                        my $transname=$udir.'/'.$ufile;
  895:                        my $remoteurl='http://'.$clientip.'/userfiles/'.$fname;
  896:                              my $response;
  897:                               {
  898:                              my $ua=new LWP::UserAgent;
  899:                              my $request=new HTTP::Request('GET',"$remoteurl");
  900:                              $response=$ua->request($request,$transname);
  901: 			      }
  902:                              if ($response->is_error()) {
  903: 				 unlink($transname);
  904:                                  my $message=$response->status_line;
  905:                                  &logthis(
  906:                                   "LWP GET: $message for $fname ($remoteurl)");
  907: 				 print $client "failed\n";
  908:                              } else {
  909:                                  print $client "ok\n";
  910:                              }
  911:                      } else {
  912:                        print $client "not_home\n";
  913:                      } 
  914: # ------------------------------------------ authenticate access to a user file
  915:                    } elsif ($userinput =~ /^tokenauthuserfile/) {
  916:                        my ($cmd,$fname,$session)=split(/:/,$userinput);
  917:                        chomp($session);
  918:                        $reply='non_auth';
  919:                        if (open(ENVIN,$perlvar{'lonIDsDir'}.'/'.
  920:                                       $session.'.id')) {
  921:                         while ($line=<ENVIN>) {
  922: 			   if ($line=~/userfile\.$fname\=/) { $reply='ok'; }
  923:                         }
  924:                         close(ENVIN);
  925:                         print $client $reply."\n";
  926: 		       } else {
  927: 			print $client "invalid_token\n";
  928:                        }
  929: # ----------------------------------------------------------------- unsubscribe
  930:                    } elsif ($userinput =~ /^unsub/) {
  931:                        my ($cmd,$fname)=split(/:/,$userinput);
  932:                        if (-e $fname) {
  933: 			   print $client &unsub($client,$fname,$clientip);
  934:                        } else {
  935: 			   print $client "not_found\n";
  936:                        }
  937: # ------------------------------------------------------------------- subscribe
  938:                    } elsif ($userinput =~ /^sub/) {
  939: 		       print $client &subscribe($userinput,$clientip);
  940: # ------------------------------------------------------------------------- log
  941:                    } elsif ($userinput =~ /^log/) {
  942:                        my ($cmd,$udom,$uname,$what)=split(/:/,$userinput);
  943:                        chomp($what);
  944:                        my $proname=propath($udom,$uname);
  945:                        my $now=time;
  946:                        {
  947: 			 my $hfh;
  948: 			 if ($hfh=IO::File->new(">>$proname/activity.log")) { 
  949:                             print $hfh "$now:$hostid{$clientip}:$what\n";
  950:                             print $client "ok\n"; 
  951: 			} else {
  952:                             print $client "error:$!\n";
  953: 		        }
  954: 		       }
  955: # ------------------------------------------------------------------------- put
  956:                    } elsif ($userinput =~ /^put/) {
  957:                       my ($cmd,$udom,$uname,$namespace,$what)
  958:                           =split(/:/,$userinput);
  959:                       $namespace=~s/\//\_/g;
  960:                       $namespace=~s/\W//g;
  961:                       if ($namespace ne 'roles') {
  962:                        chomp($what);
  963:                        my $proname=propath($udom,$uname);
  964:                        my $now=time;
  965:                        unless ($namespace=~/^nohist\_/) {
  966: 			   my $hfh;
  967: 			   if (
  968:                              $hfh=IO::File->new(">>$proname/$namespace.hist")
  969: 			       ) { print $hfh "P:$now:$what\n"; }
  970: 		       }
  971:                        my @pairs=split(/\&/,$what);
  972:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT,0640)) {
  973:                            foreach $pair (@pairs) {
  974: 			       ($key,$value)=split(/=/,$pair);
  975:                                $hash{$key}=$value;
  976:                            }
  977: 			   if (untie(%hash)) {
  978:                               print $client "ok\n";
  979:                            } else {
  980:                               print $client "error:$!\n";
  981:                            }
  982:                        } else {
  983:                            print $client "error:$!\n";
  984:                        }
  985: 		      } else {
  986:                           print $client "refused\n";
  987:                       }
  988: # -------------------------------------------------------------------- rolesput
  989:                    } elsif ($userinput =~ /^rolesput/) {
  990: 		       &Debug("rolesput");
  991: 		    if ($wasenc==1) {
  992:                        my ($cmd,$exedom,$exeuser,$udom,$uname,$what)
  993:                           =split(/:/,$userinput);
  994: 		       &Debug("cmd = ".$cmd." exedom= ".$exedom.
  995: 				    "user = ".$exeuser." udom=".$udom.
  996: 				    "what = ".$what);
  997:                        my $namespace='roles';
  998:                        chomp($what);
  999:                        my $proname=propath($udom,$uname);
 1000:                        my $now=time;
 1001:                        {
 1002: 			   my $hfh;
 1003: 			   if (
 1004:                              $hfh=IO::File->new(">>$proname/$namespace.hist")
 1005: 			       ) { 
 1006:                                   print $hfh "P:$now:$exedom:$exeuser:$what\n";
 1007:                                  }
 1008: 		       }
 1009:                        my @pairs=split(/\&/,$what);
 1010:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT,0640)) {
 1011:                            foreach $pair (@pairs) {
 1012: 			       ($key,$value)=split(/=/,$pair);
 1013: 			       &ManagePermissions($key, $udom, $uname,
 1014: 						  &GetAuthType( $udom, 
 1015: 								$uname));
 1016:                                $hash{$key}=$value;
 1017: 			       
 1018:                            }
 1019: 			   if (untie(%hash)) {
 1020:                               print $client "ok\n";
 1021:                            } else {
 1022:                               print $client "error:$!\n";
 1023:                            }
 1024:                        } else {
 1025:                            print $client "error:$!\n";
 1026:                        }
 1027: 		      } else {
 1028:                           print $client "refused\n";
 1029:                       }
 1030: # ------------------------------------------------------------------------- get
 1031:                    } elsif ($userinput =~ /^get/) {
 1032:                        my ($cmd,$udom,$uname,$namespace,$what)
 1033:                           =split(/:/,$userinput);
 1034:                        $namespace=~s/\//\_/g;
 1035:                        $namespace=~s/\W//g;
 1036:                        chomp($what);
 1037:                        my @queries=split(/\&/,$what);
 1038:                        my $proname=propath($udom,$uname);
 1039:                        my $qresult='';
 1040:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER,0640)) {
 1041:                            for ($i=0;$i<=$#queries;$i++) {
 1042:                                $qresult.="$hash{$queries[$i]}&";
 1043:                            }
 1044: 			   if (untie(%hash)) {
 1045: 		              $qresult=~s/\&$//;
 1046:                               print $client "$qresult\n";
 1047:                            } else {
 1048:                               print $client "error:$!\n";
 1049:                            }
 1050:                        } else {
 1051:                            print $client "error:$!\n";
 1052:                        }
 1053: # ------------------------------------------------------------------------ eget
 1054:                    } elsif ($userinput =~ /^eget/) {
 1055:                        my ($cmd,$udom,$uname,$namespace,$what)
 1056:                           =split(/:/,$userinput);
 1057:                        $namespace=~s/\//\_/g;
 1058:                        $namespace=~s/\W//g;
 1059:                        chomp($what);
 1060:                        my @queries=split(/\&/,$what);
 1061:                        my $proname=propath($udom,$uname);
 1062:                        my $qresult='';
 1063:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER,0640)) {
 1064:                            for ($i=0;$i<=$#queries;$i++) {
 1065:                                $qresult.="$hash{$queries[$i]}&";
 1066:                            }
 1067: 			   if (untie(%hash)) {
 1068: 		              $qresult=~s/\&$//;
 1069:                               if ($cipher) {
 1070:                                 my $cmdlength=length($qresult);
 1071:                                 $qresult.="         ";
 1072:                                 my $encqresult='';
 1073:                                 for 
 1074: 				(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 1075:                                  $encqresult.=
 1076:                                  unpack("H16",
 1077:                                  $cipher->encrypt(substr($qresult,$encidx,8)));
 1078:                                 }
 1079:                                 print $client "enc:$cmdlength:$encqresult\n";
 1080: 			      } else {
 1081: 			        print $client "error:no_key\n";
 1082:                               }
 1083:                            } else {
 1084:                               print $client "error:$!\n";
 1085:                            }
 1086:                        } else {
 1087:                            print $client "error:$!\n";
 1088:                        }
 1089: # ------------------------------------------------------------------------- del
 1090:                    } elsif ($userinput =~ /^del/) {
 1091:                        my ($cmd,$udom,$uname,$namespace,$what)
 1092:                           =split(/:/,$userinput);
 1093:                        $namespace=~s/\//\_/g;
 1094:                        $namespace=~s/\W//g;
 1095:                        chomp($what);
 1096:                        my $proname=propath($udom,$uname);
 1097:                        my $now=time;
 1098:                        unless ($namespace=~/^nohist\_/) {
 1099: 			   my $hfh;
 1100: 			   if (
 1101:                              $hfh=IO::File->new(">>$proname/$namespace.hist")
 1102: 			       ) { print $hfh "D:$now:$what\n"; }
 1103: 		       }
 1104:                        my @keys=split(/\&/,$what);
 1105:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT,0640)) {
 1106:                            foreach $key (@keys) {
 1107:                                delete($hash{$key});
 1108:                            }
 1109: 			   if (untie(%hash)) {
 1110:                               print $client "ok\n";
 1111:                            } else {
 1112:                               print $client "error:$!\n";
 1113:                            }
 1114:                        } else {
 1115:                            print $client "error:$!\n";
 1116:                        }
 1117: # ------------------------------------------------------------------------ keys
 1118:                    } elsif ($userinput =~ /^keys/) {
 1119:                        my ($cmd,$udom,$uname,$namespace)
 1120:                           =split(/:/,$userinput);
 1121:                        $namespace=~s/\//\_/g;
 1122:                        $namespace=~s/\W//g;
 1123:                        my $proname=propath($udom,$uname);
 1124:                        my $qresult='';
 1125:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER,0640)) {
 1126:                            foreach $key (keys %hash) {
 1127:                                $qresult.="$key&";
 1128:                            }
 1129: 			   if (untie(%hash)) {
 1130: 		              $qresult=~s/\&$//;
 1131:                               print $client "$qresult\n";
 1132:                            } else {
 1133:                               print $client "error:$!\n";
 1134:                            }
 1135:                        } else {
 1136:                            print $client "error:$!\n";
 1137:                        }
 1138: # ------------------------------------------------------------------------ dump
 1139:                    } elsif ($userinput =~ /^dump/) {
 1140:                        my ($cmd,$udom,$uname,$namespace,$regexp)
 1141:                           =split(/:/,$userinput);
 1142:                        $namespace=~s/\//\_/g;
 1143:                        $namespace=~s/\W//g;
 1144:                        if (defined($regexp)) {
 1145:                           $regexp=&unescape($regexp);
 1146: 		       } else {
 1147:                           $regexp='.';
 1148: 		       }
 1149:                        my $proname=propath($udom,$uname);
 1150:                        my $qresult='';
 1151:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER,0640)) {
 1152:                            study($regexp);
 1153:                            foreach $key (keys %hash) {
 1154:                                my $unescapeKey = &unescape($key);
 1155:                                if (eval('$unescapeKey=~/$regexp/')) {
 1156:                                   $qresult.="$key=$hash{$key}&";
 1157:                               }
 1158:                            }
 1159: 			   if (untie(%hash)) {
 1160: 		              $qresult=~s/\&$//;
 1161:                               print $client "$qresult\n";
 1162:                            } else {
 1163:                               print $client "error:$!\n";
 1164:                            }
 1165:                        } else {
 1166:                            print $client "error:$!\n";
 1167:                        }
 1168: # ----------------------------------------------------------------------- store
 1169:                    } elsif ($userinput =~ /^store/) {
 1170:                       my ($cmd,$udom,$uname,$namespace,$rid,$what)
 1171:                           =split(/:/,$userinput);
 1172:                       $namespace=~s/\//\_/g;
 1173:                       $namespace=~s/\W//g;
 1174:                       if ($namespace ne 'roles') {
 1175:                        chomp($what);
 1176:                        my $proname=propath($udom,$uname);
 1177:                        my $now=time;
 1178:                        unless ($namespace=~/^nohist\_/) {
 1179: 			   my $hfh;
 1180: 			   if (
 1181:                              $hfh=IO::File->new(">>$proname/$namespace.hist")
 1182: 			       ) { print $hfh "P:$now:$rid:$what\n"; }
 1183: 		       }
 1184:                        my @pairs=split(/\&/,$what);
 1185:                          
 1186:     if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT,0640)) {
 1187:                            my @previouskeys=split(/&/,$hash{"keys:$rid"});
 1188:                            my $key;
 1189:                            $hash{"version:$rid"}++;
 1190:                            my $version=$hash{"version:$rid"};
 1191:                            my $allkeys=''; 
 1192:                            foreach $pair (@pairs) {
 1193: 			       ($key,$value)=split(/=/,$pair);
 1194:                                $allkeys.=$key.':';
 1195:                                $hash{"$version:$rid:$key"}=$value;
 1196:                            }
 1197:                            $hash{"$version:$rid:timestamp"}=$now;
 1198:                            $allkeys.='timestamp';
 1199:                            $hash{"$version:keys:$rid"}=$allkeys;
 1200: 			   if (untie(%hash)) {
 1201:                               print $client "ok\n";
 1202:                            } else {
 1203:                               print $client "error:$!\n";
 1204:                            }
 1205:                        } else {
 1206:                            print $client "error:$!\n";
 1207:                        }
 1208: 		      } else {
 1209:                           print $client "refused\n";
 1210:                       }
 1211: # --------------------------------------------------------------------- restore
 1212:                    } elsif ($userinput =~ /^restore/) {
 1213:                        my ($cmd,$udom,$uname,$namespace,$rid)
 1214:                           =split(/:/,$userinput);
 1215:                        $namespace=~s/\//\_/g;
 1216:                        $namespace=~s/\W//g;
 1217:                        chomp($rid);
 1218:                        my $proname=propath($udom,$uname);
 1219:                        my $qresult='';
 1220:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER,0640)) {
 1221:                 	   my $version=$hash{"version:$rid"};
 1222:                            $qresult.="version=$version&";
 1223:                            my $scope;
 1224:                            for ($scope=1;$scope<=$version;$scope++) {
 1225: 			      my $vkeys=$hash{"$scope:keys:$rid"};
 1226:                               my @keys=split(/:/,$vkeys);
 1227:                               my $key;
 1228:                               $qresult.="$scope:keys=$vkeys&";
 1229:                               foreach $key (@keys) {
 1230: 	     $qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
 1231:                               }                                  
 1232:                            }
 1233: 			   if (untie(%hash)) {
 1234: 		              $qresult=~s/\&$//;
 1235:                               print $client "$qresult\n";
 1236:                            } else {
 1237:                               print $client "error:$!\n";
 1238:                            }
 1239:                        } else {
 1240:                            print $client "error:$!\n";
 1241:                        }
 1242: # -------------------------------------------------------------------- chatsend
 1243:                    } elsif ($userinput =~ /^chatsend/) {
 1244:                        my ($cmd,$cdom,$cnum,$newpost)=split(/\:/,$userinput);
 1245:                        &chatadd($cdom,$cnum,$newpost);
 1246:                        print $client "ok\n";
 1247: # -------------------------------------------------------------------- chatretr
 1248:                    } elsif ($userinput =~ /^chatretr/) {
 1249:                        my ($cmd,$cdom,$cnum)=split(/\:/,$userinput);
 1250:                        my $reply='';
 1251:                        foreach (&getchat($cdom,$cnum)) {
 1252: 			   $reply.=&escape($_).':';
 1253:                        }
 1254:                        $reply=~s/\:$//;
 1255:                        print $client $reply."\n";
 1256: # ------------------------------------------------------------------- querysend
 1257:                    } elsif ($userinput =~ /^querysend/) {
 1258:                        my ($cmd,$query,
 1259: 			   $arg1,$arg2,$arg3)=split(/\:/,$userinput);
 1260: 		       $query=~s/\n*$//g;
 1261: 		       print $client "".
 1262: 			       sqlreply("$hostid{$clientip}\&$query".
 1263: 					"\&$arg1"."\&$arg2"."\&$arg3")."\n";
 1264: # ------------------------------------------------------------------ queryreply
 1265:                    } elsif ($userinput =~ /^queryreply/) {
 1266:                        my ($cmd,$id,$reply)=split(/:/,$userinput); 
 1267: 		       my $store;
 1268:                        my $execdir=$perlvar{'lonDaemons'};
 1269:                        if ($store=IO::File->new(">$execdir/tmp/$id")) {
 1270: 			   $reply=~s/\&/\n/g;
 1271: 			   print $store $reply;
 1272: 			   close $store;
 1273: 			   my $store2=IO::File->new(">$execdir/tmp/$id.end");
 1274: 			   print $store2 "done\n";
 1275: 			   close $store2;
 1276: 			   print $client "ok\n";
 1277: 		       }
 1278: 		       else {
 1279: 			   print $client "error:$!\n";
 1280: 		       }
 1281: # ----------------------------------------------------------------------- idput
 1282:                    } elsif ($userinput =~ /^idput/) {
 1283:                        my ($cmd,$udom,$what)=split(/:/,$userinput);
 1284:                        chomp($what);
 1285:                        $udom=~s/\W//g;
 1286:                        my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
 1287:                        my $now=time;
 1288:                        {
 1289: 			   my $hfh;
 1290: 			   if (
 1291:                              $hfh=IO::File->new(">>$proname.hist")
 1292: 			       ) { print $hfh "P:$now:$what\n"; }
 1293: 		       }
 1294:                        my @pairs=split(/\&/,$what);
 1295:                  if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT,0640)) {
 1296:                            foreach $pair (@pairs) {
 1297: 			       ($key,$value)=split(/=/,$pair);
 1298:                                $hash{$key}=$value;
 1299:                            }
 1300: 			   if (untie(%hash)) {
 1301:                               print $client "ok\n";
 1302:                            } else {
 1303:                               print $client "error:$!\n";
 1304:                            }
 1305:                        } else {
 1306:                            print $client "error:$!\n";
 1307:                        }
 1308: # ----------------------------------------------------------------------- idget
 1309:                    } elsif ($userinput =~ /^idget/) {
 1310:                        my ($cmd,$udom,$what)=split(/:/,$userinput);
 1311:                        chomp($what);
 1312:                        $udom=~s/\W//g;
 1313:                        my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
 1314:                        my @queries=split(/\&/,$what);
 1315:                        my $qresult='';
 1316:                  if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER,0640)) {
 1317:                            for ($i=0;$i<=$#queries;$i++) {
 1318:                                $qresult.="$hash{$queries[$i]}&";
 1319:                            }
 1320: 			   if (untie(%hash)) {
 1321: 		              $qresult=~s/\&$//;
 1322:                               print $client "$qresult\n";
 1323:                            } else {
 1324:                               print $client "error:$!\n";
 1325:                            }
 1326:                        } else {
 1327:                            print $client "error:$!\n";
 1328:                        }
 1329: # ---------------------------------------------------------------------- tmpput
 1330:                    } elsif ($userinput =~ /^tmpput/) {
 1331:                        my ($cmd,$what)=split(/:/,$userinput);
 1332: 		       my $store;
 1333:                        $tmpsnum++;
 1334:                        my $id=$$.'_'.$clientip.'_'.$tmpsnum;
 1335:                        $id=~s/\W/\_/g;
 1336:                        $what=~s/\n//g;
 1337:                        my $execdir=$perlvar{'lonDaemons'};
 1338:                        if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
 1339: 			   print $store $what;
 1340: 			   close $store;
 1341: 			   print $client "$id\n";
 1342: 		       }
 1343: 		       else {
 1344: 			   print $client "error:$!\n";
 1345: 		       }
 1346: 
 1347: # ---------------------------------------------------------------------- tmpget
 1348:                    } elsif ($userinput =~ /^tmpget/) {
 1349:                        my ($cmd,$id)=split(/:/,$userinput);
 1350:                        chomp($id);
 1351:                        $id=~s/\W/\_/g;
 1352:                        my $store;
 1353:                        my $execdir=$perlvar{'lonDaemons'};
 1354:                        if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
 1355:                            my $reply=<$store>;
 1356: 			   print $client "$reply\n";
 1357:                            close $store;
 1358: 		       }
 1359: 		       else {
 1360: 			   print $client "error:$!\n";
 1361: 		       }
 1362: 
 1363: # -------------------------------------------------------------------------- ls
 1364:                    } elsif ($userinput =~ /^ls/) {
 1365:                        my ($cmd,$ulsdir)=split(/:/,$userinput);
 1366:                        my $ulsout='';
 1367:                        my $ulsfn;
 1368:                        if (-e $ulsdir) {
 1369:                            if(-d $ulsdir) {
 1370:                                if (opendir(LSDIR,$ulsdir)) {
 1371:                                    while ($ulsfn=readdir(LSDIR)) {
 1372:                                        my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1373:                                        $ulsout.=$ulsfn.'&'.
 1374:                                                 join('&',@ulsstats).':';
 1375:                                    }
 1376:                                    closedir(LSDIR);
 1377:                                }
 1378:                            } else {
 1379:                                my @ulsstats=stat($ulsdir);
 1380:                                $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1381:                            }
 1382:                        } else {
 1383:                           $ulsout='no_such_dir';
 1384:                        }
 1385:                        if ($ulsout eq '') { $ulsout='empty'; }
 1386:                        print $client "$ulsout\n";
 1387: # ------------------------------------------------------------------ Hanging up
 1388:                    } elsif (($userinput =~ /^exit/) ||
 1389:                             ($userinput =~ /^init/)) {
 1390:                        &logthis(
 1391:       "Client $clientip ($hostid{$clientip}) hanging up: $userinput");
 1392:                        print $client "bye\n";
 1393:                        $client->close();
 1394: 		       last;
 1395: # ------------------------------------------------------------- unknown command
 1396:                    } else {
 1397:                        # unknown command
 1398:                        print $client "unknown_cmd\n";
 1399:                    }
 1400: # -------------------------------------------------------------------- complete
 1401: 		   alarm(0);
 1402:                    &status('Listening to '.$hostid{$clientip});
 1403: 	       }
 1404: # --------------------------------------------- client unknown or fishy, refuse
 1405:             } else {
 1406: 	        print $client "refused\n";
 1407:                 $client->close();
 1408:                 &logthis("<font color=blue>WARNING: "
 1409:                 ."Rejected client $clientip, closing connection</font>");
 1410:             }
 1411: 	}              
 1412: 
 1413: # =============================================================================
 1414:        
 1415: 	&logthis("<font color=red>CRITICAL: "
 1416: 		 ."Disconnect from $clientip ($hostid{$clientip})</font>");    
 1417:         # tidy up gracefully and finish
 1418:     
 1419:         $server->close();
 1420: 
 1421:         # this exit is VERY important, otherwise the child will become
 1422:         # a producer of more and more children, forking yourself into
 1423:         # process death.
 1424:         exit;
 1425:     }
 1426: }
 1427: 
 1428: 
 1429: #
 1430: #   Checks to see if the input roleput request was to set
 1431: # an author role.  If so, invokes the lchtmldir script to set
 1432: # up a correct public_html 
 1433: # Parameters:
 1434: #    request   - The request sent to the rolesput subchunk.
 1435: #                We're looking for  /domain/_au
 1436: #    domain    - The domain in which the user is having roles doctored.
 1437: #    user      - Name of the user for which the role is being put.
 1438: #    authtype  - The authentication type associated with the user.
 1439: #
 1440: sub ManagePermissions
 1441: {
 1442:     my $request = shift;
 1443:     my $domain  = shift;
 1444:     my $user    = shift;
 1445:     my $authtype= shift;
 1446: 
 1447:     # See if the request is of the form /$domain/_au
 1448: 
 1449:     if($request =~ /^(\/$domain\/_au)$/) { # It's an author rolesput...
 1450: 	my $execdir = $perlvar{'lonDaemons'};
 1451: 	my $userhome= "/home/$user" ;
 1452: 	Debug("system $execdir/lchtmldir $userhome $system $authtype");
 1453: 	system("$execdir/lchtmldir $userhome $user $authtype");
 1454:     }
 1455: }
 1456: #
 1457: #   GetAuthType - Determines the authorization type of a user in a domain.
 1458: 
 1459: #     Returns the authorization type or nouser if there is no such user.
 1460: #
 1461: sub GetAuthType 
 1462: {
 1463:     my $domain = shift;
 1464:     my $user   = shift;
 1465: 
 1466:     Debug("GetAuthType( $domain, $user ) \n");
 1467:     my $proname    = &propath($domain, $user); 
 1468:     my $passwdfile = "$proname/passwd";
 1469:     if( -e $passwdfile ) {
 1470: 	my $pf = IO::File->new($passwdfile);
 1471: 	my $realpassword = <$pf>;
 1472: 	chomp($realpassword);
 1473: 	Debug("Password info = $realpassword\n");
 1474: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
 1475: 	Debug("Authtype = $authtype, content = $contentpwd\n");
 1476: 	my $availinfo = '';
 1477: 	if($authtype eq 'krb4' or $authtype eq 'krb5') {
 1478: 	    $availinfo = $contentpwd;
 1479: 	}
 1480: 
 1481: 	return "$authtype:$availinfo";
 1482:     }
 1483:     else {
 1484: 	Debug("Returning nouser");
 1485: 	return "nouser";
 1486:     }
 1487: }
 1488: 
 1489: sub addline {
 1490:     my ($fname,$hostid,$ip,$newline)=@_;
 1491:     my $contents;
 1492:     my $found=0;
 1493:     my $expr='^'.$hostid.':'.$ip.':';
 1494:     $expr =~ s/\./\\\./g;
 1495:     if ($sh=IO::File->new("$fname.subscription")) {
 1496: 	while (my $subline=<$sh>) {
 1497: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
 1498: 	}
 1499: 	$sh->close();
 1500:     }
 1501:     $sh=IO::File->new(">$fname.subscription");
 1502:     if ($contents) { print $sh $contents; }
 1503:     if ($newline) { print $sh $newline; }
 1504:     $sh->close();
 1505:     return $found;
 1506: }
 1507: 
 1508: sub getchat {
 1509:     my ($cdom,$cname)=@_;
 1510:     my %hash;
 1511:     my $proname=&propath($cdom,$cname);
 1512:     my @entries=();
 1513:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
 1514: 	    &GDBM_READER(),0640)) {
 1515: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
 1516: 	untie %hash;
 1517:     }
 1518:     return @entries;
 1519: }
 1520: 
 1521: sub chatadd {
 1522:     my ($cdom,$cname,$newchat)=@_;
 1523:     my %hash;
 1524:     my $proname=&propath($cdom,$cname);
 1525:     my @entries=();
 1526:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
 1527: 	    &GDBM_WRCREAT(),0640)) {
 1528: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
 1529: 	my $time=time;
 1530: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
 1531: 	my ($thentime,$idnum)=split(/\_/,$lastid);
 1532: 	my $newid=$time.'_000000';
 1533: 	if ($thentime==$time) {
 1534: 	    $idnum=~s/^0+//;
 1535: 	    $idnum++;
 1536: 	    $idnum=substr('000000'.$idnum,-6,6);
 1537: 	    $newid=$time.'_'.$idnum;
 1538: 	}
 1539: 	$hash{$newid}=$newchat;
 1540: 	my $expired=$time-3600;
 1541: 	foreach (keys %hash) {
 1542: 	    my ($thistime)=($_=~/(\d+)\_/);
 1543: 	    if ($thistime<$expired) {
 1544: 		delete $hash{$_};
 1545: 	    }
 1546: 	}
 1547: 	untie %hash;
 1548:     }
 1549: }
 1550: 
 1551: sub unsub {
 1552:     my ($fname,$clientip)=@_;
 1553:     my $result;
 1554:     if (unlink("$fname.$hostid{$clientip}")) {
 1555: 	$result="ok\n";
 1556:     } else {
 1557: 	$result="not_subscribed\n";
 1558:     }
 1559:     if (-e "$fname.subscription") {
 1560: 	my $found=&addline($fname,$hostid{$clientip},$clientip,'');
 1561: 	if ($found) { $result="ok\n"; }
 1562:     } else {
 1563: 	if ($result != "ok\n") { $result="not_subscribed\n"; }
 1564:     }
 1565:     return $result;
 1566: }
 1567: 
 1568: sub subscribe {
 1569:     my ($userinput,$clientip)=@_;
 1570:     my $result;
 1571:     my ($cmd,$fname)=split(/:/,$userinput);
 1572:     my $ownership=&ishome($fname);
 1573:     if ($ownership eq 'owner') {
 1574: 	if (-e $fname) {
 1575: 	    if (-d $fname) {
 1576: 		$result="directory\n";
 1577: 	    } else {
 1578: 		if (-e "$fname.$hostid{$clientip}") {&unsub($fname,$clientip);}
 1579: 		$now=time;
 1580: 		my $found=&addline($fname,$hostid{$clientip},$clientip,
 1581: 				   "$hostid{$clientip}:$clientip:$now\n");
 1582: 		if ($found) { $result="$fname\n"; }
 1583: 		# if they were subscribed to only meta data, delete that
 1584:                 # subscription, when you subscribe to a file you also get
 1585:                 # the metadata
 1586: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
 1587: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
 1588: 		$fname="http://$thisserver/".$fname;
 1589: 		$result="$fname\n";
 1590: 	    }
 1591: 	} else {
 1592: 	    $result="not_found\n";
 1593: 	}
 1594:     } else {
 1595: 	$result="rejected\n";
 1596:     }
 1597:     return $result;
 1598: }
 1599: 
 1600: sub make_passwd_file {
 1601:     my ($umode,$npass,$passfilename)=@_;
 1602:     my $result="ok\n";
 1603:     if ($umode eq 'krb4' or $umode eq 'krb5') {
 1604: 	{
 1605: 	    my $pf = IO::File->new(">$passfilename");
 1606: 	    print $pf "$umode:$npass\n";
 1607: 	}
 1608:     } elsif ($umode eq 'internal') {
 1609: 	my $salt=time;
 1610: 	$salt=substr($salt,6,2);
 1611: 	my $ncpass=crypt($npass,$salt);
 1612: 	{
 1613: 	    &Debug("Creating internal auth");
 1614: 	    my $pf = IO::File->new(">$passfilename");
 1615: 	    print $pf "internal:$ncpass\n"; 
 1616: 	}
 1617:     } elsif ($umode eq 'localauth') {
 1618: 	{
 1619: 	    my $pf = IO::File->new(">$passfilename");
 1620: 	    print $pf "localauth:$npass\n";
 1621: 	}
 1622:     } elsif ($umode eq 'unix') {
 1623: 	{
 1624: 	    my $execpath="$perlvar{'lonDaemons'}/"."lcuseradd";
 1625: 	    {
 1626: 		&Debug("Executing external: ".$execpath);
 1627: 		my $se = IO::File->new("|$execpath");
 1628: 		print $se "$uname\n";
 1629: 		print $se "$npass\n";
 1630: 		print $se "$npass\n";
 1631: 	    }
 1632: 	    my $pf = IO::File->new(">$passfilename");
 1633: 	    print $pf "unix:\n";
 1634: 	}
 1635:     } elsif ($umode eq 'none') {
 1636: 	{
 1637: 	    my $pf = IO::File->new(">$passfilename");
 1638: 	    print $pf "none:\n";
 1639: 	}
 1640:     } else {
 1641: 	$result="auth_mode_error\n";
 1642:     }
 1643:     return $result;
 1644: }
 1645: 
 1646: # ----------------------------------- POD (plain old documentation, CPAN style)
 1647: 
 1648: =head1 NAME
 1649: 
 1650: lond - "LON Daemon" Server (port "LOND" 5663)
 1651: 
 1652: =head1 SYNOPSIS
 1653: 
 1654: Usage: B<lond>
 1655: 
 1656: Should only be run as user=www.  This is a command-line script which
 1657: is invoked by B<loncron>.  There is no expectation that a typical user
 1658: will manually start B<lond> from the command-line.  (In other words,
 1659: DO NOT START B<lond> YOURSELF.)
 1660: 
 1661: =head1 DESCRIPTION
 1662: 
 1663: There are two characteristics associated with the running of B<lond>,
 1664: PROCESS MANAGEMENT (starting, stopping, handling child processes)
 1665: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
 1666: subscriptions, etc).  These are described in two large
 1667: sections below.
 1668: 
 1669: B<PROCESS MANAGEMENT>
 1670: 
 1671: Preforker - server who forks first. Runs as a daemon. HUPs.
 1672: Uses IDEA encryption
 1673: 
 1674: B<lond> forks off children processes that correspond to the other servers
 1675: in the network.  Management of these processes can be done at the
 1676: parent process level or the child process level.
 1677: 
 1678: B<logs/lond.log> is the location of log messages.
 1679: 
 1680: The process management is now explained in terms of linux shell commands,
 1681: subroutines internal to this code, and signal assignments:
 1682: 
 1683: =over 4
 1684: 
 1685: =item *
 1686: 
 1687: PID is stored in B<logs/lond.pid>
 1688: 
 1689: This is the process id number of the parent B<lond> process.
 1690: 
 1691: =item *
 1692: 
 1693: SIGTERM and SIGINT
 1694: 
 1695: Parent signal assignment:
 1696:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 1697: 
 1698: Child signal assignment:
 1699:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
 1700: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
 1701:  to restart a new child.)
 1702: 
 1703: Command-line invocations:
 1704:  B<kill> B<-s> SIGTERM I<PID>
 1705:  B<kill> B<-s> SIGINT I<PID>
 1706: 
 1707: Subroutine B<HUNTSMAN>:
 1708:  This is only invoked for the B<lond> parent I<PID>.
 1709: This kills all the children, and then the parent.
 1710: The B<lonc.pid> file is cleared.
 1711: 
 1712: =item *
 1713: 
 1714: SIGHUP
 1715: 
 1716: Current bug:
 1717:  This signal can only be processed the first time
 1718: on the parent process.  Subsequent SIGHUP signals
 1719: have no effect.
 1720: 
 1721: Parent signal assignment:
 1722:  $SIG{HUP}  = \&HUPSMAN;
 1723: 
 1724: Child signal assignment:
 1725:  none (nothing happens)
 1726: 
 1727: Command-line invocations:
 1728:  B<kill> B<-s> SIGHUP I<PID>
 1729: 
 1730: Subroutine B<HUPSMAN>:
 1731:  This is only invoked for the B<lond> parent I<PID>,
 1732: This kills all the children, and then the parent.
 1733: The B<lond.pid> file is cleared.
 1734: 
 1735: =item *
 1736: 
 1737: SIGUSR1
 1738: 
 1739: Parent signal assignment:
 1740:  $SIG{USR1} = \&USRMAN;
 1741: 
 1742: Child signal assignment:
 1743:  $SIG{USR1}= \&logstatus;
 1744: 
 1745: Command-line invocations:
 1746:  B<kill> B<-s> SIGUSR1 I<PID>
 1747: 
 1748: Subroutine B<USRMAN>:
 1749:  When invoked for the B<lond> parent I<PID>,
 1750: SIGUSR1 is sent to all the children, and the status of
 1751: each connection is logged.
 1752: 
 1753: =item *
 1754: 
 1755: SIGCHLD
 1756: 
 1757: Parent signal assignment:
 1758:  $SIG{CHLD} = \&REAPER;
 1759: 
 1760: Child signal assignment:
 1761:  none
 1762: 
 1763: Command-line invocations:
 1764:  B<kill> B<-s> SIGCHLD I<PID>
 1765: 
 1766: Subroutine B<REAPER>:
 1767:  This is only invoked for the B<lond> parent I<PID>.
 1768: Information pertaining to the child is removed.
 1769: The socket port is cleaned up.
 1770: 
 1771: =back
 1772: 
 1773: B<SERVER-SIDE ACTIVITIES>
 1774: 
 1775: Server-side information can be accepted in an encrypted or non-encrypted
 1776: method.
 1777: 
 1778: =over 4
 1779: 
 1780: =item ping
 1781: 
 1782: Query a client in the hosts.tab table; "Are you there?"
 1783: 
 1784: =item pong
 1785: 
 1786: Respond to a ping query.
 1787: 
 1788: =item ekey
 1789: 
 1790: Read in encrypted key, make cipher.  Respond with a buildkey.
 1791: 
 1792: =item load
 1793: 
 1794: Respond with CPU load based on a computation upon /proc/loadavg.
 1795: 
 1796: =item currentauth
 1797: 
 1798: Reply with current authentication information (only over an
 1799: encrypted channel).
 1800: 
 1801: =item auth
 1802: 
 1803: Only over an encrypted channel, reply as to whether a user's
 1804: authentication information can be validated.
 1805: 
 1806: =item passwd
 1807: 
 1808: Allow for a password to be set.
 1809: 
 1810: =item makeuser
 1811: 
 1812: Make a user.
 1813: 
 1814: =item passwd
 1815: 
 1816: Allow for authentication mechanism and password to be changed.
 1817: 
 1818: =item home
 1819: 
 1820: Respond to a question "are you the home for a given user?"
 1821: 
 1822: =item update
 1823: 
 1824: Update contents of a subscribed resource.
 1825: 
 1826: =item unsubscribe
 1827: 
 1828: The server is unsubscribing from a resource.
 1829: 
 1830: =item subscribe
 1831: 
 1832: The server is subscribing to a resource.
 1833: 
 1834: =item log
 1835: 
 1836: Place in B<logs/lond.log>
 1837: 
 1838: =item put
 1839: 
 1840: stores hash in namespace
 1841: 
 1842: =item rolesput
 1843: 
 1844: put a role into a user's environment
 1845: 
 1846: =item get
 1847: 
 1848: returns hash with keys from array
 1849: reference filled in from namespace
 1850: 
 1851: =item eget
 1852: 
 1853: returns hash with keys from array
 1854: reference filled in from namesp (encrypts the return communication)
 1855: 
 1856: =item rolesget
 1857: 
 1858: get a role from a user's environment
 1859: 
 1860: =item del
 1861: 
 1862: deletes keys out of array from namespace
 1863: 
 1864: =item keys
 1865: 
 1866: returns namespace keys
 1867: 
 1868: =item dump
 1869: 
 1870: dumps the complete (or key matching regexp) namespace into a hash
 1871: 
 1872: =item store
 1873: 
 1874: stores hash permanently
 1875: for this url; hashref needs to be given and should be a \%hashname; the
 1876: remaining args aren't required and if they aren't passed or are '' they will
 1877: be derived from the ENV
 1878: 
 1879: =item restore
 1880: 
 1881: returns a hash for a given url
 1882: 
 1883: =item querysend
 1884: 
 1885: Tells client about the lonsql process that has been launched in response
 1886: to a sent query.
 1887: 
 1888: =item queryreply
 1889: 
 1890: Accept information from lonsql and make appropriate storage in temporary
 1891: file space.
 1892: 
 1893: =item idput
 1894: 
 1895: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
 1896: for each student, defined perhaps by the institutional Registrar.)
 1897: 
 1898: =item idget
 1899: 
 1900: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
 1901: for each student, defined perhaps by the institutional Registrar.)
 1902: 
 1903: =item tmpput
 1904: 
 1905: Accept and store information in temporary space.
 1906: 
 1907: =item tmpget
 1908: 
 1909: Send along temporarily stored information.
 1910: 
 1911: =item ls
 1912: 
 1913: List part of a user's directory.
 1914: 
 1915: =item Hanging up (exit or init)
 1916: 
 1917: What to do when a client tells the server that they (the client)
 1918: are leaving the network.
 1919: 
 1920: =item unknown command
 1921: 
 1922: If B<lond> is sent an unknown command (not in the list above),
 1923: it replys to the client "unknown_cmd".
 1924: 
 1925: =item UNKNOWN CLIENT
 1926: 
 1927: If the anti-spoofing algorithm cannot verify the client,
 1928: the client is rejected (with a "refused" message sent
 1929: to the client, and the connection is closed.
 1930: 
 1931: =back
 1932: 
 1933: =head1 PREREQUISITES
 1934: 
 1935: IO::Socket
 1936: IO::File
 1937: Apache::File
 1938: Symbol
 1939: POSIX
 1940: Crypt::IDEA
 1941: LWP::UserAgent()
 1942: GDBM_File
 1943: Authen::Krb4
 1944: Authen::Krb5
 1945: 
 1946: =head1 COREQUISITES
 1947: 
 1948: =head1 OSNAMES
 1949: 
 1950: linux
 1951: 
 1952: =head1 SCRIPT CATEGORIES
 1953: 
 1954: Server/Process
 1955: 
 1956: =cut

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