File:  [LON-CAPA] / loncom / lond
Revision 1.102: download - view: text, annotated - select for diffs
Mon Oct 7 13:50:36 2002 UTC (21 years, 6 months ago) by www
Branches: MAIN
CVS tags: HEAD
Toward bug 531.

Can address most recent version.
Can find out with lonnet::getversion what the most recent version is
Shows versions in lonmeta

    1: #!/usr/bin/perl
    2: # The LearningOnline Network
    3: # lond "LON Daemon" Server (port "LOND" 5663)
    4: #
    5: # $Id: lond,v 1.102 2002/10/07 13:50:36 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: }
  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: # ------------------------------------------------------------- current version
 1019:                    } elsif ($userinput =~ /^currentversion/) {
 1020:                        my ($cmd,$fname)=split(/:/,$userinput);
 1021: 		       print $client &currentversion($fname)."\n";
 1022: # ------------------------------------------------------------------------- log
 1023:                    } elsif ($userinput =~ /^log/) {
 1024:                        my ($cmd,$udom,$uname,$what)=split(/:/,$userinput);
 1025:                        chomp($what);
 1026:                        my $proname=propath($udom,$uname);
 1027:                        my $now=time;
 1028:                        {
 1029: 			 my $hfh;
 1030: 			 if ($hfh=IO::File->new(">>$proname/activity.log")) { 
 1031:                             print $hfh "$now:$hostid{$clientip}:$what\n";
 1032:                             print $client "ok\n"; 
 1033: 			} else {
 1034:                             print $client "error:$!\n";
 1035: 		        }
 1036: 		       }
 1037: # ------------------------------------------------------------------------- put
 1038:                    } elsif ($userinput =~ /^put/) {
 1039:                       my ($cmd,$udom,$uname,$namespace,$what)
 1040:                           =split(/:/,$userinput);
 1041:                       $namespace=~s/\//\_/g;
 1042:                       $namespace=~s/\W//g;
 1043:                       if ($namespace ne 'roles') {
 1044:                        chomp($what);
 1045:                        my $proname=propath($udom,$uname);
 1046:                        my $now=time;
 1047:                        unless ($namespace=~/^nohist\_/) {
 1048: 			   my $hfh;
 1049: 			   if (
 1050:                              $hfh=IO::File->new(">>$proname/$namespace.hist")
 1051: 			       ) { print $hfh "P:$now:$what\n"; }
 1052: 		       }
 1053:                        my @pairs=split(/\&/,$what);
 1054:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT,0640)) {
 1055:                            foreach $pair (@pairs) {
 1056: 			       ($key,$value)=split(/=/,$pair);
 1057:                                $hash{$key}=$value;
 1058:                            }
 1059: 			   if (untie(%hash)) {
 1060:                               print $client "ok\n";
 1061:                            } else {
 1062:                               print $client "error:$!\n";
 1063:                            }
 1064:                        } else {
 1065:                            print $client "error:$!\n";
 1066:                        }
 1067: 		      } else {
 1068:                           print $client "refused\n";
 1069:                       }
 1070: # -------------------------------------------------------------------- rolesput
 1071:                    } elsif ($userinput =~ /^rolesput/) {
 1072: 		       &Debug("rolesput");
 1073: 		    if ($wasenc==1) {
 1074:                        my ($cmd,$exedom,$exeuser,$udom,$uname,$what)
 1075:                           =split(/:/,$userinput);
 1076: 		       &Debug("cmd = ".$cmd." exedom= ".$exedom.
 1077: 				    "user = ".$exeuser." udom=".$udom.
 1078: 				    "what = ".$what);
 1079:                        my $namespace='roles';
 1080:                        chomp($what);
 1081:                        my $proname=propath($udom,$uname);
 1082:                        my $now=time;
 1083:                        {
 1084: 			   my $hfh;
 1085: 			   if (
 1086:                              $hfh=IO::File->new(">>$proname/$namespace.hist")
 1087: 			       ) { 
 1088:                                   print $hfh "P:$now:$exedom:$exeuser:$what\n";
 1089:                                  }
 1090: 		       }
 1091:                        my @pairs=split(/\&/,$what);
 1092:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT,0640)) {
 1093:                            foreach $pair (@pairs) {
 1094: 			       ($key,$value)=split(/=/,$pair);
 1095: 			       &ManagePermissions($key, $udom, $uname,
 1096: 						  &GetAuthType( $udom, 
 1097: 								$uname));
 1098:                                $hash{$key}=$value;
 1099: 			       
 1100:                            }
 1101: 			   if (untie(%hash)) {
 1102:                               print $client "ok\n";
 1103:                            } else {
 1104:                               print $client "error:$!\n";
 1105:                            }
 1106:                        } else {
 1107:                            print $client "error:$!\n";
 1108:                        }
 1109: 		      } else {
 1110:                           print $client "refused\n";
 1111:                       }
 1112: # ------------------------------------------------------------------------- get
 1113:                    } elsif ($userinput =~ /^get/) {
 1114:                        my ($cmd,$udom,$uname,$namespace,$what)
 1115:                           =split(/:/,$userinput);
 1116:                        $namespace=~s/\//\_/g;
 1117:                        $namespace=~s/\W//g;
 1118:                        chomp($what);
 1119:                        my @queries=split(/\&/,$what);
 1120:                        my $proname=propath($udom,$uname);
 1121:                        my $qresult='';
 1122:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER,0640)) {
 1123:                            for ($i=0;$i<=$#queries;$i++) {
 1124:                                $qresult.="$hash{$queries[$i]}&";
 1125:                            }
 1126: 			   if (untie(%hash)) {
 1127: 		              $qresult=~s/\&$//;
 1128:                               print $client "$qresult\n";
 1129:                            } else {
 1130:                               print $client "error:$!\n";
 1131:                            }
 1132:                        } else {
 1133:                            print $client "error:$!\n";
 1134:                        }
 1135: # ------------------------------------------------------------------------ eget
 1136:                    } elsif ($userinput =~ /^eget/) {
 1137:                        my ($cmd,$udom,$uname,$namespace,$what)
 1138:                           =split(/:/,$userinput);
 1139:                        $namespace=~s/\//\_/g;
 1140:                        $namespace=~s/\W//g;
 1141:                        chomp($what);
 1142:                        my @queries=split(/\&/,$what);
 1143:                        my $proname=propath($udom,$uname);
 1144:                        my $qresult='';
 1145:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER,0640)) {
 1146:                            for ($i=0;$i<=$#queries;$i++) {
 1147:                                $qresult.="$hash{$queries[$i]}&";
 1148:                            }
 1149: 			   if (untie(%hash)) {
 1150: 		              $qresult=~s/\&$//;
 1151:                               if ($cipher) {
 1152:                                 my $cmdlength=length($qresult);
 1153:                                 $qresult.="         ";
 1154:                                 my $encqresult='';
 1155:                                 for 
 1156: 				(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 1157:                                  $encqresult.=
 1158:                                  unpack("H16",
 1159:                                  $cipher->encrypt(substr($qresult,$encidx,8)));
 1160:                                 }
 1161:                                 print $client "enc:$cmdlength:$encqresult\n";
 1162: 			      } else {
 1163: 			        print $client "error:no_key\n";
 1164:                               }
 1165:                            } else {
 1166:                               print $client "error:$!\n";
 1167:                            }
 1168:                        } else {
 1169:                            print $client "error:$!\n";
 1170:                        }
 1171: # ------------------------------------------------------------------------- del
 1172:                    } elsif ($userinput =~ /^del/) {
 1173:                        my ($cmd,$udom,$uname,$namespace,$what)
 1174:                           =split(/:/,$userinput);
 1175:                        $namespace=~s/\//\_/g;
 1176:                        $namespace=~s/\W//g;
 1177:                        chomp($what);
 1178:                        my $proname=propath($udom,$uname);
 1179:                        my $now=time;
 1180:                        unless ($namespace=~/^nohist\_/) {
 1181: 			   my $hfh;
 1182: 			   if (
 1183:                              $hfh=IO::File->new(">>$proname/$namespace.hist")
 1184: 			       ) { print $hfh "D:$now:$what\n"; }
 1185: 		       }
 1186:                        my @keys=split(/\&/,$what);
 1187:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT,0640)) {
 1188:                            foreach $key (@keys) {
 1189:                                delete($hash{$key});
 1190:                            }
 1191: 			   if (untie(%hash)) {
 1192:                               print $client "ok\n";
 1193:                            } else {
 1194:                               print $client "error:$!\n";
 1195:                            }
 1196:                        } else {
 1197:                            print $client "error:$!\n";
 1198:                        }
 1199: # ------------------------------------------------------------------------ keys
 1200:                    } elsif ($userinput =~ /^keys/) {
 1201:                        my ($cmd,$udom,$uname,$namespace)
 1202:                           =split(/:/,$userinput);
 1203:                        $namespace=~s/\//\_/g;
 1204:                        $namespace=~s/\W//g;
 1205:                        my $proname=propath($udom,$uname);
 1206:                        my $qresult='';
 1207:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER,0640)) {
 1208:                            foreach $key (keys %hash) {
 1209:                                $qresult.="$key&";
 1210:                            }
 1211: 			   if (untie(%hash)) {
 1212: 		              $qresult=~s/\&$//;
 1213:                               print $client "$qresult\n";
 1214:                            } else {
 1215:                               print $client "error:$!\n";
 1216:                            }
 1217:                        } else {
 1218:                            print $client "error:$!\n";
 1219:                        }
 1220: # ------------------------------------------------------------------------ dump
 1221:                    } elsif ($userinput =~ /^dump/) {
 1222:                        my ($cmd,$udom,$uname,$namespace,$regexp)
 1223:                           =split(/:/,$userinput);
 1224:                        $namespace=~s/\//\_/g;
 1225:                        $namespace=~s/\W//g;
 1226:                        if (defined($regexp)) {
 1227:                           $regexp=&unescape($regexp);
 1228: 		       } else {
 1229:                           $regexp='.';
 1230: 		       }
 1231:                        my $qresult='';
 1232:                        my $proname=propath($udom,$uname);
 1233:     if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
 1234:                            study($regexp);
 1235:                            while (($key,$value) = each(%hash)) {
 1236:                                if ($regexp eq '.') {
 1237:                                    $qresult.=$key.'='.$value.'&';
 1238:                                } else {
 1239:                                    my $unescapeKey = &unescape($key);
 1240:                                    if (eval('$unescapeKey=~/$regexp/')) {
 1241:                                        $qresult.="$key=$value&";
 1242:                                    }
 1243:                                }
 1244:                            }
 1245:                            if (untie(%hash)) {
 1246:                                chop($qresult);
 1247:                                print $client "$qresult\n";
 1248:                            } else {
 1249:                                print $client "error:$!\n";
 1250:                            }
 1251:                        } else {
 1252:                            print $client "error:$!\n";
 1253:                        }
 1254: # ----------------------------------------------------------------------- store
 1255:                    } elsif ($userinput =~ /^store/) {
 1256:                       my ($cmd,$udom,$uname,$namespace,$rid,$what)
 1257:                           =split(/:/,$userinput);
 1258:                       $namespace=~s/\//\_/g;
 1259:                       $namespace=~s/\W//g;
 1260:                       if ($namespace ne 'roles') {
 1261:                        chomp($what);
 1262:                        my $proname=propath($udom,$uname);
 1263:                        my $now=time;
 1264:                        unless ($namespace=~/^nohist\_/) {
 1265: 			   my $hfh;
 1266: 			   if (
 1267:                              $hfh=IO::File->new(">>$proname/$namespace.hist")
 1268: 			       ) { print $hfh "P:$now:$rid:$what\n"; }
 1269: 		       }
 1270:                        my @pairs=split(/\&/,$what);
 1271:                          
 1272:     if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT,0640)) {
 1273:                            my @previouskeys=split(/&/,$hash{"keys:$rid"});
 1274:                            my $key;
 1275:                            $hash{"version:$rid"}++;
 1276:                            my $version=$hash{"version:$rid"};
 1277:                            my $allkeys=''; 
 1278:                            foreach $pair (@pairs) {
 1279: 			       ($key,$value)=split(/=/,$pair);
 1280:                                $allkeys.=$key.':';
 1281:                                $hash{"$version:$rid:$key"}=$value;
 1282:                            }
 1283:                            $hash{"$version:$rid:timestamp"}=$now;
 1284:                            $allkeys.='timestamp';
 1285:                            $hash{"$version:keys:$rid"}=$allkeys;
 1286: 			   if (untie(%hash)) {
 1287:                               print $client "ok\n";
 1288:                            } else {
 1289:                               print $client "error:$!\n";
 1290:                            }
 1291:                        } else {
 1292:                            print $client "error:$!\n";
 1293:                        }
 1294: 		      } else {
 1295:                           print $client "refused\n";
 1296:                       }
 1297: # --------------------------------------------------------------------- restore
 1298:                    } elsif ($userinput =~ /^restore/) {
 1299:                        my ($cmd,$udom,$uname,$namespace,$rid)
 1300:                           =split(/:/,$userinput);
 1301:                        $namespace=~s/\//\_/g;
 1302:                        $namespace=~s/\W//g;
 1303:                        chomp($rid);
 1304:                        my $proname=propath($udom,$uname);
 1305:                        my $qresult='';
 1306:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER,0640)) {
 1307:                 	   my $version=$hash{"version:$rid"};
 1308:                            $qresult.="version=$version&";
 1309:                            my $scope;
 1310:                            for ($scope=1;$scope<=$version;$scope++) {
 1311: 			      my $vkeys=$hash{"$scope:keys:$rid"};
 1312:                               my @keys=split(/:/,$vkeys);
 1313:                               my $key;
 1314:                               $qresult.="$scope:keys=$vkeys&";
 1315:                               foreach $key (@keys) {
 1316: 	     $qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
 1317:                               }                                  
 1318:                            }
 1319: 			   if (untie(%hash)) {
 1320: 		              $qresult=~s/\&$//;
 1321:                               print $client "$qresult\n";
 1322:                            } else {
 1323:                               print $client "error:$!\n";
 1324:                            }
 1325:                        } else {
 1326:                            print $client "error:$!\n";
 1327:                        }
 1328: # -------------------------------------------------------------------- chatsend
 1329:                    } elsif ($userinput =~ /^chatsend/) {
 1330:                        my ($cmd,$cdom,$cnum,$newpost)=split(/\:/,$userinput);
 1331:                        &chatadd($cdom,$cnum,$newpost);
 1332:                        print $client "ok\n";
 1333: # -------------------------------------------------------------------- chatretr
 1334:                    } elsif ($userinput =~ /^chatretr/) {
 1335:                        my ($cmd,$cdom,$cnum)=split(/\:/,$userinput);
 1336:                        my $reply='';
 1337:                        foreach (&getchat($cdom,$cnum)) {
 1338: 			   $reply.=&escape($_).':';
 1339:                        }
 1340:                        $reply=~s/\:$//;
 1341:                        print $client $reply."\n";
 1342: # ------------------------------------------------------------------- querysend
 1343:                    } elsif ($userinput =~ /^querysend/) {
 1344:                        my ($cmd,$query,
 1345: 			   $arg1,$arg2,$arg3)=split(/\:/,$userinput);
 1346: 		       $query=~s/\n*$//g;
 1347: 		       print $client "".
 1348: 			       sqlreply("$hostid{$clientip}\&$query".
 1349: 					"\&$arg1"."\&$arg2"."\&$arg3")."\n";
 1350: # ------------------------------------------------------------------ queryreply
 1351:                    } elsif ($userinput =~ /^queryreply/) {
 1352:                        my ($cmd,$id,$reply)=split(/:/,$userinput); 
 1353: 		       my $store;
 1354:                        my $execdir=$perlvar{'lonDaemons'};
 1355:                        if ($store=IO::File->new(">$execdir/tmp/$id")) {
 1356: 			   $reply=~s/\&/\n/g;
 1357: 			   print $store $reply;
 1358: 			   close $store;
 1359: 			   my $store2=IO::File->new(">$execdir/tmp/$id.end");
 1360: 			   print $store2 "done\n";
 1361: 			   close $store2;
 1362: 			   print $client "ok\n";
 1363: 		       }
 1364: 		       else {
 1365: 			   print $client "error:$!\n";
 1366: 		       }
 1367: # ----------------------------------------------------------------------- idput
 1368:                    } elsif ($userinput =~ /^idput/) {
 1369:                        my ($cmd,$udom,$what)=split(/:/,$userinput);
 1370:                        chomp($what);
 1371:                        $udom=~s/\W//g;
 1372:                        my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
 1373:                        my $now=time;
 1374:                        {
 1375: 			   my $hfh;
 1376: 			   if (
 1377:                              $hfh=IO::File->new(">>$proname.hist")
 1378: 			       ) { print $hfh "P:$now:$what\n"; }
 1379: 		       }
 1380:                        my @pairs=split(/\&/,$what);
 1381:                  if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT,0640)) {
 1382:                            foreach $pair (@pairs) {
 1383: 			       ($key,$value)=split(/=/,$pair);
 1384:                                $hash{$key}=$value;
 1385:                            }
 1386: 			   if (untie(%hash)) {
 1387:                               print $client "ok\n";
 1388:                            } else {
 1389:                               print $client "error:$!\n";
 1390:                            }
 1391:                        } else {
 1392:                            print $client "error:$!\n";
 1393:                        }
 1394: # ----------------------------------------------------------------------- idget
 1395:                    } elsif ($userinput =~ /^idget/) {
 1396:                        my ($cmd,$udom,$what)=split(/:/,$userinput);
 1397:                        chomp($what);
 1398:                        $udom=~s/\W//g;
 1399:                        my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
 1400:                        my @queries=split(/\&/,$what);
 1401:                        my $qresult='';
 1402:                  if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER,0640)) {
 1403:                            for ($i=0;$i<=$#queries;$i++) {
 1404:                                $qresult.="$hash{$queries[$i]}&";
 1405:                            }
 1406: 			   if (untie(%hash)) {
 1407: 		              $qresult=~s/\&$//;
 1408:                               print $client "$qresult\n";
 1409:                            } else {
 1410:                               print $client "error:$!\n";
 1411:                            }
 1412:                        } else {
 1413:                            print $client "error:$!\n";
 1414:                        }
 1415: # ---------------------------------------------------------------------- tmpput
 1416:                    } elsif ($userinput =~ /^tmpput/) {
 1417:                        my ($cmd,$what)=split(/:/,$userinput);
 1418: 		       my $store;
 1419:                        $tmpsnum++;
 1420:                        my $id=$$.'_'.$clientip.'_'.$tmpsnum;
 1421:                        $id=~s/\W/\_/g;
 1422:                        $what=~s/\n//g;
 1423:                        my $execdir=$perlvar{'lonDaemons'};
 1424:                        if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
 1425: 			   print $store $what;
 1426: 			   close $store;
 1427: 			   print $client "$id\n";
 1428: 		       }
 1429: 		       else {
 1430: 			   print $client "error:$!\n";
 1431: 		       }
 1432: 
 1433: # ---------------------------------------------------------------------- tmpget
 1434:                    } elsif ($userinput =~ /^tmpget/) {
 1435:                        my ($cmd,$id)=split(/:/,$userinput);
 1436:                        chomp($id);
 1437:                        $id=~s/\W/\_/g;
 1438:                        my $store;
 1439:                        my $execdir=$perlvar{'lonDaemons'};
 1440:                        if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
 1441:                            my $reply=<$store>;
 1442: 			   print $client "$reply\n";
 1443:                            close $store;
 1444: 		       }
 1445: 		       else {
 1446: 			   print $client "error:$!\n";
 1447: 		       }
 1448: 
 1449: # -------------------------------------------------------------------------- ls
 1450:                    } elsif ($userinput =~ /^ls/) {
 1451:                        my ($cmd,$ulsdir)=split(/:/,$userinput);
 1452:                        my $ulsout='';
 1453:                        my $ulsfn;
 1454:                        if (-e $ulsdir) {
 1455:                            if(-d $ulsdir) {
 1456:                                if (opendir(LSDIR,$ulsdir)) {
 1457:                                    while ($ulsfn=readdir(LSDIR)) {
 1458:                                        my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1459:                                        $ulsout.=$ulsfn.'&'.
 1460:                                                 join('&',@ulsstats).':';
 1461:                                    }
 1462:                                    closedir(LSDIR);
 1463:                                }
 1464:                            } else {
 1465:                                my @ulsstats=stat($ulsdir);
 1466:                                $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1467:                            }
 1468:                        } else {
 1469:                           $ulsout='no_such_dir';
 1470:                        }
 1471:                        if ($ulsout eq '') { $ulsout='empty'; }
 1472:                        print $client "$ulsout\n";
 1473: # ------------------------------------------------------------------ Hanging up
 1474:                    } elsif (($userinput =~ /^exit/) ||
 1475:                             ($userinput =~ /^init/)) {
 1476:                        &logthis(
 1477:       "Client $clientip ($hostid{$clientip}) hanging up: $userinput");
 1478:                        print $client "bye\n";
 1479:                        $client->close();
 1480: 		       last;
 1481: # ------------------------------------------------------------- unknown command
 1482:                    } else {
 1483:                        # unknown command
 1484:                        print $client "unknown_cmd\n";
 1485:                    }
 1486: # -------------------------------------------------------------------- complete
 1487: 		   alarm(0);
 1488:                    &status('Listening to '.$hostid{$clientip});
 1489: 	       }
 1490: # --------------------------------------------- client unknown or fishy, refuse
 1491:             } else {
 1492: 	        print $client "refused\n";
 1493:                 $client->close();
 1494:                 &logthis("<font color=blue>WARNING: "
 1495:                 ."Rejected client $clientip, closing connection</font>");
 1496:             }
 1497: 	}              
 1498: 
 1499: # =============================================================================
 1500:        
 1501: 	&logthis("<font color=red>CRITICAL: "
 1502: 		 ."Disconnect from $clientip ($hostid{$clientip})</font>");    
 1503:         # tidy up gracefully and finish
 1504:     
 1505:         $server->close();
 1506: 
 1507:         # this exit is VERY important, otherwise the child will become
 1508:         # a producer of more and more children, forking yourself into
 1509:         # process death.
 1510:         exit;
 1511:     }
 1512: }
 1513: 
 1514: 
 1515: #
 1516: #   Checks to see if the input roleput request was to set
 1517: # an author role.  If so, invokes the lchtmldir script to set
 1518: # up a correct public_html 
 1519: # Parameters:
 1520: #    request   - The request sent to the rolesput subchunk.
 1521: #                We're looking for  /domain/_au
 1522: #    domain    - The domain in which the user is having roles doctored.
 1523: #    user      - Name of the user for which the role is being put.
 1524: #    authtype  - The authentication type associated with the user.
 1525: #
 1526: sub ManagePermissions
 1527: {
 1528:     my $request = shift;
 1529:     my $domain  = shift;
 1530:     my $user    = shift;
 1531:     my $authtype= shift;
 1532: 
 1533:     # See if the request is of the form /$domain/_au
 1534: 
 1535:     if($request =~ /^(\/$domain\/_au)$/) { # It's an author rolesput...
 1536: 	my $execdir = $perlvar{'lonDaemons'};
 1537: 	my $userhome= "/home/$user" ;
 1538: 	Debug("system $execdir/lchtmldir $userhome $system $authtype");
 1539: 	system("$execdir/lchtmldir $userhome $user $authtype");
 1540:     }
 1541: }
 1542: #
 1543: #   GetAuthType - Determines the authorization type of a user in a domain.
 1544: 
 1545: #     Returns the authorization type or nouser if there is no such user.
 1546: #
 1547: sub GetAuthType 
 1548: {
 1549:     my $domain = shift;
 1550:     my $user   = shift;
 1551: 
 1552:     Debug("GetAuthType( $domain, $user ) \n");
 1553:     my $proname    = &propath($domain, $user); 
 1554:     my $passwdfile = "$proname/passwd";
 1555:     if( -e $passwdfile ) {
 1556: 	my $pf = IO::File->new($passwdfile);
 1557: 	my $realpassword = <$pf>;
 1558: 	chomp($realpassword);
 1559: 	Debug("Password info = $realpassword\n");
 1560: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
 1561: 	Debug("Authtype = $authtype, content = $contentpwd\n");
 1562: 	my $availinfo = '';
 1563: 	if($authtype eq 'krb4' or $authtype eq 'krb5') {
 1564: 	    $availinfo = $contentpwd;
 1565: 	}
 1566: 
 1567: 	return "$authtype:$availinfo";
 1568:     }
 1569:     else {
 1570: 	Debug("Returning nouser");
 1571: 	return "nouser";
 1572:     }
 1573: }
 1574: 
 1575: sub addline {
 1576:     my ($fname,$hostid,$ip,$newline)=@_;
 1577:     my $contents;
 1578:     my $found=0;
 1579:     my $expr='^'.$hostid.':'.$ip.':';
 1580:     $expr =~ s/\./\\\./g;
 1581:     if ($sh=IO::File->new("$fname.subscription")) {
 1582: 	while (my $subline=<$sh>) {
 1583: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
 1584: 	}
 1585: 	$sh->close();
 1586:     }
 1587:     $sh=IO::File->new(">$fname.subscription");
 1588:     if ($contents) { print $sh $contents; }
 1589:     if ($newline) { print $sh $newline; }
 1590:     $sh->close();
 1591:     return $found;
 1592: }
 1593: 
 1594: sub getchat {
 1595:     my ($cdom,$cname)=@_;
 1596:     my %hash;
 1597:     my $proname=&propath($cdom,$cname);
 1598:     my @entries=();
 1599:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
 1600: 	    &GDBM_READER(),0640)) {
 1601: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
 1602: 	untie %hash;
 1603:     }
 1604:     return @entries;
 1605: }
 1606: 
 1607: sub chatadd {
 1608:     my ($cdom,$cname,$newchat)=@_;
 1609:     my %hash;
 1610:     my $proname=&propath($cdom,$cname);
 1611:     my @entries=();
 1612:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
 1613: 	    &GDBM_WRCREAT(),0640)) {
 1614: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
 1615: 	my $time=time;
 1616: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
 1617: 	my ($thentime,$idnum)=split(/\_/,$lastid);
 1618: 	my $newid=$time.'_000000';
 1619: 	if ($thentime==$time) {
 1620: 	    $idnum=~s/^0+//;
 1621: 	    $idnum++;
 1622: 	    $idnum=substr('000000'.$idnum,-6,6);
 1623: 	    $newid=$time.'_'.$idnum;
 1624: 	}
 1625: 	$hash{$newid}=$newchat;
 1626: 	my $expired=$time-3600;
 1627: 	foreach (keys %hash) {
 1628: 	    my ($thistime)=($_=~/(\d+)\_/);
 1629: 	    if ($thistime<$expired) {
 1630: 		delete $hash{$_};
 1631: 	    }
 1632: 	}
 1633: 	untie %hash;
 1634:     }
 1635: }
 1636: 
 1637: sub unsub {
 1638:     my ($fname,$clientip)=@_;
 1639:     my $result;
 1640:     if (unlink("$fname.$hostid{$clientip}")) {
 1641: 	$result="ok\n";
 1642:     } else {
 1643: 	$result="not_subscribed\n";
 1644:     }
 1645:     if (-e "$fname.subscription") {
 1646: 	my $found=&addline($fname,$hostid{$clientip},$clientip,'');
 1647: 	if ($found) { $result="ok\n"; }
 1648:     } else {
 1649: 	if ($result != "ok\n") { $result="not_subscribed\n"; }
 1650:     }
 1651:     return $result;
 1652: }
 1653: 
 1654: sub currentversion {
 1655:     my $fname=shift;
 1656:     my $version=-1;
 1657:     my $ulsdir='';
 1658:     if ($fname=~/^(.+)\/[^\/]+$/) {
 1659:        $ulsdir=$1;
 1660:     }
 1661:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
 1662:     $fname=~s/\.(\w+(?:\.meta)*)$/\.\(\\d\+\)\.$1\$/;
 1663: 
 1664:     if (-e $fname) { $version=1; }
 1665:     if (-e $ulsdir) {
 1666:        if(-d $ulsdir) {
 1667:           if (opendir(LSDIR,$ulsdir)) {
 1668:              while ($ulsfn=readdir(LSDIR)) {
 1669: # see if this is a regular file (ignore links produced earlier)
 1670:                  my $thisfile=$ulsdir.'/'.$ulsfn;
 1671:                  unless (-l $thisfile) {
 1672: 		    if ($thisfile=~/$fname/) {
 1673: 		        if ($1>$version) { $version=$1; }
 1674:                     }
 1675: 		 }
 1676:              }
 1677:              closedir(LSDIR);
 1678:              $version++;
 1679:           }
 1680:       }
 1681:    }
 1682:    return $version;
 1683: }
 1684: 
 1685: sub thisversion {
 1686:     my $fname=shift;
 1687:     my $version=-1;
 1688:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
 1689: 	$version=$1;
 1690:     }
 1691:     return $version;
 1692: }
 1693: 
 1694: sub subscribe {
 1695:     my ($userinput,$clientip)=@_;
 1696:     my $result;
 1697:     my ($cmd,$fname)=split(/:/,$userinput);
 1698:     my $ownership=&ishome($fname);
 1699:     if ($ownership eq 'owner') {
 1700: # explitly asking for the current version?
 1701:         unless (-e $fname) {
 1702:             my $currentversion=&currentversion($fname);
 1703: 	    if (&thisversion($fname)==$currentversion) {
 1704:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
 1705: 		    my $root=$1;
 1706:                     my $extension=$2;
 1707:                     symlink($root.'.'.$extension,
 1708:                             $root.'.'.$currentversion.'.'.$extension);
 1709:                     unless ($extension=~/\.meta$/) {
 1710:                        symlink($root.'.'.$extension.'.meta',
 1711:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
 1712: 		    }
 1713:                 }
 1714:             }
 1715:         }
 1716: 	if (-e $fname) {
 1717: 	    if (-d $fname) {
 1718: 		$result="directory\n";
 1719: 	    } else {
 1720: 		if (-e "$fname.$hostid{$clientip}") {&unsub($fname,$clientip);}
 1721: 		$now=time;
 1722: 		my $found=&addline($fname,$hostid{$clientip},$clientip,
 1723: 				   "$hostid{$clientip}:$clientip:$now\n");
 1724: 		if ($found) { $result="$fname\n"; }
 1725: 		# if they were subscribed to only meta data, delete that
 1726:                 # subscription, when you subscribe to a file you also get
 1727:                 # the metadata
 1728: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
 1729: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
 1730: 		$fname="http://$thisserver/".$fname;
 1731: 		$result="$fname\n";
 1732: 	    }
 1733: 	} else {
 1734: 	    $result="not_found\n";
 1735: 	}
 1736:     } else {
 1737: 	$result="rejected\n";
 1738:     }
 1739:     return $result;
 1740: }
 1741: 
 1742: sub make_passwd_file {
 1743:     my ($uname, $umode,$npass,$passfilename)=@_;
 1744:     my $result="ok\n";
 1745:     if ($umode eq 'krb4' or $umode eq 'krb5') {
 1746: 	{
 1747: 	    my $pf = IO::File->new(">$passfilename");
 1748: 	    print $pf "$umode:$npass\n";
 1749: 	}
 1750:     } elsif ($umode eq 'internal') {
 1751: 	my $salt=time;
 1752: 	$salt=substr($salt,6,2);
 1753: 	my $ncpass=crypt($npass,$salt);
 1754: 	{
 1755: 	    &Debug("Creating internal auth");
 1756: 	    my $pf = IO::File->new(">$passfilename");
 1757: 	    print $pf "internal:$ncpass\n"; 
 1758: 	}
 1759:     } elsif ($umode eq 'localauth') {
 1760: 	{
 1761: 	    my $pf = IO::File->new(">$passfilename");
 1762: 	    print $pf "localauth:$npass\n";
 1763: 	}
 1764:     } elsif ($umode eq 'unix') {
 1765: 	{
 1766: 	    my $execpath="$perlvar{'lonDaemons'}/"."lcuseradd";
 1767: 	    {
 1768: 		&Debug("Executing external: ".$execpath);
 1769: 		&Debug("user  = ".$uname.", Password =". $npass);
 1770: 		my $se = IO::File->new("|$execpath > /home/www/lcuseradd.log");
 1771: 		print $se "$uname\n";
 1772: 		print $se "$npass\n";
 1773: 		print $se "$npass\n";
 1774: 	    }
 1775: 	    my $useraddok = $?;
 1776: 	    if($useraddok > 0) {
 1777: 		&logthis("Failed lcuseradd: ".&lcuseraddstrerror($useraddok));
 1778: 	    }
 1779: 	    my $pf = IO::File->new(">$passfilename");
 1780: 	    print $pf "unix:\n";
 1781: 	}
 1782:     } elsif ($umode eq 'none') {
 1783: 	{
 1784: 	    my $pf = IO::File->new(">$passfilename");
 1785: 	    print $pf "none:\n";
 1786: 	}
 1787:     } else {
 1788: 	$result="auth_mode_error\n";
 1789:     }
 1790:     return $result;
 1791: }
 1792: 
 1793: # ----------------------------------- POD (plain old documentation, CPAN style)
 1794: 
 1795: =head1 NAME
 1796: 
 1797: lond - "LON Daemon" Server (port "LOND" 5663)
 1798: 
 1799: =head1 SYNOPSIS
 1800: 
 1801: Usage: B<lond>
 1802: 
 1803: Should only be run as user=www.  This is a command-line script which
 1804: is invoked by B<loncron>.  There is no expectation that a typical user
 1805: will manually start B<lond> from the command-line.  (In other words,
 1806: DO NOT START B<lond> YOURSELF.)
 1807: 
 1808: =head1 DESCRIPTION
 1809: 
 1810: There are two characteristics associated with the running of B<lond>,
 1811: PROCESS MANAGEMENT (starting, stopping, handling child processes)
 1812: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
 1813: subscriptions, etc).  These are described in two large
 1814: sections below.
 1815: 
 1816: B<PROCESS MANAGEMENT>
 1817: 
 1818: Preforker - server who forks first. Runs as a daemon. HUPs.
 1819: Uses IDEA encryption
 1820: 
 1821: B<lond> forks off children processes that correspond to the other servers
 1822: in the network.  Management of these processes can be done at the
 1823: parent process level or the child process level.
 1824: 
 1825: B<logs/lond.log> is the location of log messages.
 1826: 
 1827: The process management is now explained in terms of linux shell commands,
 1828: subroutines internal to this code, and signal assignments:
 1829: 
 1830: =over 4
 1831: 
 1832: =item *
 1833: 
 1834: PID is stored in B<logs/lond.pid>
 1835: 
 1836: This is the process id number of the parent B<lond> process.
 1837: 
 1838: =item *
 1839: 
 1840: SIGTERM and SIGINT
 1841: 
 1842: Parent signal assignment:
 1843:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 1844: 
 1845: Child signal assignment:
 1846:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
 1847: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
 1848:  to restart a new child.)
 1849: 
 1850: Command-line invocations:
 1851:  B<kill> B<-s> SIGTERM I<PID>
 1852:  B<kill> B<-s> SIGINT I<PID>
 1853: 
 1854: Subroutine B<HUNTSMAN>:
 1855:  This is only invoked for the B<lond> parent I<PID>.
 1856: This kills all the children, and then the parent.
 1857: The B<lonc.pid> file is cleared.
 1858: 
 1859: =item *
 1860: 
 1861: SIGHUP
 1862: 
 1863: Current bug:
 1864:  This signal can only be processed the first time
 1865: on the parent process.  Subsequent SIGHUP signals
 1866: have no effect.
 1867: 
 1868: Parent signal assignment:
 1869:  $SIG{HUP}  = \&HUPSMAN;
 1870: 
 1871: Child signal assignment:
 1872:  none (nothing happens)
 1873: 
 1874: Command-line invocations:
 1875:  B<kill> B<-s> SIGHUP I<PID>
 1876: 
 1877: Subroutine B<HUPSMAN>:
 1878:  This is only invoked for the B<lond> parent I<PID>,
 1879: This kills all the children, and then the parent.
 1880: The B<lond.pid> file is cleared.
 1881: 
 1882: =item *
 1883: 
 1884: SIGUSR1
 1885: 
 1886: Parent signal assignment:
 1887:  $SIG{USR1} = \&USRMAN;
 1888: 
 1889: Child signal assignment:
 1890:  $SIG{USR1}= \&logstatus;
 1891: 
 1892: Command-line invocations:
 1893:  B<kill> B<-s> SIGUSR1 I<PID>
 1894: 
 1895: Subroutine B<USRMAN>:
 1896:  When invoked for the B<lond> parent I<PID>,
 1897: SIGUSR1 is sent to all the children, and the status of
 1898: each connection is logged.
 1899: 
 1900: =item *
 1901: 
 1902: SIGCHLD
 1903: 
 1904: Parent signal assignment:
 1905:  $SIG{CHLD} = \&REAPER;
 1906: 
 1907: Child signal assignment:
 1908:  none
 1909: 
 1910: Command-line invocations:
 1911:  B<kill> B<-s> SIGCHLD I<PID>
 1912: 
 1913: Subroutine B<REAPER>:
 1914:  This is only invoked for the B<lond> parent I<PID>.
 1915: Information pertaining to the child is removed.
 1916: The socket port is cleaned up.
 1917: 
 1918: =back
 1919: 
 1920: B<SERVER-SIDE ACTIVITIES>
 1921: 
 1922: Server-side information can be accepted in an encrypted or non-encrypted
 1923: method.
 1924: 
 1925: =over 4
 1926: 
 1927: =item ping
 1928: 
 1929: Query a client in the hosts.tab table; "Are you there?"
 1930: 
 1931: =item pong
 1932: 
 1933: Respond to a ping query.
 1934: 
 1935: =item ekey
 1936: 
 1937: Read in encrypted key, make cipher.  Respond with a buildkey.
 1938: 
 1939: =item load
 1940: 
 1941: Respond with CPU load based on a computation upon /proc/loadavg.
 1942: 
 1943: =item currentauth
 1944: 
 1945: Reply with current authentication information (only over an
 1946: encrypted channel).
 1947: 
 1948: =item auth
 1949: 
 1950: Only over an encrypted channel, reply as to whether a user's
 1951: authentication information can be validated.
 1952: 
 1953: =item passwd
 1954: 
 1955: Allow for a password to be set.
 1956: 
 1957: =item makeuser
 1958: 
 1959: Make a user.
 1960: 
 1961: =item passwd
 1962: 
 1963: Allow for authentication mechanism and password to be changed.
 1964: 
 1965: =item home
 1966: 
 1967: Respond to a question "are you the home for a given user?"
 1968: 
 1969: =item update
 1970: 
 1971: Update contents of a subscribed resource.
 1972: 
 1973: =item unsubscribe
 1974: 
 1975: The server is unsubscribing from a resource.
 1976: 
 1977: =item subscribe
 1978: 
 1979: The server is subscribing to a resource.
 1980: 
 1981: =item log
 1982: 
 1983: Place in B<logs/lond.log>
 1984: 
 1985: =item put
 1986: 
 1987: stores hash in namespace
 1988: 
 1989: =item rolesput
 1990: 
 1991: put a role into a user's environment
 1992: 
 1993: =item get
 1994: 
 1995: returns hash with keys from array
 1996: reference filled in from namespace
 1997: 
 1998: =item eget
 1999: 
 2000: returns hash with keys from array
 2001: reference filled in from namesp (encrypts the return communication)
 2002: 
 2003: =item rolesget
 2004: 
 2005: get a role from a user's environment
 2006: 
 2007: =item del
 2008: 
 2009: deletes keys out of array from namespace
 2010: 
 2011: =item keys
 2012: 
 2013: returns namespace keys
 2014: 
 2015: =item dump
 2016: 
 2017: dumps the complete (or key matching regexp) namespace into a hash
 2018: 
 2019: =item store
 2020: 
 2021: stores hash permanently
 2022: for this url; hashref needs to be given and should be a \%hashname; the
 2023: remaining args aren't required and if they aren't passed or are '' they will
 2024: be derived from the ENV
 2025: 
 2026: =item restore
 2027: 
 2028: returns a hash for a given url
 2029: 
 2030: =item querysend
 2031: 
 2032: Tells client about the lonsql process that has been launched in response
 2033: to a sent query.
 2034: 
 2035: =item queryreply
 2036: 
 2037: Accept information from lonsql and make appropriate storage in temporary
 2038: file space.
 2039: 
 2040: =item idput
 2041: 
 2042: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
 2043: for each student, defined perhaps by the institutional Registrar.)
 2044: 
 2045: =item idget
 2046: 
 2047: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
 2048: for each student, defined perhaps by the institutional Registrar.)
 2049: 
 2050: =item tmpput
 2051: 
 2052: Accept and store information in temporary space.
 2053: 
 2054: =item tmpget
 2055: 
 2056: Send along temporarily stored information.
 2057: 
 2058: =item ls
 2059: 
 2060: List part of a user's directory.
 2061: 
 2062: =item Hanging up (exit or init)
 2063: 
 2064: What to do when a client tells the server that they (the client)
 2065: are leaving the network.
 2066: 
 2067: =item unknown command
 2068: 
 2069: If B<lond> is sent an unknown command (not in the list above),
 2070: it replys to the client "unknown_cmd".
 2071: 
 2072: =item UNKNOWN CLIENT
 2073: 
 2074: If the anti-spoofing algorithm cannot verify the client,
 2075: the client is rejected (with a "refused" message sent
 2076: to the client, and the connection is closed.
 2077: 
 2078: =back
 2079: 
 2080: =head1 PREREQUISITES
 2081: 
 2082: IO::Socket
 2083: IO::File
 2084: Apache::File
 2085: Symbol
 2086: POSIX
 2087: Crypt::IDEA
 2088: LWP::UserAgent()
 2089: GDBM_File
 2090: Authen::Krb4
 2091: Authen::Krb5
 2092: 
 2093: =head1 COREQUISITES
 2094: 
 2095: =head1 OSNAMES
 2096: 
 2097: linux
 2098: 
 2099: =head1 SCRIPT CATEGORIES
 2100: 
 2101: Server/Process
 2102: 
 2103: =cut

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