File:  [LON-CAPA] / loncom / lond
Revision 1.103: download - view: text, annotated - select for diffs
Wed Oct 30 14:50:04 2002 UTC (21 years, 6 months ago) by www
Branches: MAIN
CVS tags: version_0_6, HEAD
Show status in "ps"

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

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