File:  [LON-CAPA] / loncom / lond
Revision 1.75: download - view: text, annotated - select for diffs
Wed Mar 27 04:07:02 2002 UTC (22 years, 1 month ago) by foxr
Branches: MAIN
CVS tags: HEAD
Add DoSelect sub to encapsulate select in the presence of signals.

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

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