File:  [LON-CAPA] / loncom / lond
Revision 1.99: download - view: text, annotated - select for diffs
Fri Sep 20 02:04:07 2002 UTC (21 years, 7 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
bug 779 Detect local auth of a nonexistent user and unconditionally fail it.

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

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