File:  [LON-CAPA] / loncom / lond
Revision 1.96: download - view: text, annotated - select for diffs
Fri Sep 13 02:46:12 2002 UTC (21 years, 7 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Log error value from passwd change to lond.log as textual equivalent.
Analysis for Bug 701.
 Useful addition in any event so we'll commit it that way too.

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

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