File:  [LON-CAPA] / loncom / lond
Revision 1.101: download - view: text, annotated - select for diffs
Thu Oct 3 15:02:22 2002 UTC (21 years, 7 months ago) by www
Branches: MAIN
CVS tags: HEAD
Fixes Bug #111, toward Bug #531
Can now explicitly address current version of a resource, not just previous
ones.

Does so by generating a symbolic link from the "versioned" filename to the
current file. Deletes symbolic link again when file is republished, and
subsequently replaces it by the now-stale "real" file.

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

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