File:  [LON-CAPA] / loncom / lond
Revision 1.74: download - view: text, annotated - select for diffs
Sun Mar 3 19:49:00 2002 UTC (22 years, 2 months ago) by harris41
Branches: MAIN
CVS tags: HEAD
up to date, fairly complete documentation

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

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