File:  [LON-CAPA] / loncom / lond
Revision 1.90.2.1: download - view: text, annotated - select for diffs
Tue Sep 3 02:02:50 2002 UTC (21 years, 8 months ago) by albertel
Branches: version_0_5_1
Diff to branchpoint 1.90: preferred, unified
- backport of 1.94

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

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