File:  [LON-CAPA] / loncom / lond
Revision 1.148: download - view: text, annotated - select for diffs
Mon Sep 29 10:09:18 2003 UTC (20 years, 7 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Put in logic to reinit lond itself (except for apache reload).  I don't believe
this logic works correctly yet, however lond still does everything it used to doso I'll do the commit anyway.

    1: #!/usr/bin/perl
    2: # The LearningOnline Network
    3: # lond "LON Daemon" Server (port "LOND" 5663)
    4: #
    5: # $Id: lond,v 1.148 2003/09/29 10:09:18 foxr Exp $
    6: #
    7: # Copyright Michigan State University Board of Trustees
    8: #
    9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
   10: #
   11: # LON-CAPA is free software; you can redistribute it and/or modify
   12: # it under the terms of the GNU General Public License as published by
   13: # the Free Software Foundation; either version 2 of the License, or
   14: # (at your option) any later version.
   15: #
   16: # LON-CAPA is distributed in the hope that it will be useful,
   17: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   18: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   19: # GNU General Public License for more details.
   20: #
   21: # You should have received a copy of the GNU General Public License
   22: # along with LON-CAPA; if not, write to the Free Software
   23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   24: #
   25: # /home/httpd/html/adm/gpl.txt
   26: #
   27: # http://www.lon-capa.org/
   28: #
   29: # 5/26/99,6/4,6/10,6/11,6/14,6/15,6/26,6/28,6/30,
   30: # 7/8,7/9,7/10,7/12,7/17,7/19,9/21,
   31: # 10/7,10/8,10/9,10/11,10/13,10/15,11/4,11/16,
   32: # 12/7,12/15,01/06,01/11,01/12,01/14,2/8,
   33: # 03/07,05/31 Gerd Kortemeyer
   34: # 06/29,06/30,07/14,07/15,07/17,07/20,07/25,09/18 Gerd Kortemeyer
   35: # 12/05,12/13,12/29 Gerd Kortemeyer
   36: # YEAR=2001
   37: # 02/12 Gerd Kortemeyer
   38: # 03/24 Gerd Kortemeyer
   39: # 05/11,05/28,08/30 Gerd Kortemeyer
   40: # 11/26,11/27 Gerd Kortemeyer
   41: # 12/22 Gerd Kortemeyer
   42: # YEAR=2002
   43: # 01/20/02,02/05 Gerd Kortemeyer
   44: # 02/05 Guy Albertelli
   45: # 02/12 Gerd Kortemeyer
   46: # 02/19 Matthew Hall
   47: # 02/25 Gerd Kortemeyer
   48: # 01/xx/2003 Ron Fox.. Remove preforking.  This makes the general daemon
   49: #      logic simpler (and there were problems maintaining the preforked
   50: #      population).  Since the time averaged connection rate is close to zero
   51: #      because lonc's purpose is to maintain near continuous connnections,
   52: #      preforking is not really needed.
   53: # 08/xx/2003 Ron Fox:  Add management requests.  Management requests
   54: #      will be validated via a call to ValidateManager. At present, this
   55: #      is done by simple host verification.  In the future we can modify
   56: #      this function to do a certificate check.
   57: #      Management functions supported include:
   58: #       - pushing /home/httpd/lonTabs/hosts.tab
   59: #       - pushing /home/httpd/lonTabs/domain.tab
   60: # 09/08/2003 Ron Fox:  Told lond to take care of change logging so we
   61: #      don't have to remember it:
   62: # $Log: lond,v $
   63: # Revision 1.148  2003/09/29 10:09:18  foxr
   64: # Put in logic to reinit lond itself (except for apache reload).  I don't believe
   65: # this logic works correctly yet, however lond still does everything it used to doso I'll do the commit anyway.
   66: #
   67: # Revision 1.147  2003/09/23 11:23:31  foxr
   68: # Comlplete implementation of reinit functionality.  Must still implement
   69: # the actual initialization functionality, but the process can now
   70: # receive the request and either invoke the appropriate internal function or
   71: # signal the correct lonc.
   72: #
   73: # Revision 1.146  2003/09/16 10:28:14  foxr
   74: # ReinitProcess - decode the process selector and produce the associated pid
   75: # filename.  Note: While it is possible to test that valid process selectors are
   76: # handled properly I am not able to test that invalid process selectors produce
   77: # the appropriate error as lonManage also blocks the use of invalid process selectors.
   78: #
   79: # Revision 1.145  2003/09/16 10:13:20  foxr
   80: # Added ReinitProcess function to oversee the parsing and processing of the
   81: # reinit:<process> client request.
   82: #
   83: # Revision 1.144  2003/09/16 09:47:01  foxr
   84: # Added skeletal support for SIGUSR2 (update hosts.tab)
   85: #
   86: # Revision 1.143  2003/09/15 10:03:52  foxr
   87: # Completed and tested code for pushfile.
   88: #
   89: # Revision 1.142  2003/09/09 20:47:46  www
   90: # Permanently store chatroom entries in chatroom.log
   91: #
   92: # Revision 1.141  2003/09/08 10:32:07  foxr
   93: # Added PushFile sub This sub oversees the push of a new configuration table file
   94: # Currently supported files are:
   95: # - hosts.tab   (transaction pushfile:hosts:contents)
   96: # - domain.tab  (transaction pushfile:domain:contents)
   97: #
   98: 
   99: 
  100: use strict;
  101: use lib '/home/httpd/lib/perl/';
  102: use LONCAPA::Configuration;
  103: 
  104: use IO::Socket;
  105: use IO::File;
  106: #use Apache::File;
  107: use Symbol;
  108: use POSIX;
  109: use Crypt::IDEA;
  110: use LWP::UserAgent();
  111: use GDBM_File;
  112: use Authen::Krb4;
  113: use Authen::Krb5;
  114: use lib '/home/httpd/lib/perl/';
  115: use localauth;
  116: use File::Copy;
  117: 
  118: my $DEBUG = 0;		       # Non zero to enable debug log entries.
  119: 
  120: my $status='';
  121: my $lastlog='';
  122: 
  123: my $VERSION='$Revision: 1.148 $'; #' stupid emacs
  124: my $remoteVERSION;
  125: my $currenthostid;
  126: my $currentdomainid;
  127: 
  128: my $client;
  129: my $clientip;
  130: 
  131: my $server;
  132: my $thisserver;
  133: 
  134: my %hostid;
  135: my %hostdom;
  136: my %hostip;
  137: my %perlvar;			# Will have the apache conf defined perl vars.
  138: 
  139: #
  140: #  The array below are password error strings."
  141: #
  142: my $lastpwderror    = 13;		# Largest error number from lcpasswd.
  143: my @passwderrors = ("ok",
  144: 		   "lcpasswd must be run as user 'www'",
  145: 		   "lcpasswd got incorrect number of arguments",
  146: 		   "lcpasswd did not get the right nubmer of input text lines",
  147: 		   "lcpasswd too many simultaneous pwd changes in progress",
  148: 		   "lcpasswd User does not exist.",
  149: 		   "lcpasswd Incorrect current passwd",
  150: 		   "lcpasswd Unable to su to root.",
  151: 		   "lcpasswd Cannot set new passwd.",
  152: 		   "lcpasswd Username has invalid characters",
  153: 		   "lcpasswd Invalid characters in password",
  154: 		    "11", "12",
  155: 		    "lcpasswd Password mismatch");
  156: 
  157: 
  158: #  The array below are lcuseradd error strings.:
  159: 
  160: my $lastadderror = 13;
  161: my @adderrors    = ("ok",
  162: 		    "User ID mismatch, lcuseradd must run as user www",
  163: 		    "lcuseradd Incorrect number of command line parameters must be 3",
  164: 		    "lcuseradd Incorrect number of stdinput lines, must be 3",
  165: 		    "lcuseradd Too many other simultaneous pwd changes in progress",
  166: 		    "lcuseradd User does not exist",
  167: 		    "lcuseradd Unabel to mak ewww member of users's group",
  168: 		    "lcuseradd Unable to su to root",
  169: 		    "lcuseradd Unable to set password",
  170: 		    "lcuseradd Usrname has invbalid charcters",
  171: 		    "lcuseradd Password has an invalid character",
  172: 		    "lcuseradd User already exists",
  173: 		    "lcuseradd Could not add user.",
  174: 		    "lcuseradd Password mismatch");
  175: 
  176: 
  177: #
  178: #   GetCertificate: Given a transaction that requires a certificate,
  179: #   this function will extract the certificate from the transaction
  180: #   request.  Note that at this point, the only concept of a certificate
  181: #   is the hostname to which we are connected.
  182: #
  183: #   Parameter:
  184: #      request   - The request sent by our client (this parameterization may
  185: #                  need to change when we really use a certificate granting
  186: #                  authority.
  187: #
  188: sub GetCertificate {
  189:     my $request = shift;
  190: 
  191:     return $clientip;
  192: }
  193: 
  194: 
  195: #
  196: #  ValidManager: Determines if a given certificate represents a valid manager.
  197: #                in this primitive implementation, the 'certificate' is
  198: #                just the connecting loncapa client name.  This is checked
  199: #                against a valid client list in the configuration.
  200: #
  201: #                  
  202: sub ValidManager {
  203:     my $certificate = shift; 
  204: 
  205:     my $hostentry   = $hostid{$certificate};
  206:     if ($hostentry ne undef) {
  207: 	&logthis('<font color="yellow">Authenticating manager'.
  208: 		 " $hostentry</font>");
  209: 	return 1;
  210:     } else {
  211: 	&logthis('<font color="red"> Failed manager authentication '.
  212: 		 "$certificate </font>");
  213:     }
  214: }
  215: #
  216: #  CopyFile:  Called as part of the process of installing a 
  217: #             new configuration file.  This function copies an existing
  218: #             file to a backup file.
  219: # Parameters:
  220: #     oldfile  - Name of the file to backup.
  221: #     newfile  - Name of the backup file.
  222: # Return:
  223: #     0   - Failure (errno has failure reason).
  224: #     1   - Success.
  225: #
  226: sub CopyFile {
  227:     my $oldfile = shift;
  228:     my $newfile = shift;
  229: 
  230:     #  The file must exist:
  231: 
  232:     if(-e $oldfile) {
  233: 
  234: 	 # Read the old file.
  235: 
  236: 	my $oldfh = IO::File->new("< $oldfile");
  237: 	if(!$oldfh) {
  238: 	    return 0;
  239: 	}
  240: 	my @contents = <$oldfh>;  # Suck in the entire file.
  241: 
  242: 	# write the backup file:
  243: 
  244: 	my $newfh = IO::File->new("> $newfile");
  245: 	if(!(defined $newfh)){
  246: 	    return 0;
  247: 	}
  248: 	my $lines = scalar @contents;
  249: 	for (my $i =0; $i < $lines; $i++) {
  250: 	    print $newfh ($contents[$i]);
  251: 	}
  252: 
  253: 	$oldfh->close;
  254: 	$newfh->close;
  255: 
  256: 	chmod(0660, $newfile);
  257: 
  258: 	return 1;
  259: 	    
  260:     } else {
  261: 	return 0;
  262:     }
  263: }
  264: 
  265: #
  266: #   InstallFile: Called to install an administrative file:
  267: #       - The file is created with <name>.tmp
  268: #       - The <name>.tmp file is then mv'd to <name>
  269: #   This lugubrious procedure is done to ensure that we are never without
  270: #   a valid, even if dated, version of the file regardless of who crashes
  271: #   and when the crash occurs.
  272: #
  273: #  Parameters:
  274: #       Name of the file
  275: #       File Contents.
  276: #  Return:
  277: #      nonzero - success.
  278: #      0       - failure and $! has an errno.
  279: #
  280: sub InstallFile {
  281:     my $Filename = shift;
  282:     my $Contents = shift;
  283:     my $TempFile = $Filename.".tmp";
  284: 
  285:     #  Open the file for write:
  286: 
  287:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
  288:     if(!(defined $fh)) {
  289: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
  290: 	return 0;
  291:     }
  292:     #  write the contents of the file:
  293: 
  294:     print $fh ($Contents); 
  295:     $fh->close;			# In case we ever have a filesystem w. locking
  296: 
  297:     chmod(0660, $TempFile);
  298: 
  299:     # Now we can move install the file in position.
  300:     
  301:     move($TempFile, $Filename);
  302: 
  303:     return 1;
  304: }
  305: 
  306: #
  307: #   PushFile:  Called to do an administrative push of a file.
  308: #              - Ensure the file being pushed is one we support.
  309: #              - Backup the old file to <filename.saved>
  310: #              - Separate the contents of the new file out from the
  311: #                rest of the request.
  312: #              - Write the new file.
  313: #  Parameter:
  314: #     Request - The entire user request.  This consists of a : separated
  315: #               string pushfile:tablename:contents.
  316: #     NOTE:  The contents may have :'s in it as well making things a bit
  317: #            more interesting... but not much.
  318: #  Returns:
  319: #     String to send to client ("ok" or "refused" if bad file).
  320: #
  321: sub PushFile {
  322:     my $request = shift;    
  323:     my ($command, $filename, $contents) = split(":", $request, 3);
  324:     
  325:     #  At this point in time, pushes for only the following tables are
  326:     #  supported:
  327:     #   hosts.tab  ($filename eq host).
  328:     #   domain.tab ($filename eq domain).
  329:     # Construct the destination filename or reject the request.
  330:     #
  331:     # lonManage is supposed to ensure this, however this session could be
  332:     # part of some elaborate spoof that managed somehow to authenticate.
  333:     #
  334: 
  335:     my $tablefile = $perlvar{'lonTabDir'}.'/'; # need to precede with dir.
  336:     if ($filename eq "host") {
  337: 	$tablefile .= "hosts.tab";
  338:     } elsif ($filename eq "domain") {
  339: 	$tablefile .= "domain.tab";
  340:     } else {
  341: 	return "refused";
  342:     }
  343:     #
  344:     # >copy< the old table to the backup table
  345:     #        don't rename in case system crashes/reboots etc. in the time
  346:     #        window between a rename and write.
  347:     #
  348:     my $backupfile = $tablefile;
  349:     $backupfile    =~ s/\.tab$/.old/;
  350:     if(!CopyFile($tablefile, $backupfile)) {
  351: 	&logthis('<font color="green"> CopyFile from '.$tablefile." to ".$backupfile." failed </font>");
  352: 	return "error:$!";
  353:     }
  354:     &logthis('<font color="green"> Pushfile: backed up '
  355: 	    .$tablefile." to $backupfile</font>");
  356:     
  357:     #  Install the new file:
  358: 
  359:     if(!InstallFile($tablefile, $contents)) {
  360: 	&logthis('<font color="red"> Pushfile: unable to install '
  361: 	 .$tablefile." $! </font>");
  362: 	return "error:$!";
  363:     }
  364:     else {
  365: 	&logthis('<font color="green"> Installed new '.$tablefile
  366: 		 ."</font>");
  367: 
  368:     }
  369: 
  370: 
  371:     #  Indicate success:
  372:  
  373:     return "ok";
  374: 
  375: }
  376: 
  377: #
  378: #  Called to re-init either lonc or lond.
  379: #
  380: #  Parameters:
  381: #    request   - The full request by the client.  This is of the form
  382: #                reinit:<process>  
  383: #                where <process> is allowed to be either of 
  384: #                lonc or lond
  385: #
  386: #  Returns:
  387: #     The string to be sent back to the client either:
  388: #   ok         - Everything worked just fine.
  389: #   error:why  - There was a failure and why describes the reason.
  390: #
  391: #
  392: sub ReinitProcess {
  393:     my $request = shift;
  394: 
  395: 
  396:     # separate the request (reinit) from the process identifier and
  397:     # validate it producing the name of the .pid file for the process.
  398:     #
  399:     #
  400:     my ($junk, $process) = split(":", $request);
  401:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
  402:     if($process eq 'lonc') {
  403: 	$processpidfile = $processpidfile."lonc.pid";
  404: 	if (!open(PIDFILE, "< $processpidfile")) {
  405: 	    return "error:Open failed for $processpidfile";
  406: 	}
  407: 	my $loncpid = <PIDFILE>;
  408: 	close(PIDFILE);
  409: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
  410: 		."</font>");
  411: 	kill("USR2", $loncpid);
  412:     } elsif ($process eq 'lond') {
  413: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
  414: 	&UpdateHosts;			# Lond is us!!
  415:     } else {
  416: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
  417: 		 ."</font>");
  418: 	return "error:Invalid process identifier $process";
  419:     }
  420:     return 'ok';
  421: }
  422: 
  423: #
  424: #  Convert an error return code from lcpasswd to a string value.
  425: #
  426: sub lcpasswdstrerror {
  427:     my $ErrorCode = shift;
  428:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
  429: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
  430:     } else {
  431: 	return $passwderrors[$ErrorCode];
  432:     }
  433: }
  434: 
  435: #
  436: # Convert an error return code from lcuseradd to a string value:
  437: #
  438: sub lcuseraddstrerror {
  439:     my $ErrorCode = shift;
  440:     if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
  441: 	return "lcuseradd - Unrecognized error code: ".$ErrorCode;
  442:     } else {
  443: 	return $adderrors[$ErrorCode];
  444:     }
  445: }
  446: 
  447: # grabs exception and records it to log before exiting
  448: sub catchexception {
  449:     my ($error)=@_;
  450:     $SIG{'QUIT'}='DEFAULT';
  451:     $SIG{__DIE__}='DEFAULT';
  452:     &logthis("<font color=red>CRITICAL: "
  453:      ."ABNORMAL EXIT. Child $$ for server $thisserver died through "
  454:      ."a crash with this error msg->[$error]</font>");
  455:     &logthis('Famous last words: '.$status.' - '.$lastlog);
  456:     if ($client) { print $client "error: $error\n"; }
  457:     $server->close();
  458:     die($error);
  459: }
  460: 
  461: sub timeout {
  462:     &logthis("<font color=ref>CRITICAL: TIME OUT ".$$."</font>");
  463:     &catchexception('Timeout');
  464: }
  465: # -------------------------------- Set signal handlers to record abnormal exits
  466: 
  467: $SIG{'QUIT'}=\&catchexception;
  468: $SIG{__DIE__}=\&catchexception;
  469: 
  470: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
  471: &status("Read loncapa.conf and loncapa_apache.conf");
  472: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
  473: %perlvar=%{$perlvarref};
  474: undef $perlvarref;
  475: 
  476: # ----------------------------- Make sure this process is running from user=www
  477: my $wwwid=getpwnam('www');
  478: if ($wwwid!=$<) {
  479:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
  480:    my $subj="LON: $currenthostid User ID mismatch";
  481:    system("echo 'User ID mismatch.  lond must be run as user www.' |\
  482:  mailto $emailto -s '$subj' > /dev/null");
  483:    exit 1;
  484: }
  485: 
  486: # --------------------------------------------- Check if other instance running
  487: 
  488: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
  489: 
  490: if (-e $pidfile) {
  491:    my $lfh=IO::File->new("$pidfile");
  492:    my $pide=<$lfh>;
  493:    chomp($pide);
  494:    if (kill 0 => $pide) { die "already running"; }
  495: }
  496: 
  497: # ------------------------------------------------------------- Read hosts file
  498: 
  499: 
  500: 
  501: # establish SERVER socket, bind and listen.
  502: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
  503:                                 Type      => SOCK_STREAM,
  504:                                 Proto     => 'tcp',
  505:                                 Reuse     => 1,
  506:                                 Listen    => 10 )
  507:   or die "making socket: $@\n";
  508: 
  509: # --------------------------------------------------------- Do global variables
  510: 
  511: # global variables
  512: 
  513: my %children               = ();       # keys are current child process IDs
  514: my $children               = 0;        # current number of children
  515: 
  516: sub REAPER {                        # takes care of dead children
  517:     $SIG{CHLD} = \&REAPER;
  518:     my $pid = wait;
  519:     if (defined($children{$pid})) {
  520: 	&logthis("Child $pid died");
  521: 	$children --;
  522: 	delete $children{$pid};
  523:     } else {
  524: 	&logthis("Unknown Child $pid died");
  525:     }
  526: }
  527: 
  528: sub HUNTSMAN {                      # signal handler for SIGINT
  529:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
  530:     kill 'INT' => keys %children;
  531:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
  532:     my $execdir=$perlvar{'lonDaemons'};
  533:     unlink("$execdir/logs/lond.pid");
  534:     &logthis("<font color=red>CRITICAL: Shutting down</font>");
  535:     exit;                           # clean up with dignity
  536: }
  537: 
  538: sub HUPSMAN {                      # signal handler for SIGHUP
  539:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
  540:     kill 'INT' => keys %children;
  541:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
  542:     &logthis("<font color=red>CRITICAL: Restarting</font>");
  543:     my $execdir=$perlvar{'lonDaemons'};
  544:     unlink("$execdir/logs/lond.pid");
  545:     exec("$execdir/lond");         # here we go again
  546: }
  547: 
  548: #
  549: #    Kill off hashes that describe the host table prior to re-reading it.
  550: #    Hashes affected are:
  551: #       %hostid, %hostdom %hostip
  552: #
  553: sub KillHostHashes {
  554:     foreach my $key (keys %hostid) {
  555: 	delete $hostid{$key};
  556:     }
  557:     foreach my $key (keys %hostdom) {
  558: 	delete $hostdom{$key};
  559:     }
  560:     foreach my $key (keys %hostip) {
  561: 	delete $hostip{$key};
  562:     }
  563: }
  564: #
  565: #   Read in the host table from file and distribute it into the various hashes:
  566: #
  567: #    - %hostid  -  Indexed by IP, the loncapa hostname.
  568: #    - %hostdom -  Indexed by  loncapa hostname, the domain.
  569: #    - %hostip  -  Indexed by hostid, the Ip address of the host.
  570: sub ReadHostTable {
  571: 
  572:     open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
  573:     
  574:     while (my $configline=<CONFIG>) {
  575: 	my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
  576: 	chomp($ip); $ip=~s/\D+$//;
  577: 	$hostid{$ip}=$id;
  578: 	$hostdom{$id}=$domain;
  579: 	$hostip{$id}=$ip;
  580: 	if ($id eq $perlvar{'lonHostID'}) { $thisserver=$name; }
  581:     }
  582:     close(CONFIG);
  583: }
  584: #
  585: #  Reload the Apache daemon's state.
  586: #
  587: sub ReloadApache {
  588: }
  589: 
  590: #
  591: #   Called in response to a USR2 signal.
  592: #   - Reread hosts.tab
  593: #   - All children connected to hosts that were removed from hosts.tab
  594: #     are killed via SIGINT
  595: #   - All children connected to previously existing hosts are sent SIGUSR1
  596: #   - Our internal hosts hash is updated to reflect the new contents of
  597: #     hosts.tab causing connections from hosts added to hosts.tab to
  598: #     now be honored.
  599: #
  600: sub UpdateHosts {
  601:     logthis('<font color="blue"> Updating connections </font>');
  602:     #
  603:     #  The %children hash has the set of IP's we currently have children
  604:     #  on.  These need to be matched against records in the hosts.tab
  605:     #  Any ip's no longer in the table get killed off they correspond to
  606:     #  either dropped or changed hosts.  Note that the re-read of the table
  607:     #  will take care of new and changed hosts as connections come into being.
  608: 
  609: 
  610:     KillHostHashes;
  611:     ReadHostTable;
  612: 
  613:     foreach my $child (keys %children) {
  614: 	my $childip = $children{$child};
  615: 	if(!$hostid{$childip}) {
  616: 	    kill('INT', $child);
  617: 	}
  618:     }
  619:     ReloadApache;
  620: }
  621: 
  622: 
  623: sub checkchildren {
  624:     &initnewstatus();
  625:     &logstatus();
  626:     &logthis('Going to check on the children');
  627:     my $docdir=$perlvar{'lonDocRoot'};
  628:     foreach (sort keys %children) {
  629: 	sleep 1;
  630:         unless (kill 'USR1' => $_) {
  631: 	    &logthis ('Child '.$_.' is dead');
  632:             &logstatus($$.' is dead');
  633:         } 
  634:     }
  635:     sleep 5;
  636:     $SIG{ALRM} = sub { die "timeout" };
  637:     $SIG{__DIE__} = 'DEFAULT';
  638:     foreach (sort keys %children) {
  639:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
  640:           eval {
  641:             alarm(300);
  642: 	    &logthis('Child '.$_.' did not respond');
  643: 	    kill 9 => $_;
  644: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
  645: 	    #$subj="LON: $currenthostid killed lond process $_";
  646: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
  647: 	    #$execdir=$perlvar{'lonDaemons'};
  648: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
  649: 	    alarm(0);
  650: 	  }
  651:         }
  652:     }
  653:     $SIG{ALRM} = 'DEFAULT';
  654:     $SIG{__DIE__} = \&cathcexception;
  655: }
  656: 
  657: # --------------------------------------------------------------------- Logging
  658: 
  659: sub logthis {
  660:     my $message=shift;
  661:     my $execdir=$perlvar{'lonDaemons'};
  662:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
  663:     my $now=time;
  664:     my $local=localtime($now);
  665:     $lastlog=$local.': '.$message;
  666:     print $fh "$local ($$): $message\n";
  667: }
  668: 
  669: # ------------------------- Conditional log if $DEBUG true.
  670: sub Debug {
  671:     my $message = shift;
  672:     if($DEBUG) {
  673: 	&logthis($message);
  674:     }
  675: }
  676: # ------------------------------------------------------------------ Log status
  677: 
  678: sub logstatus {
  679:     my $docdir=$perlvar{'lonDocRoot'};
  680:     {
  681:     my $fh=IO::File->new(">>$docdir/lon-status/londstatus.txt");
  682:     print $fh $$."\t".$currenthostid."\t".$status."\t".$lastlog."\n";
  683:     $fh->close();
  684:     }
  685:     {
  686: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
  687:         print $fh $status."\n".$lastlog."\n".time;
  688:         $fh->close();
  689:     }
  690: }
  691: 
  692: sub initnewstatus {
  693:     my $docdir=$perlvar{'lonDocRoot'};
  694:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
  695:     my $now=time;
  696:     my $local=localtime($now);
  697:     print $fh "LOND status $local - parent $$\n\n";
  698:     opendir(DIR,"$docdir/lon-status/londchld");
  699:     while (my $filename=readdir(DIR)) {
  700:         unlink("$docdir/lon-status/londchld/$filename");
  701:     }
  702:     closedir(DIR);
  703: }
  704: 
  705: # -------------------------------------------------------------- Status setting
  706: 
  707: sub status {
  708:     my $what=shift;
  709:     my $now=time;
  710:     my $local=localtime($now);
  711:     $status=$local.': '.$what;
  712:     $0='lond: '.$what.' '.$local;
  713: }
  714: 
  715: # -------------------------------------------------------- Escape Special Chars
  716: 
  717: sub escape {
  718:     my $str=shift;
  719:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
  720:     return $str;
  721: }
  722: 
  723: # ----------------------------------------------------- Un-Escape Special Chars
  724: 
  725: sub unescape {
  726:     my $str=shift;
  727:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  728:     return $str;
  729: }
  730: 
  731: # ----------------------------------------------------------- Send USR1 to lonc
  732: 
  733: sub reconlonc {
  734:     my $peerfile=shift;
  735:     &logthis("Trying to reconnect for $peerfile");
  736:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  737:     if (my $fh=IO::File->new("$loncfile")) {
  738: 	my $loncpid=<$fh>;
  739:         chomp($loncpid);
  740:         if (kill 0 => $loncpid) {
  741: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  742:             kill USR1 => $loncpid;
  743:         } else {
  744: 	    &logthis(
  745:               "<font color=red>CRITICAL: "
  746:              ."lonc at pid $loncpid not responding, giving up</font>");
  747:         }
  748:     } else {
  749:       &logthis('<font color=red>CRITICAL: lonc not running, giving up</font>');
  750:     }
  751: }
  752: 
  753: # -------------------------------------------------- Non-critical communication
  754: 
  755: sub subreply {
  756:     my ($cmd,$server)=@_;
  757:     my $peerfile="$perlvar{'lonSockDir'}/$server";
  758:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  759:                                       Type    => SOCK_STREAM,
  760:                                       Timeout => 10)
  761:        or return "con_lost";
  762:     print $sclient "$cmd\n";
  763:     my $answer=<$sclient>;
  764:     chomp($answer);
  765:     if (!$answer) { $answer="con_lost"; }
  766:     return $answer;
  767: }
  768: 
  769: sub reply {
  770:   my ($cmd,$server)=@_;
  771:   my $answer;
  772:   if ($server ne $currenthostid) { 
  773:     $answer=subreply($cmd,$server);
  774:     if ($answer eq 'con_lost') {
  775: 	$answer=subreply("ping",$server);
  776:         if ($answer ne $server) {
  777: 	    &logthis("sub reply: answer != server answer is $answer, server is $server");
  778:            &reconlonc("$perlvar{'lonSockDir'}/$server");
  779:         }
  780:         $answer=subreply($cmd,$server);
  781:     }
  782:   } else {
  783:     $answer='self_reply';
  784:   } 
  785:   return $answer;
  786: }
  787: 
  788: # -------------------------------------------------------------- Talk to lonsql
  789: 
  790: sub sqlreply {
  791:     my ($cmd)=@_;
  792:     my $answer=subsqlreply($cmd);
  793:     if ($answer eq 'con_lost') { $answer=subsqlreply($cmd); }
  794:     return $answer;
  795: }
  796: 
  797: sub subsqlreply {
  798:     my ($cmd)=@_;
  799:     my $unixsock="mysqlsock";
  800:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
  801:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  802:                                       Type    => SOCK_STREAM,
  803:                                       Timeout => 10)
  804:        or return "con_lost";
  805:     print $sclient "$cmd\n";
  806:     my $answer=<$sclient>;
  807:     chomp($answer);
  808:     if (!$answer) { $answer="con_lost"; }
  809:     return $answer;
  810: }
  811: 
  812: # -------------------------------------------- Return path to profile directory
  813: 
  814: sub propath {
  815:     my ($udom,$uname)=@_;
  816:     $udom=~s/\W//g;
  817:     $uname=~s/\W//g;
  818:     my $subdir=$uname.'__';
  819:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
  820:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
  821:     return $proname;
  822: } 
  823: 
  824: # --------------------------------------- Is this the home server of an author?
  825: 
  826: sub ishome {
  827:     my $author=shift;
  828:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  829:     my ($udom,$uname)=split(/\//,$author);
  830:     my $proname=propath($udom,$uname);
  831:     if (-e $proname) {
  832: 	return 'owner';
  833:     } else {
  834:         return 'not_owner';
  835:     }
  836: }
  837: 
  838: # ======================================================= Continue main program
  839: # ---------------------------------------------------- Fork once and dissociate
  840: 
  841: my $fpid=fork;
  842: exit if $fpid;
  843: die "Couldn't fork: $!" unless defined ($fpid);
  844: 
  845: POSIX::setsid() or die "Can't start new session: $!";
  846: 
  847: # ------------------------------------------------------- Write our PID on disk
  848: 
  849: my $execdir=$perlvar{'lonDaemons'};
  850: open (PIDSAVE,">$execdir/logs/lond.pid");
  851: print PIDSAVE "$$\n";
  852: close(PIDSAVE);
  853: &logthis("<font color=red>CRITICAL: ---------- Starting ----------</font>");
  854: &status('Starting');
  855: 
  856: 
  857: 
  858: # ----------------------------------------------------- Install signal handlers
  859: 
  860: 
  861: $SIG{CHLD} = \&REAPER;
  862: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
  863: $SIG{HUP}  = \&HUPSMAN;
  864: $SIG{USR1} = \&checkchildren;
  865: $SIG{USR2} = \&UpdateHosts;
  866: 
  867: #  Read the host hashes:
  868: 
  869: ReadHostTable;
  870: 
  871: # --------------------------------------------------------------
  872: #   Accept connections.  When a connection comes in, it is validated
  873: #   and if good, a child process is created to process transactions
  874: #   along the connection.
  875: 
  876: while (1) {
  877:     $client = $server->accept() or next;
  878:     make_new_child($client);
  879: }
  880: 
  881: sub make_new_child {
  882:     my $pid;
  883:     my $cipher;
  884:     my $sigset;
  885: 
  886:     $client = shift;
  887:     &logthis("Attempting to start child");    
  888:     # block signal for fork
  889:     $sigset = POSIX::SigSet->new(SIGINT);
  890:     sigprocmask(SIG_BLOCK, $sigset)
  891:         or die "Can't block SIGINT for fork: $!\n";
  892: 
  893:     die "fork: $!" unless defined ($pid = fork);
  894: 
  895:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
  896: 	                               # connection liveness.
  897: 
  898:     #
  899:     #  Figure out who we're talking to so we can record the peer in 
  900:     #  the pid hash.
  901:     #
  902:     my $caller = getpeername($client);
  903:     my ($port,$iaddr)=unpack_sockaddr_in($caller);
  904:     $clientip=inet_ntoa($iaddr);
  905:     
  906:     if ($pid) {
  907:         # Parent records the child's birth and returns.
  908:         sigprocmask(SIG_UNBLOCK, $sigset)
  909:             or die "Can't unblock SIGINT for fork: $!\n";
  910:         $children{$pid} = $clientip;
  911:         $children++;
  912:         &status('Started child '.$pid);
  913:         return;
  914:     } else {
  915:         # Child can *not* return from this subroutine.
  916:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
  917:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
  918:                                 #don't get intercepted
  919:         $SIG{USR1}= \&logstatus;
  920:         $SIG{ALRM}= \&timeout;
  921:         $lastlog='Forked ';
  922:         $status='Forked';
  923: 
  924:         # unblock signals
  925:         sigprocmask(SIG_UNBLOCK, $sigset)
  926:             or die "Can't unblock SIGINT for fork: $!\n";
  927: 
  928:         my $tmpsnum=0;
  929: #---------------------------------------------------- kerberos 5 initialization
  930:         &Authen::Krb5::init_context();
  931:         &Authen::Krb5::init_ets();
  932: 
  933:             &status('Accepted connection');
  934: # =============================================================================
  935:             # do something with the connection
  936: # -----------------------------------------------------------------------------
  937: 	# see if we know client and check for spoof IP by challenge
  938: 
  939:             my $clientrec=($hostid{$clientip} ne undef);
  940:             &logthis(
  941: "<font color=yellow>INFO: Connection, $clientip ($hostid{$clientip})</font>"
  942:             );
  943:             &status("Connecting $clientip ($hostid{$clientip})"); 
  944:             my $clientok;
  945:             if ($clientrec) {
  946: 	      &status("Waiting for init from $clientip ($hostid{$clientip})");
  947: 	      my $remotereq=<$client>;
  948:               $remotereq=~s/[^\w:]//g;
  949:               if ($remotereq =~ /^init/) {
  950: 		  &sethost("sethost:$perlvar{'lonHostID'}");
  951: 		  my $challenge="$$".time;
  952:                   print $client "$challenge\n";
  953:                   &status(
  954:            "Waiting for challenge reply from $clientip ($hostid{$clientip})"); 
  955:                   $remotereq=<$client>;
  956:                   $remotereq=~s/\W//g;
  957:                   if ($challenge eq $remotereq) {
  958: 		      $clientok=1;
  959:                       print $client "ok\n";
  960:                   } else {
  961: 		      &logthis(
  962:  "<font color=blue>WARNING: $clientip did not reply challenge</font>");
  963:                       &status('No challenge reply '.$clientip);
  964:                   }
  965:               } else {
  966: 		  &logthis(
  967:                     "<font color=blue>WARNING: "
  968:                    ."$clientip failed to initialize: >$remotereq< </font>");
  969:                   &status('No init '.$clientip);
  970:               }
  971: 	    } else {
  972:               &logthis(
  973:  "<font color=blue>WARNING: Unknown client $clientip</font>");
  974:               &status('Hung up on '.$clientip);
  975:             }
  976:             if ($clientok) {
  977: # ---------------- New known client connecting, could mean machine online again
  978: 
  979: 		foreach my $id (keys(%hostip)) {
  980: 		    if ($hostip{$id} ne $clientip ||
  981: 		       $hostip{$currenthostid} eq $clientip) {
  982: 			# no need to try to do recon's to myself
  983: 			next;
  984: 		    }
  985: 		    &reconlonc("$perlvar{'lonSockDir'}/$id");
  986: 		}
  987: 		&logthis("<font color=green>Established connection: $hostid{$clientip}</font>");
  988:               &status('Will listen to '.$hostid{$clientip});
  989: # ------------------------------------------------------------ Process requests
  990:               while (my $userinput=<$client>) {
  991:                 chomp($userinput);
  992: 		Debug("Request = $userinput\n");
  993:                 &status('Processing '.$hostid{$clientip}.': '.$userinput);
  994:                 my $wasenc=0;
  995:                 alarm(120);
  996: # ------------------------------------------------------------ See if encrypted
  997: 		if ($userinput =~ /^enc/) {
  998: 		  if ($cipher) {
  999:                     my ($cmd,$cmdlength,$encinput)=split(/:/,$userinput);
 1000: 		    $userinput='';
 1001:                     for (my $encidx=0;$encidx<length($encinput);$encidx+=16) {
 1002:                        $userinput.=
 1003: 			   $cipher->decrypt(
 1004:                             pack("H16",substr($encinput,$encidx,16))
 1005:                            );
 1006: 		    }
 1007: 		    $userinput=substr($userinput,0,$cmdlength);
 1008:                     $wasenc=1;
 1009: 		}
 1010: 	      }
 1011: 	  
 1012: # ------------------------------------------------------------- Normal commands
 1013: # ------------------------------------------------------------------------ ping
 1014: 		   if ($userinput =~ /^ping/) {
 1015:                        print $client "$currenthostid\n";
 1016: # ------------------------------------------------------------------------ pong
 1017: 		   }elsif ($userinput =~ /^pong/) {
 1018:                        my $reply=&reply("ping",$hostid{$clientip});
 1019:                        print $client "$currenthostid:$reply\n"; 
 1020: # ------------------------------------------------------------------------ ekey
 1021: 		   } elsif ($userinput =~ /^ekey/) {
 1022:                        my $buildkey=time.$$.int(rand 100000);
 1023:                        $buildkey=~tr/1-6/A-F/;
 1024:                        $buildkey=int(rand 100000).$buildkey.int(rand 100000);
 1025:                        my $key=$currenthostid.$hostid{$clientip};
 1026:                        $key=~tr/a-z/A-Z/;
 1027:                        $key=~tr/G-P/0-9/;
 1028:                        $key=~tr/Q-Z/0-9/;
 1029:                        $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
 1030:                        $key=substr($key,0,32);
 1031:                        my $cipherkey=pack("H32",$key);
 1032:                        $cipher=new IDEA $cipherkey;
 1033:                        print $client "$buildkey\n"; 
 1034: # ------------------------------------------------------------------------ load
 1035: 		   } elsif ($userinput =~ /^load/) {
 1036:                        my $loadavg;
 1037:                        {
 1038:                           my $loadfile=IO::File->new('/proc/loadavg');
 1039:                           $loadavg=<$loadfile>;
 1040:                        }
 1041:                        $loadavg =~ s/\s.*//g;
 1042: 		       my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
 1043: 		       print $client "$loadpercent\n";
 1044: # -------------------------------------------------------------------- userload
 1045: 		   } elsif ($userinput =~ /^userload/) {
 1046: 		       my $userloadpercent=&userload();
 1047: 		       print $client "$userloadpercent\n";
 1048: 
 1049: #
 1050: #        Transactions requiring encryption:
 1051: #
 1052: # ----------------------------------------------------------------- currentauth
 1053: 		   } elsif ($userinput =~ /^currentauth/) {
 1054: 		     if ($wasenc==1) {
 1055:                        my ($cmd,$udom,$uname)=split(/:/,$userinput);
 1056: 		       my $result = GetAuthType($udom, $uname);
 1057: 		       if($result eq "nouser") {
 1058: 			   print $client "unknown_user\n";
 1059: 		       }
 1060: 		       else {
 1061: 			   print $client "$result\n"
 1062: 		       }
 1063: 		     } else {
 1064: 		       print $client "refused\n";
 1065: 		     }
 1066: #--------------------------------------------------------------------- pushfile
 1067: 		   } elsif($userinput =~ /^pushfile/) { 
 1068: 		       if($wasenc == 1) {
 1069: 			   my $cert = GetCertificate($userinput);
 1070: 			   if(ValidManager($cert)) {
 1071: 			       my $reply = PushFile($userinput);
 1072: 			       print $client "$reply\n";
 1073: 			   } else {
 1074: 			       print $client "refused\n";
 1075: 			   } 
 1076: 		       } else {
 1077: 			   print $client "refused\n";
 1078: 		       }
 1079: #--------------------------------------------------------------------- reinit
 1080: 		   } elsif($userinput =~ /^reinit/) {
 1081: 		       if ($wasenc == 1) {
 1082: 			   my $cert = GetCertificate($userinput);
 1083: 			   if(ValidManager($cert)) {
 1084: 			       chomp($userinput);
 1085: 			       my $reply = ReinitProcess($userinput);
 1086: 			       print $client  "$reply\n";
 1087: 			   } else {
 1088: 			       print $client "refused\n";
 1089: 			   }
 1090: 		       } else {
 1091: 			   print $client "refused\n";
 1092: 		       }
 1093: # ------------------------------------------------------------------------ auth
 1094:                    } elsif ($userinput =~ /^auth/) {
 1095: 		     if ($wasenc==1) {
 1096:                        my ($cmd,$udom,$uname,$upass)=split(/:/,$userinput);
 1097:                        chomp($upass);
 1098:                        $upass=unescape($upass);
 1099:                        my $proname=propath($udom,$uname);
 1100:                        my $passfilename="$proname/passwd";
 1101:                        if (-e $passfilename) {
 1102:                           my $pf = IO::File->new($passfilename);
 1103:                           my $realpasswd=<$pf>;
 1104:                           chomp($realpasswd);
 1105:                           my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
 1106:                           my $pwdcorrect=0;
 1107:                           if ($howpwd eq 'internal') {
 1108: 			      &Debug("Internal auth");
 1109: 			      $pwdcorrect=
 1110: 				  (crypt($upass,$contentpwd) eq $contentpwd);
 1111:                           } elsif ($howpwd eq 'unix') {
 1112: 			      &Debug("Unix auth");
 1113:                               if((getpwnam($uname))[1] eq "") { #no such user!
 1114: 				  $pwdcorrect = 0;
 1115: 			      } else {
 1116: 				  $contentpwd=(getpwnam($uname))[1];
 1117: 				  my $pwauth_path="/usr/local/sbin/pwauth";
 1118: 				  unless ($contentpwd eq 'x') {
 1119: 				      $pwdcorrect=
 1120: 					  (crypt($upass,$contentpwd) eq 
 1121: 					   $contentpwd);
 1122: 				  }
 1123: 		  
 1124: 			      elsif (-e $pwauth_path) {
 1125: 				  open PWAUTH, "|$pwauth_path" or
 1126: 				      die "Cannot invoke authentication";
 1127: 				  print PWAUTH "$uname\n$upass\n";
 1128: 				  close PWAUTH;
 1129: 				  $pwdcorrect=!$?;
 1130: 			      }
 1131: 			      }
 1132:                           } elsif ($howpwd eq 'krb4') {
 1133:                               my $null=pack("C",0);
 1134:                               unless ($upass=~/$null/) {
 1135:                                   my $krb4_error = &Authen::Krb4::get_pw_in_tkt
 1136:                                       ($uname,"",$contentpwd,'krbtgt',
 1137:                                        $contentpwd,1,$upass);
 1138:                                   if (!$krb4_error) {
 1139:                                       $pwdcorrect = 1;
 1140:                                   } else { 
 1141:                                       $pwdcorrect=0; 
 1142:                                       # log error if it is not a bad password
 1143:                                       if ($krb4_error != 62) {
 1144:        &logthis('krb4:'.$uname.','.$contentpwd.','.
 1145:                 &Authen::Krb4::get_err_txt($Authen::Krb4::error));
 1146:                                       }
 1147:                                   }
 1148:                               }
 1149:                           } elsif ($howpwd eq 'krb5') {
 1150: 			      my $null=pack("C",0);
 1151: 			      unless ($upass=~/$null/) {
 1152: 				  my $krbclient=&Authen::Krb5::parse_name($uname.'@'.$contentpwd);
 1153: 				  my $krbservice="krbtgt/".$contentpwd."\@".$contentpwd;
 1154: 				  my $krbserver=&Authen::Krb5::parse_name($krbservice);
 1155: 				  my $credentials=&Authen::Krb5::cc_default();
 1156: 				  $credentials->initialize($krbclient);
 1157: 				  my $krbreturn = 
 1158: 				    &Authen::Krb5::get_in_tkt_with_password(
 1159: 				     $krbclient,$krbserver,$upass,$credentials);
 1160: #				  unless ($krbreturn) {
 1161: #				      &logthis("Krb5 Error: ".
 1162: #					       &Authen::Krb5::error());
 1163: #				  }
 1164: 				  $pwdcorrect = ($krbreturn == 1);
 1165: 			   } else { $pwdcorrect=0; }
 1166:                           } elsif ($howpwd eq 'localauth') {
 1167: 			    $pwdcorrect=&localauth::localauth($uname,$upass,
 1168: 							      $contentpwd);
 1169: 			  }
 1170:                           if ($pwdcorrect) {
 1171:                              print $client "authorized\n";
 1172:                           } else {
 1173:                              print $client "non_authorized\n";
 1174:                           }  
 1175: 		       } else {
 1176:                           print $client "unknown_user\n";
 1177:                        }
 1178: 		     } else {
 1179: 		       print $client "refused\n";
 1180: 		     }
 1181: # ---------------------------------------------------------------------- passwd
 1182:                    } elsif ($userinput =~ /^passwd/) {
 1183: 		     if ($wasenc==1) {
 1184:                        my 
 1185:                        ($cmd,$udom,$uname,$upass,$npass)=split(/:/,$userinput);
 1186:                        chomp($npass);
 1187:                        $upass=&unescape($upass);
 1188:                        $npass=&unescape($npass);
 1189: 		       &Debug("Trying to change password for $uname");
 1190: 		       my $proname=propath($udom,$uname);
 1191:                        my $passfilename="$proname/passwd";
 1192:                        if (-e $passfilename) {
 1193: 			   my $realpasswd;
 1194:                           { my $pf = IO::File->new($passfilename);
 1195: 			    $realpasswd=<$pf>; }
 1196:                           chomp($realpasswd);
 1197:                           my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
 1198:                           if ($howpwd eq 'internal') {
 1199: 			   &Debug("internal auth");
 1200: 			   if (crypt($upass,$contentpwd) eq $contentpwd) {
 1201: 			     my $salt=time;
 1202:                              $salt=substr($salt,6,2);
 1203: 			     my $ncpass=crypt($npass,$salt);
 1204:                              {
 1205: 				 my $pf;
 1206: 				 if ($pf = IO::File->new(">$passfilename")) {
 1207: 				     print $pf "internal:$ncpass\n";
 1208: 				     &logthis("Result of password change for $uname: pwchange_success");
 1209: 				     print $client "ok\n";
 1210: 				 } else {
 1211: 				     &logthis("Unable to open $uname passwd to change password");
 1212: 				     print $client "non_authorized\n";
 1213: 				 }
 1214: 			     }             
 1215: 			     
 1216:                            } else {
 1217:                              print $client "non_authorized\n";
 1218:                            }
 1219:                           } elsif ($howpwd eq 'unix') {
 1220: 			      # Unix means we have to access /etc/password
 1221: 			      # one way or another.
 1222: 			      # First: Make sure the current password is
 1223: 			      #        correct
 1224: 			      &Debug("auth is unix");
 1225: 			      $contentpwd=(getpwnam($uname))[1];
 1226: 			      my $pwdcorrect = "0";
 1227: 			      my $pwauth_path="/usr/local/sbin/pwauth";
 1228: 			      unless ($contentpwd eq 'x') {
 1229: 				  $pwdcorrect=
 1230:                                     (crypt($upass,$contentpwd) eq $contentpwd);
 1231: 			      } elsif (-e $pwauth_path) {
 1232: 				  open PWAUTH, "|$pwauth_path" or
 1233: 				      die "Cannot invoke authentication";
 1234: 				  print PWAUTH "$uname\n$upass\n";
 1235: 				  close PWAUTH;
 1236: 				  &Debug("exited pwauth with $? ($uname,$upass) ");
 1237: 				  $pwdcorrect=($? == 0);
 1238: 			      }
 1239: 			     if ($pwdcorrect) {
 1240: 				 my $execdir=$perlvar{'lonDaemons'};
 1241: 				 &Debug("Opening lcpasswd pipeline");
 1242: 				 my $pf = IO::File->new("|$execdir/lcpasswd > $perlvar{'lonDaemons'}/logs/lcpasswd.log");
 1243: 				 print $pf "$uname\n$npass\n$npass\n";
 1244: 				 close $pf;
 1245: 				 my $err = $?;
 1246: 				 my $result = ($err>0 ? 'pwchange_failure' 
 1247: 					       : 'ok');
 1248: 				 &logthis("Result of password change for $uname: ".
 1249: 					  &lcpasswdstrerror($?));
 1250: 				 print $client "$result\n";
 1251: 			     } else {
 1252: 				 print $client "non_authorized\n";
 1253: 			     }
 1254: 			  } else {
 1255:                             print $client "auth_mode_error\n";
 1256:                           }  
 1257: 		       } else {
 1258:                           print $client "unknown_user\n";
 1259:                        }
 1260: 		     } else {
 1261: 		       print $client "refused\n";
 1262: 		     }
 1263: # -------------------------------------------------------------------- makeuser
 1264:                    } elsif ($userinput =~ /^makeuser/) {
 1265: 		     &Debug("Make user received");
 1266:     	             my $oldumask=umask(0077);
 1267: 		     if ($wasenc==1) {
 1268:                        my 
 1269:                        ($cmd,$udom,$uname,$umode,$npass)=split(/:/,$userinput);
 1270: 		       &Debug("cmd =".$cmd." $udom =".$udom.
 1271: 				    " uname=".$uname);
 1272:                        chomp($npass);
 1273:                        $npass=&unescape($npass);
 1274:                        my $proname=propath($udom,$uname);
 1275:                        my $passfilename="$proname/passwd";
 1276: 		       &Debug("Password file created will be:".
 1277: 				    $passfilename);
 1278:                        if (-e $passfilename) {
 1279: 			   print $client "already_exists\n";
 1280:                        } elsif ($udom ne $currentdomainid) {
 1281:                            print $client "not_right_domain\n";
 1282:                        } else {
 1283:                            my @fpparts=split(/\//,$proname);
 1284:                            my $fpnow=$fpparts[0].'/'.$fpparts[1].'/'.$fpparts[2];
 1285:                            my $fperror='';
 1286:                            for (my $i=3;$i<=$#fpparts;$i++) {
 1287:                                $fpnow.='/'.$fpparts[$i]; 
 1288:                                unless (-e $fpnow) {
 1289: 				   unless (mkdir($fpnow,0777)) {
 1290:                                       $fperror="error: ".($!+0)
 1291: 					  ." mkdir failed while attempting "
 1292:                                               ."makeuser\n";
 1293:                                    }
 1294:                                }
 1295:                            }
 1296:                            unless ($fperror) {
 1297: 			       my $result=&make_passwd_file($uname, $umode,$npass,
 1298: 							    $passfilename);
 1299: 			       print $client $result;
 1300:                            } else {
 1301:                                print $client "$fperror\n";
 1302:                            }
 1303:                        }
 1304: 		     } else {
 1305: 		       print $client "refused\n";
 1306: 		     }
 1307: 		     umask($oldumask);
 1308: # -------------------------------------------------------------- changeuserauth
 1309:                    } elsif ($userinput =~ /^changeuserauth/) {
 1310: 		       &Debug("Changing authorization");
 1311: 		      if ($wasenc==1) {
 1312:                        my 
 1313: 		       ($cmd,$udom,$uname,$umode,$npass)=split(/:/,$userinput);
 1314:                        chomp($npass);
 1315: 		       &Debug("cmd = ".$cmd." domain= ".$udom.
 1316: 			      "uname =".$uname." umode= ".$umode);
 1317:                        $npass=&unescape($npass);
 1318:                        my $proname=&propath($udom,$uname);
 1319:                        my $passfilename="$proname/passwd";
 1320: 		       if ($udom ne $currentdomainid) {
 1321:                            print $client "not_right_domain\n";
 1322:                        } else {
 1323: 			   my $result=&make_passwd_file($uname, $umode,$npass,
 1324: 							$passfilename);
 1325: 			   print $client $result;
 1326:                        }
 1327: 		     } else {
 1328: 		       print $client "refused\n";
 1329: 		     }
 1330: # ------------------------------------------------------------------------ home
 1331:                    } elsif ($userinput =~ /^home/) {
 1332:                        my ($cmd,$udom,$uname)=split(/:/,$userinput);
 1333:                        chomp($uname);
 1334:                        my $proname=propath($udom,$uname);
 1335:                        if (-e $proname) {
 1336:                           print $client "found\n";
 1337:                        } else {
 1338: 			  print $client "not_found\n";
 1339:                        }
 1340: # ---------------------------------------------------------------------- update
 1341:                    } elsif ($userinput =~ /^update/) {
 1342:                        my ($cmd,$fname)=split(/:/,$userinput);
 1343:                        my $ownership=ishome($fname);
 1344:                        if ($ownership eq 'not_owner') {
 1345:                         if (-e $fname) {
 1346:                           my ($dev,$ino,$mode,$nlink,
 1347:                               $uid,$gid,$rdev,$size,
 1348:                               $atime,$mtime,$ctime,
 1349:                               $blksize,$blocks)=stat($fname);
 1350:                           my $now=time;
 1351:                           my $since=$now-$atime;
 1352:                           if ($since>$perlvar{'lonExpire'}) {
 1353:                               my $reply=
 1354:                                     &reply("unsub:$fname","$hostid{$clientip}");
 1355:                               unlink("$fname");
 1356:                           } else {
 1357: 			     my $transname="$fname.in.transfer";
 1358:                              my $remoteurl=
 1359:                                     reply("sub:$fname","$hostid{$clientip}");
 1360:                              my $response;
 1361:                               {
 1362:                              my $ua=new LWP::UserAgent;
 1363:                              my $request=new HTTP::Request('GET',"$remoteurl");
 1364:                              $response=$ua->request($request,$transname);
 1365: 			      }
 1366:                              if ($response->is_error()) {
 1367: 				 unlink($transname);
 1368:                                  my $message=$response->status_line;
 1369:                                  &logthis(
 1370:                                   "LWP GET: $message for $fname ($remoteurl)");
 1371:                              } else {
 1372: 	                         if ($remoteurl!~/\.meta$/) {
 1373:                                   my $ua=new LWP::UserAgent;
 1374:                                   my $mrequest=
 1375:                                    new HTTP::Request('GET',$remoteurl.'.meta');
 1376:                                   my $mresponse=
 1377:                                    $ua->request($mrequest,$fname.'.meta');
 1378:                                   if ($mresponse->is_error()) {
 1379: 		                    unlink($fname.'.meta');
 1380:                                   }
 1381: 	                         }
 1382:                                  rename($transname,$fname);
 1383: 			     }
 1384:                           }
 1385:                           print $client "ok\n";
 1386:                         } else {
 1387:                           print $client "not_found\n";
 1388:                         }
 1389: 		       } else {
 1390: 			print $client "rejected\n";
 1391:                        }
 1392: # -------------------------------------- fetch a user file from a remote server
 1393:                    } elsif ($userinput =~ /^fetchuserfile/) {
 1394:                       my ($cmd,$fname)=split(/:/,$userinput);
 1395: 		      my ($udom,$uname,$ufile)=split(/\//,$fname);
 1396:                       my $udir=propath($udom,$uname).'/userfiles';
 1397:                       unless (-e $udir) { mkdir($udir,0770); }
 1398:                        if (-e $udir) {
 1399:                        $ufile=~s/^[\.\~]+//;
 1400:                        $ufile=~s/\///g;
 1401:                        my $transname=$udir.'/'.$ufile;
 1402:                        my $remoteurl='http://'.$clientip.'/userfiles/'.$fname;
 1403:                              my $response;
 1404:                               {
 1405:                              my $ua=new LWP::UserAgent;
 1406:                              my $request=new HTTP::Request('GET',"$remoteurl");
 1407:                              $response=$ua->request($request,$transname);
 1408: 			      }
 1409:                              if ($response->is_error()) {
 1410: 				 unlink($transname);
 1411:                                  my $message=$response->status_line;
 1412:                                  &logthis(
 1413:                                   "LWP GET: $message for $fname ($remoteurl)");
 1414: 				 print $client "failed\n";
 1415:                              } else {
 1416:                                  print $client "ok\n";
 1417:                              }
 1418:                      } else {
 1419:                        print $client "not_home\n";
 1420:                      } 
 1421: # ------------------------------------------ authenticate access to a user file
 1422:                    } elsif ($userinput =~ /^tokenauthuserfile/) {
 1423:                        my ($cmd,$fname,$session)=split(/:/,$userinput);
 1424:                        chomp($session);
 1425:                        my $reply='non_auth';
 1426:                        if (open(ENVIN,$perlvar{'lonIDsDir'}.'/'.
 1427: 				$session.'.id')) {
 1428: 			   while (my $line=<ENVIN>) {
 1429: 			       if ($line=~/userfile\.$fname\=/) { $reply='ok'; }
 1430: 			   }
 1431: 			   close(ENVIN);
 1432: 			   print $client $reply."\n";
 1433: 		       } else {
 1434: 			   print $client "invalid_token\n";
 1435:                        }
 1436: # ----------------------------------------------------------------- unsubscribe
 1437:                    } elsif ($userinput =~ /^unsub/) {
 1438:                        my ($cmd,$fname)=split(/:/,$userinput);
 1439:                        if (-e $fname) {
 1440: 			   print $client &unsub($client,$fname,$clientip);
 1441:                        } else {
 1442: 			   print $client "not_found\n";
 1443:                        }
 1444: # ------------------------------------------------------------------- subscribe
 1445:                    } elsif ($userinput =~ /^sub/) {
 1446: 		       print $client &subscribe($userinput,$clientip);
 1447: # ------------------------------------------------------------- current version
 1448:                    } elsif ($userinput =~ /^currentversion/) {
 1449:                        my ($cmd,$fname)=split(/:/,$userinput);
 1450: 		       print $client &currentversion($fname)."\n";
 1451: # ------------------------------------------------------------------------- log
 1452:                    } elsif ($userinput =~ /^log/) {
 1453:                        my ($cmd,$udom,$uname,$what)=split(/:/,$userinput);
 1454:                        chomp($what);
 1455:                        my $proname=propath($udom,$uname);
 1456:                        my $now=time;
 1457:                        {
 1458: 			 my $hfh;
 1459: 			 if ($hfh=IO::File->new(">>$proname/activity.log")) { 
 1460:                             print $hfh "$now:$hostid{$clientip}:$what\n";
 1461:                             print $client "ok\n"; 
 1462: 			} else {
 1463:                             print $client "error: ".($!+0)
 1464: 				." IO::File->new Failed "
 1465:                                     ."while attempting log\n";
 1466: 		        }
 1467: 		       }
 1468: # ------------------------------------------------------------------------- put
 1469:                    } elsif ($userinput =~ /^put/) {
 1470:                       my ($cmd,$udom,$uname,$namespace,$what)
 1471:                           =split(/:/,$userinput);
 1472:                       $namespace=~s/\//\_/g;
 1473:                       $namespace=~s/\W//g;
 1474:                       if ($namespace ne 'roles') {
 1475:                        chomp($what);
 1476:                        my $proname=propath($udom,$uname);
 1477:                        my $now=time;
 1478:                        unless ($namespace=~/^nohist\_/) {
 1479: 			   my $hfh;
 1480: 			   if (
 1481:                              $hfh=IO::File->new(">>$proname/$namespace.hist")
 1482: 			       ) { print $hfh "P:$now:$what\n"; }
 1483: 		       }
 1484:                        my @pairs=split(/\&/,$what);
 1485: 		       my %hash;
 1486: 		       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
 1487:                            foreach my $pair (@pairs) {
 1488: 			       my ($key,$value)=split(/=/,$pair);
 1489:                                $hash{$key}=$value;
 1490:                            }
 1491: 			   if (untie(%hash)) {
 1492:                               print $client "ok\n";
 1493:                            } else {
 1494:                               print $client "error: ".($!+0)
 1495: 				  ." untie(GDBM) failed ".
 1496:                                       "while attempting put\n";
 1497:                            }
 1498:                        } else {
 1499:                            print $client "error: ".($!)
 1500: 			       ." tie(GDBM) Failed ".
 1501:                                    "while attempting put\n";
 1502:                        }
 1503: 		      } else {
 1504:                           print $client "refused\n";
 1505:                       }
 1506: # -------------------------------------------------------------------- rolesput
 1507:                    } elsif ($userinput =~ /^rolesput/) {
 1508: 		       &Debug("rolesput");
 1509: 		    if ($wasenc==1) {
 1510:                        my ($cmd,$exedom,$exeuser,$udom,$uname,$what)
 1511:                           =split(/:/,$userinput);
 1512: 		       &Debug("cmd = ".$cmd." exedom= ".$exedom.
 1513: 				    "user = ".$exeuser." udom=".$udom.
 1514: 				    "what = ".$what);
 1515:                        my $namespace='roles';
 1516:                        chomp($what);
 1517:                        my $proname=propath($udom,$uname);
 1518:                        my $now=time;
 1519:                        {
 1520: 			   my $hfh;
 1521: 			   if (
 1522:                              $hfh=IO::File->new(">>$proname/$namespace.hist")
 1523: 			       ) { 
 1524:                                   print $hfh "P:$now:$exedom:$exeuser:$what\n";
 1525:                                  }
 1526: 		       }
 1527:                        my @pairs=split(/\&/,$what);
 1528: 		       my %hash;
 1529: 		       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
 1530:                            foreach my $pair (@pairs) {
 1531: 			       my ($key,$value)=split(/=/,$pair);
 1532: 			       &ManagePermissions($key, $udom, $uname,
 1533: 						  &GetAuthType( $udom, 
 1534: 								$uname));
 1535:                                $hash{$key}=$value;
 1536:                            }
 1537: 			   if (untie(%hash)) {
 1538:                               print $client "ok\n";
 1539:                            } else {
 1540:                               print $client "error: ".($!+0)
 1541: 				  ." untie(GDBM) Failed ".
 1542:                                       "while attempting rolesput\n";
 1543:                            }
 1544:                        } else {
 1545:                            print $client "error: ".($!+0)
 1546: 			       ." tie(GDBM) Failed ".
 1547:                                    "while attempting rolesput\n";
 1548:                        }
 1549: 		      } else {
 1550:                           print $client "refused\n";
 1551:                       }
 1552: # -------------------------------------------------------------------- rolesdel
 1553:                    } elsif ($userinput =~ /^rolesdel/) {
 1554: 		       &Debug("rolesdel");
 1555: 		    if ($wasenc==1) {
 1556:                        my ($cmd,$exedom,$exeuser,$udom,$uname,$what)
 1557:                           =split(/:/,$userinput);
 1558: 		       &Debug("cmd = ".$cmd." exedom= ".$exedom.
 1559: 				    "user = ".$exeuser." udom=".$udom.
 1560: 				    "what = ".$what);
 1561:                        my $namespace='roles';
 1562:                        chomp($what);
 1563:                        my $proname=propath($udom,$uname);
 1564:                        my $now=time;
 1565:                        {
 1566: 			   my $hfh;
 1567: 			   if (
 1568:                              $hfh=IO::File->new(">>$proname/$namespace.hist")
 1569: 			       ) { 
 1570:                                   print $hfh "D:$now:$exedom:$exeuser:$what\n";
 1571:                                  }
 1572: 		       }
 1573:                        my @rolekeys=split(/\&/,$what);
 1574: 		       my %hash;
 1575: 		       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
 1576:                            foreach my $key (@rolekeys) {
 1577:                                delete $hash{$key};
 1578:                            }
 1579: 			   if (untie(%hash)) {
 1580:                               print $client "ok\n";
 1581:                            } else {
 1582:                               print $client "error: ".($!+0)
 1583: 				  ." untie(GDBM) Failed ".
 1584:                                       "while attempting rolesdel\n";
 1585:                            }
 1586:                        } else {
 1587:                            print $client "error: ".($!+0)
 1588: 			       ." tie(GDBM) Failed ".
 1589:                                    "while attempting rolesdel\n";
 1590:                        }
 1591: 		      } else {
 1592:                           print $client "refused\n";
 1593:                       }
 1594: # ------------------------------------------------------------------------- get
 1595:                    } elsif ($userinput =~ /^get/) {
 1596:                        my ($cmd,$udom,$uname,$namespace,$what)
 1597:                           =split(/:/,$userinput);
 1598:                        $namespace=~s/\//\_/g;
 1599:                        $namespace=~s/\W//g;
 1600:                        chomp($what);
 1601:                        my @queries=split(/\&/,$what);
 1602:                        my $proname=propath($udom,$uname);
 1603:                        my $qresult='';
 1604: 		       my %hash;
 1605: 		       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
 1606:                            for (my $i=0;$i<=$#queries;$i++) {
 1607:                                $qresult.="$hash{$queries[$i]}&";
 1608:                            }
 1609: 			   if (untie(%hash)) {
 1610: 		              $qresult=~s/\&$//;
 1611:                               print $client "$qresult\n";
 1612:                            } else {
 1613:                               print $client "error: ".($!+0)
 1614: 				  ." untie(GDBM) Failed ".
 1615:                                       "while attempting get\n";
 1616:                            }
 1617:                        } else {
 1618:                            if ($!+0 == 2) {
 1619:                                print $client "error:No such file or ".
 1620:                                    "GDBM reported bad block error\n";
 1621:                            } else {
 1622:                                print $client "error: ".($!+0)
 1623:                                    ." tie(GDBM) Failed ".
 1624:                                        "while attempting get\n";
 1625:                            }
 1626:                        }
 1627: # ------------------------------------------------------------------------ eget
 1628:                    } elsif ($userinput =~ /^eget/) {
 1629:                        my ($cmd,$udom,$uname,$namespace,$what)
 1630:                           =split(/:/,$userinput);
 1631:                        $namespace=~s/\//\_/g;
 1632:                        $namespace=~s/\W//g;
 1633:                        chomp($what);
 1634:                        my @queries=split(/\&/,$what);
 1635:                        my $proname=propath($udom,$uname);
 1636:                        my $qresult='';
 1637: 		       my %hash;
 1638: 		       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
 1639:                            for (my $i=0;$i<=$#queries;$i++) {
 1640:                                $qresult.="$hash{$queries[$i]}&";
 1641:                            }
 1642: 			   if (untie(%hash)) {
 1643: 		              $qresult=~s/\&$//;
 1644:                               if ($cipher) {
 1645:                                 my $cmdlength=length($qresult);
 1646:                                 $qresult.="         ";
 1647:                                 my $encqresult='';
 1648:                                 for 
 1649: 				(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 1650:                                  $encqresult.=
 1651:                                  unpack("H16",
 1652:                                  $cipher->encrypt(substr($qresult,$encidx,8)));
 1653:                                 }
 1654:                                 print $client "enc:$cmdlength:$encqresult\n";
 1655: 			      } else {
 1656: 			        print $client "error:no_key\n";
 1657:                               }
 1658:                            } else {
 1659:                               print $client "error: ".($!+0)
 1660: 				  ." untie(GDBM) Failed ".
 1661:                                       "while attempting eget\n";
 1662:                            }
 1663:                        } else {
 1664:                            print $client "error: ".($!+0)
 1665: 			       ." tie(GDBM) Failed ".
 1666:                                    "while attempting eget\n";
 1667:                        }
 1668: # ------------------------------------------------------------------------- del
 1669:                    } elsif ($userinput =~ /^del/) {
 1670:                        my ($cmd,$udom,$uname,$namespace,$what)
 1671:                           =split(/:/,$userinput);
 1672:                        $namespace=~s/\//\_/g;
 1673:                        $namespace=~s/\W//g;
 1674:                        chomp($what);
 1675:                        my $proname=propath($udom,$uname);
 1676:                        my $now=time;
 1677:                        unless ($namespace=~/^nohist\_/) {
 1678: 			   my $hfh;
 1679: 			   if (
 1680:                              $hfh=IO::File->new(">>$proname/$namespace.hist")
 1681: 			       ) { print $hfh "D:$now:$what\n"; }
 1682: 		       }
 1683:                        my @keys=split(/\&/,$what);
 1684: 		       my %hash;
 1685: 		       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
 1686:                            foreach my $key (@keys) {
 1687:                                delete($hash{$key});
 1688:                            }
 1689: 			   if (untie(%hash)) {
 1690:                               print $client "ok\n";
 1691:                            } else {
 1692:                               print $client "error: ".($!+0)
 1693: 				  ." untie(GDBM) Failed ".
 1694:                                       "while attempting del\n";
 1695:                            }
 1696:                        } else {
 1697:                            print $client "error: ".($!+0)
 1698: 			       ." tie(GDBM) Failed ".
 1699:                                    "while attempting del\n";
 1700:                        }
 1701: # ------------------------------------------------------------------------ keys
 1702:                    } elsif ($userinput =~ /^keys/) {
 1703:                        my ($cmd,$udom,$uname,$namespace)
 1704:                           =split(/:/,$userinput);
 1705:                        $namespace=~s/\//\_/g;
 1706:                        $namespace=~s/\W//g;
 1707:                        my $proname=propath($udom,$uname);
 1708:                        my $qresult='';
 1709: 		       my %hash;
 1710: 		       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
 1711:                            foreach my $key (keys %hash) {
 1712:                                $qresult.="$key&";
 1713:                            }
 1714: 			   if (untie(%hash)) {
 1715: 		              $qresult=~s/\&$//;
 1716:                               print $client "$qresult\n";
 1717:                            } else {
 1718:                               print $client "error: ".($!+0)
 1719: 				  ." untie(GDBM) Failed ".
 1720:                                       "while attempting keys\n";
 1721:                            }
 1722:                        } else {
 1723:                            print $client "error: ".($!+0)
 1724: 			       ." tie(GDBM) Failed ".
 1725:                                    "while attempting keys\n";
 1726:                        }
 1727: # ----------------------------------------------------------------- dumpcurrent
 1728:                    } elsif ($userinput =~ /^currentdump/) {
 1729:                        my ($cmd,$udom,$uname,$namespace)
 1730:                           =split(/:/,$userinput);
 1731:                        $namespace=~s/\//\_/g;
 1732:                        $namespace=~s/\W//g;
 1733:                        my $qresult='';
 1734:                        my $proname=propath($udom,$uname);
 1735: 		       my %hash;
 1736:                        if (tie(%hash,'GDBM_File',
 1737:                                "$proname/$namespace.db",
 1738:                                &GDBM_READER(),0640)) {
 1739:                            # Structure of %data:
 1740:                            # $data{$symb}->{$parameter}=$value;
 1741:                            # $data{$symb}->{'v.'.$parameter}=$version;
 1742:                            # since $parameter will be unescaped, we do not
 1743:                            # have to worry about silly parameter names...
 1744:                            my %data = ();
 1745:                            while (my ($key,$value) = each(%hash)) {
 1746:                               my ($v,$symb,$param) = split(/:/,$key);
 1747:                               next if ($v eq 'version' || $symb eq 'keys');
 1748:                               next if (exists($data{$symb}) && 
 1749:                                        exists($data{$symb}->{$param}) &&
 1750:                                        $data{$symb}->{'v.'.$param} > $v);
 1751:                               $data{$symb}->{$param}=$value;
 1752:                               $data{$symb}->{'v.'.$param}=$v;
 1753:                            }
 1754:                            if (untie(%hash)) {
 1755:                              while (my ($symb,$param_hash) = each(%data)) {
 1756:                                while(my ($param,$value) = each (%$param_hash)){
 1757:                                  next if ($param =~ /^v\./);
 1758:                                  $qresult.=$symb.':'.$param.'='.$value.'&';
 1759:                                }
 1760:                              }
 1761:                              chop($qresult);
 1762:                              print $client "$qresult\n";
 1763:                            } else {
 1764:                              print $client "error: ".($!+0)
 1765: 				 ." untie(GDBM) Failed ".
 1766:                                      "while attempting currentdump\n";
 1767:                            }
 1768:                        } else {
 1769:                            print $client "error: ".($!+0)
 1770: 			       ." tie(GDBM) Failed ".
 1771:                                       "while attempting currentdump\n";
 1772:                        }
 1773: # ------------------------------------------------------------------------ dump
 1774:                    } elsif ($userinput =~ /^dump/) {
 1775:                        my ($cmd,$udom,$uname,$namespace,$regexp)
 1776:                           =split(/:/,$userinput);
 1777:                        $namespace=~s/\//\_/g;
 1778:                        $namespace=~s/\W//g;
 1779:                        if (defined($regexp)) {
 1780:                           $regexp=&unescape($regexp);
 1781: 		       } else {
 1782:                           $regexp='.';
 1783: 		       }
 1784:                        my $qresult='';
 1785:                        my $proname=propath($udom,$uname);
 1786: 		       my %hash;
 1787: 		       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
 1788:                            study($regexp);
 1789:                            while (my ($key,$value) = each(%hash)) {
 1790:                                if ($regexp eq '.') {
 1791:                                    $qresult.=$key.'='.$value.'&';
 1792:                                } else {
 1793:                                    my $unescapeKey = &unescape($key);
 1794:                                    if (eval('$unescapeKey=~/$regexp/')) {
 1795:                                        $qresult.="$key=$value&";
 1796:                                    }
 1797:                                }
 1798:                            }
 1799:                            if (untie(%hash)) {
 1800:                                chop($qresult);
 1801:                                print $client "$qresult\n";
 1802:                            } else {
 1803:                                print $client "error: ".($!+0)
 1804: 				   ." untie(GDBM) Failed ".
 1805:                                        "while attempting dump\n";
 1806:                            }
 1807:                        } else {
 1808:                            print $client "error: ".($!+0)
 1809: 			       ." tie(GDBM) Failed ".
 1810:                                       "while attempting dump\n";
 1811:                        }
 1812: # ----------------------------------------------------------------------- store
 1813:                    } elsif ($userinput =~ /^store/) {
 1814:                       my ($cmd,$udom,$uname,$namespace,$rid,$what)
 1815:                           =split(/:/,$userinput);
 1816:                       $namespace=~s/\//\_/g;
 1817:                       $namespace=~s/\W//g;
 1818:                       if ($namespace ne 'roles') {
 1819:                        chomp($what);
 1820:                        my $proname=propath($udom,$uname);
 1821:                        my $now=time;
 1822:                        unless ($namespace=~/^nohist\_/) {
 1823: 			   my $hfh;
 1824: 			   if (
 1825:                              $hfh=IO::File->new(">>$proname/$namespace.hist")
 1826: 			       ) { print $hfh "P:$now:$rid:$what\n"; }
 1827: 		       }
 1828:                        my @pairs=split(/\&/,$what);
 1829: 		       my %hash;
 1830: 		       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
 1831:                            my @previouskeys=split(/&/,$hash{"keys:$rid"});
 1832:                            my $key;
 1833:                            $hash{"version:$rid"}++;
 1834:                            my $version=$hash{"version:$rid"};
 1835:                            my $allkeys=''; 
 1836:                            foreach my $pair (@pairs) {
 1837: 			       my ($key,$value)=split(/=/,$pair);
 1838:                                $allkeys.=$key.':';
 1839:                                $hash{"$version:$rid:$key"}=$value;
 1840:                            }
 1841:                            $hash{"$version:$rid:timestamp"}=$now;
 1842:                            $allkeys.='timestamp';
 1843:                            $hash{"$version:keys:$rid"}=$allkeys;
 1844: 			   if (untie(%hash)) {
 1845:                               print $client "ok\n";
 1846:                            } else {
 1847:                               print $client "error: ".($!+0)
 1848: 				  ." untie(GDBM) Failed ".
 1849:                                       "while attempting store\n";
 1850:                            }
 1851:                        } else {
 1852:                            print $client "error: ".($!+0)
 1853: 			       ." tie(GDBM) Failed ".
 1854:                                    "while attempting store\n";
 1855:                        }
 1856: 		      } else {
 1857:                           print $client "refused\n";
 1858:                       }
 1859: # --------------------------------------------------------------------- restore
 1860:                    } elsif ($userinput =~ /^restore/) {
 1861:                        my ($cmd,$udom,$uname,$namespace,$rid)
 1862:                           =split(/:/,$userinput);
 1863:                        $namespace=~s/\//\_/g;
 1864:                        $namespace=~s/\W//g;
 1865:                        chomp($rid);
 1866:                        my $proname=propath($udom,$uname);
 1867:                        my $qresult='';
 1868: 		       my %hash;
 1869: 		       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
 1870:                 	   my $version=$hash{"version:$rid"};
 1871:                            $qresult.="version=$version&";
 1872:                            my $scope;
 1873:                            for ($scope=1;$scope<=$version;$scope++) {
 1874: 			      my $vkeys=$hash{"$scope:keys:$rid"};
 1875:                               my @keys=split(/:/,$vkeys);
 1876:                               my $key;
 1877:                               $qresult.="$scope:keys=$vkeys&";
 1878:                               foreach $key (@keys) {
 1879: 	     $qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
 1880:                               }                                  
 1881:                            }
 1882: 			   if (untie(%hash)) {
 1883: 		              $qresult=~s/\&$//;
 1884:                               print $client "$qresult\n";
 1885:                            } else {
 1886:                               print $client "error: ".($!+0)
 1887: 				  ." untie(GDBM) Failed ".
 1888:                                       "while attempting restore\n";
 1889:                            }
 1890:                        } else {
 1891:                            print $client "error: ".($!+0)
 1892: 			       ." tie(GDBM) Failed ".
 1893:                                    "while attempting restore\n";
 1894:                        }
 1895: # -------------------------------------------------------------------- chatsend
 1896:                    } elsif ($userinput =~ /^chatsend/) {
 1897:                        my ($cmd,$cdom,$cnum,$newpost)=split(/\:/,$userinput);
 1898:                        &chatadd($cdom,$cnum,$newpost);
 1899:                        print $client "ok\n";
 1900: # -------------------------------------------------------------------- chatretr
 1901:                    } elsif ($userinput =~ /^chatretr/) {
 1902:                        my 
 1903:                         ($cmd,$cdom,$cnum,$udom,$uname)=split(/\:/,$userinput);
 1904:                        my $reply='';
 1905:                        foreach (&getchat($cdom,$cnum,$udom,$uname)) {
 1906: 			   $reply.=&escape($_).':';
 1907:                        }
 1908:                        $reply=~s/\:$//;
 1909:                        print $client $reply."\n";
 1910: # ------------------------------------------------------------------- querysend
 1911:                    } elsif ($userinput =~ /^querysend/) {
 1912:                        my ($cmd,$query,
 1913: 			   $arg1,$arg2,$arg3)=split(/\:/,$userinput);
 1914: 		       $query=~s/\n*$//g;
 1915: 		       print $client "".
 1916: 			       sqlreply("$hostid{$clientip}\&$query".
 1917: 					"\&$arg1"."\&$arg2"."\&$arg3")."\n";
 1918: # ------------------------------------------------------------------ queryreply
 1919:                    } elsif ($userinput =~ /^queryreply/) {
 1920:                        my ($cmd,$id,$reply)=split(/:/,$userinput); 
 1921: 		       my $store;
 1922:                        my $execdir=$perlvar{'lonDaemons'};
 1923:                        if ($store=IO::File->new(">$execdir/tmp/$id")) {
 1924: 			   $reply=~s/\&/\n/g;
 1925: 			   print $store $reply;
 1926: 			   close $store;
 1927: 			   my $store2=IO::File->new(">$execdir/tmp/$id.end");
 1928: 			   print $store2 "done\n";
 1929: 			   close $store2;
 1930: 			   print $client "ok\n";
 1931: 		       }
 1932: 		       else {
 1933: 			   print $client "error: ".($!+0)
 1934: 			       ." IO::File->new Failed ".
 1935:                                    "while attempting queryreply\n";
 1936: 		       }
 1937: # ----------------------------------------------------------------- courseidput
 1938:                    } elsif ($userinput =~ /^courseidput/) {
 1939:                        my ($cmd,$udom,$what)=split(/:/,$userinput);
 1940:                        chomp($what);
 1941:                        $udom=~s/\W//g;
 1942:                        my $proname=
 1943:                               "$perlvar{'lonUsersDir'}/$udom/nohist_courseids";
 1944:                        my $now=time;
 1945:                        my @pairs=split(/\&/,$what);
 1946: 		       my %hash;
 1947: 		       if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT(),0640)) {
 1948:                            foreach my $pair (@pairs) {
 1949: 			       my ($key,$value)=split(/=/,$pair);
 1950:                                $hash{$key}=$value.':'.$now;
 1951:                            }
 1952: 			   if (untie(%hash)) {
 1953:                               print $client "ok\n";
 1954:                            } else {
 1955:                               print $client "error: ".($!+0)
 1956: 				  ." untie(GDBM) Failed ".
 1957:                                       "while attempting courseidput\n";
 1958:                            }
 1959:                        } else {
 1960:                            print $client "error: ".($!+0)
 1961: 			       ." tie(GDBM) Failed ".
 1962:                                       "while attempting courseidput\n";
 1963:                        }
 1964: # ---------------------------------------------------------------- courseiddump
 1965:                    } elsif ($userinput =~ /^courseiddump/) {
 1966:                        my ($cmd,$udom,$since,$description)
 1967:                           =split(/:/,$userinput);
 1968:                        if (defined($description)) {
 1969:                           $description=&unescape($description);
 1970: 		       } else {
 1971:                           $description='.';
 1972: 		       }
 1973:                        unless (defined($since)) { $since=0; }
 1974:                        my $qresult='';
 1975:                        my $proname=
 1976:                               "$perlvar{'lonUsersDir'}/$udom/nohist_courseids";
 1977: 		       my %hash;
 1978: 		       if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER(),0640)) {
 1979:                            while (my ($key,$value) = each(%hash)) {
 1980:                                my ($descr,$lasttime)=split(/\:/,$value);
 1981:                                if ($lasttime<$since) { next; }
 1982:                                if ($description eq '.') {
 1983:                                    $qresult.=$key.'='.$descr.'&';
 1984:                                } else {
 1985:                                    my $unescapeVal = &unescape($descr);
 1986:                                    if (eval('$unescapeVal=~/$description/i')) {
 1987:                                        $qresult.="$key=$descr&";
 1988:                                    }
 1989:                                }
 1990:                            }
 1991:                            if (untie(%hash)) {
 1992:                                chop($qresult);
 1993:                                print $client "$qresult\n";
 1994:                            } else {
 1995:                                print $client "error: ".($!+0)
 1996: 				   ." untie(GDBM) Failed ".
 1997:                                        "while attempting courseiddump\n";
 1998:                            }
 1999:                        } else {
 2000:                            print $client "error: ".($!+0)
 2001: 			       ." tie(GDBM) Failed ".
 2002:                                       "while attempting courseiddump\n";
 2003:                        }
 2004: # ----------------------------------------------------------------------- idput
 2005:                    } elsif ($userinput =~ /^idput/) {
 2006:                        my ($cmd,$udom,$what)=split(/:/,$userinput);
 2007:                        chomp($what);
 2008:                        $udom=~s/\W//g;
 2009:                        my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
 2010:                        my $now=time;
 2011:                        {
 2012: 			   my $hfh;
 2013: 			   if (
 2014:                              $hfh=IO::File->new(">>$proname.hist")
 2015: 			       ) { print $hfh "P:$now:$what\n"; }
 2016: 		       }
 2017:                        my @pairs=split(/\&/,$what);
 2018: 		       my %hash;
 2019: 		       if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT(),0640)) {
 2020:                            foreach my $pair (@pairs) {
 2021: 			       my ($key,$value)=split(/=/,$pair);
 2022:                                $hash{$key}=$value;
 2023:                            }
 2024: 			   if (untie(%hash)) {
 2025:                               print $client "ok\n";
 2026:                            } else {
 2027:                               print $client "error: ".($!+0)
 2028: 				  ." untie(GDBM) Failed ".
 2029:                                       "while attempting idput\n";
 2030:                            }
 2031:                        } else {
 2032:                            print $client "error: ".($!+0)
 2033: 			       ." tie(GDBM) Failed ".
 2034:                                       "while attempting idput\n";
 2035:                        }
 2036: # ----------------------------------------------------------------------- idget
 2037:                    } elsif ($userinput =~ /^idget/) {
 2038:                        my ($cmd,$udom,$what)=split(/:/,$userinput);
 2039:                        chomp($what);
 2040:                        $udom=~s/\W//g;
 2041:                        my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
 2042:                        my @queries=split(/\&/,$what);
 2043:                        my $qresult='';
 2044: 		       my %hash;
 2045: 		       if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER(),0640)) {
 2046:                            for (my $i=0;$i<=$#queries;$i++) {
 2047:                                $qresult.="$hash{$queries[$i]}&";
 2048:                            }
 2049: 			   if (untie(%hash)) {
 2050: 			       $qresult=~s/\&$//;
 2051: 			       print $client "$qresult\n";
 2052:                            } else {
 2053: 			       print $client "error: ".($!+0)
 2054: 				   ." untie(GDBM) Failed ".
 2055: 				       "while attempting idget\n";
 2056:                            }
 2057:                        } else {
 2058:                            print $client "error: ".($!+0)
 2059: 			       ." tie(GDBM) Failed ".
 2060:                                    "while attempting idget\n";
 2061:                        }
 2062: # ---------------------------------------------------------------------- tmpput
 2063:                    } elsif ($userinput =~ /^tmpput/) {
 2064:                        my ($cmd,$what)=split(/:/,$userinput);
 2065: 		       my $store;
 2066:                        $tmpsnum++;
 2067:                        my $id=$$.'_'.$clientip.'_'.$tmpsnum;
 2068:                        $id=~s/\W/\_/g;
 2069:                        $what=~s/\n//g;
 2070:                        my $execdir=$perlvar{'lonDaemons'};
 2071:                        if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
 2072: 			   print $store $what;
 2073: 			   close $store;
 2074: 			   print $client "$id\n";
 2075: 		       }
 2076: 		       else {
 2077: 			   print $client "error: ".($!+0)
 2078: 			       ."IO::File->new Failed ".
 2079:                                    "while attempting tmpput\n";
 2080: 		       }
 2081: 
 2082: # ---------------------------------------------------------------------- tmpget
 2083:                    } elsif ($userinput =~ /^tmpget/) {
 2084:                        my ($cmd,$id)=split(/:/,$userinput);
 2085:                        chomp($id);
 2086:                        $id=~s/\W/\_/g;
 2087:                        my $store;
 2088:                        my $execdir=$perlvar{'lonDaemons'};
 2089:                        if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
 2090:                            my $reply=<$store>;
 2091: 			   print $client "$reply\n";
 2092:                            close $store;
 2093: 		       }
 2094: 		       else {
 2095: 			   print $client "error: ".($!+0)
 2096: 			       ."IO::File->new Failed ".
 2097:                                    "while attempting tmpget\n";
 2098: 		       }
 2099: 
 2100: # ---------------------------------------------------------------------- tmpdel
 2101:                    } elsif ($userinput =~ /^tmpdel/) {
 2102:                        my ($cmd,$id)=split(/:/,$userinput);
 2103:                        chomp($id);
 2104:                        $id=~s/\W/\_/g;
 2105:                        my $execdir=$perlvar{'lonDaemons'};
 2106:                        if (unlink("$execdir/tmp/$id.tmp")) {
 2107: 			   print $client "ok\n";
 2108: 		       } else {
 2109: 			   print $client "error: ".($!+0)
 2110: 			       ."Unlink tmp Failed ".
 2111:                                    "while attempting tmpdel\n";
 2112: 		       }
 2113: # -------------------------------------------------------------------------- ls
 2114:                    } elsif ($userinput =~ /^ls/) {
 2115:                        my ($cmd,$ulsdir)=split(/:/,$userinput);
 2116:                        my $ulsout='';
 2117:                        my $ulsfn;
 2118:                        if (-e $ulsdir) {
 2119:                            if(-d $ulsdir) {
 2120:                                if (opendir(LSDIR,$ulsdir)) {
 2121:                                    while ($ulsfn=readdir(LSDIR)) {
 2122:                                        my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 2123:                                        $ulsout.=$ulsfn.'&'.
 2124:                                                 join('&',@ulsstats).':';
 2125:                                    }
 2126:                                    closedir(LSDIR);
 2127:                                }
 2128:                            } else {
 2129:                                my @ulsstats=stat($ulsdir);
 2130:                                $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 2131:                            }
 2132:                        } else {
 2133:                           $ulsout='no_such_dir';
 2134:                        }
 2135:                        if ($ulsout eq '') { $ulsout='empty'; }
 2136:                        print $client "$ulsout\n";
 2137: # ----------------------------------------------------------------- setannounce
 2138:                    } elsif ($userinput =~ /^setannounce/) {
 2139: 		       my ($cmd,$announcement)=split(/:/,$userinput);
 2140: 		       chomp($announcement);
 2141: 		       $announcement=&unescape($announcement);
 2142:                        if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
 2143: 						'/announcement.txt')) {
 2144: 			   print $store $announcement;
 2145:                            close $store;
 2146: 			   print $client "ok\n";
 2147: 		       } else {
 2148: 			   print $client "error: ".($!+0)."\n";
 2149: 		       }
 2150: # ------------------------------------------------------------------ Hanging up
 2151:                    } elsif (($userinput =~ /^exit/) ||
 2152:                             ($userinput =~ /^init/)) {
 2153:                        &logthis(
 2154:       "Client $clientip ($hostid{$clientip}) hanging up: $userinput");
 2155:                        print $client "bye\n";
 2156:                        $client->close();
 2157: 		       last;
 2158: # ------------------------------------------------------------- unknown command
 2159: 		   } elsif ($userinput =~ /^sethost:/) {
 2160: 		       print $client &sethost($userinput)."\n";
 2161: 		   } elsif ($userinput =~/^version:/) {
 2162: 		       print $client &version($userinput)."\n";
 2163:                    } else {
 2164:                        # unknown command
 2165:                        print $client "unknown_cmd\n";
 2166:                    }
 2167: # -------------------------------------------------------------------- complete
 2168: 		   alarm(0);
 2169:                    &status('Listening to '.$hostid{$clientip});
 2170: 	       }
 2171: # --------------------------------------------- client unknown or fishy, refuse
 2172:             } else {
 2173: 	        print $client "refused\n";
 2174:                 $client->close();
 2175:                 &logthis("<font color=blue>WARNING: "
 2176:                 ."Rejected client $clientip, closing connection</font>");
 2177:             }
 2178: 	}             
 2179: 
 2180: # =============================================================================
 2181:        
 2182: 	&logthis("<font color=red>CRITICAL: "
 2183: 		 ."Disconnect from $clientip ($hostid{$clientip})</font>");    
 2184: 
 2185: 
 2186:         # this exit is VERY important, otherwise the child will become
 2187:         # a producer of more and more children, forking yourself into
 2188:         # process death.
 2189:         exit;
 2190:     
 2191: }
 2192: 
 2193: 
 2194: #
 2195: #   Checks to see if the input roleput request was to set
 2196: # an author role.  If so, invokes the lchtmldir script to set
 2197: # up a correct public_html 
 2198: # Parameters:
 2199: #    request   - The request sent to the rolesput subchunk.
 2200: #                We're looking for  /domain/_au
 2201: #    domain    - The domain in which the user is having roles doctored.
 2202: #    user      - Name of the user for which the role is being put.
 2203: #    authtype  - The authentication type associated with the user.
 2204: #
 2205: sub ManagePermissions
 2206: {
 2207:     my $request = shift;
 2208:     my $domain  = shift;
 2209:     my $user    = shift;
 2210:     my $authtype= shift;
 2211: 
 2212:     # See if the request is of the form /$domain/_au
 2213:     &logthis("ruequest is $request");
 2214:     if($request =~ /^(\/$domain\/_au)$/) { # It's an author rolesput...
 2215: 	my $execdir = $perlvar{'lonDaemons'};
 2216: 	my $userhome= "/home/$user" ;
 2217: 	&logthis("system $execdir/lchtmldir $userhome $user $authtype");
 2218: 	system("$execdir/lchtmldir $userhome $user $authtype");
 2219:     }
 2220: }
 2221: #
 2222: #   GetAuthType - Determines the authorization type of a user in a domain.
 2223: 
 2224: #     Returns the authorization type or nouser if there is no such user.
 2225: #
 2226: sub GetAuthType 
 2227: {
 2228:     my $domain = shift;
 2229:     my $user   = shift;
 2230: 
 2231:     Debug("GetAuthType( $domain, $user ) \n");
 2232:     my $proname    = &propath($domain, $user); 
 2233:     my $passwdfile = "$proname/passwd";
 2234:     if( -e $passwdfile ) {
 2235: 	my $pf = IO::File->new($passwdfile);
 2236: 	my $realpassword = <$pf>;
 2237: 	chomp($realpassword);
 2238: 	Debug("Password info = $realpassword\n");
 2239: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
 2240: 	Debug("Authtype = $authtype, content = $contentpwd\n");
 2241: 	my $availinfo = '';
 2242: 	if($authtype eq 'krb4' or $authtype eq 'krb5') {
 2243: 	    $availinfo = $contentpwd;
 2244: 	}
 2245: 
 2246: 	return "$authtype:$availinfo";
 2247:     }
 2248:     else {
 2249: 	Debug("Returning nouser");
 2250: 	return "nouser";
 2251:     }
 2252: }
 2253: 
 2254: sub addline {
 2255:     my ($fname,$hostid,$ip,$newline)=@_;
 2256:     my $contents;
 2257:     my $found=0;
 2258:     my $expr='^'.$hostid.':'.$ip.':';
 2259:     $expr =~ s/\./\\\./g;
 2260:     my $sh;
 2261:     if ($sh=IO::File->new("$fname.subscription")) {
 2262: 	while (my $subline=<$sh>) {
 2263: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
 2264: 	}
 2265: 	$sh->close();
 2266:     }
 2267:     $sh=IO::File->new(">$fname.subscription");
 2268:     if ($contents) { print $sh $contents; }
 2269:     if ($newline) { print $sh $newline; }
 2270:     $sh->close();
 2271:     return $found;
 2272: }
 2273: 
 2274: sub getchat {
 2275:     my ($cdom,$cname,$udom,$uname)=@_;
 2276:     my %hash;
 2277:     my $proname=&propath($cdom,$cname);
 2278:     my @entries=();
 2279:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
 2280: 	    &GDBM_READER(),0640)) {
 2281: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
 2282: 	untie %hash;
 2283:     }
 2284:     my @participants=();
 2285:     my $cutoff=time-60;
 2286:     if (tie(%hash,'GDBM_File',"$proname/nohist_inchatroom.db",
 2287: 	    &GDBM_WRCREAT(),0640)) {
 2288:         $hash{$uname.':'.$udom}=time;
 2289:         foreach (sort keys %hash) {
 2290: 	    if ($hash{$_}>$cutoff) {
 2291: 		$participants[$#participants+1]='active_participant:'.$_;
 2292:             }
 2293:         }
 2294:         untie %hash;
 2295:     }
 2296:     return (@participants,@entries);
 2297: }
 2298: 
 2299: sub chatadd {
 2300:     my ($cdom,$cname,$newchat)=@_;
 2301:     my %hash;
 2302:     my $proname=&propath($cdom,$cname);
 2303:     my @entries=();
 2304:     my $time=time;
 2305:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
 2306: 	    &GDBM_WRCREAT(),0640)) {
 2307: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
 2308: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
 2309: 	my ($thentime,$idnum)=split(/\_/,$lastid);
 2310: 	my $newid=$time.'_000000';
 2311: 	if ($thentime==$time) {
 2312: 	    $idnum=~s/^0+//;
 2313: 	    $idnum++;
 2314: 	    $idnum=substr('000000'.$idnum,-6,6);
 2315: 	    $newid=$time.'_'.$idnum;
 2316: 	}
 2317: 	$hash{$newid}=$newchat;
 2318: 	my $expired=$time-3600;
 2319: 	foreach (keys %hash) {
 2320: 	    my ($thistime)=($_=~/(\d+)\_/);
 2321: 	    if ($thistime<$expired) {
 2322: 		delete $hash{$_};
 2323: 	    }
 2324: 	}
 2325: 	untie %hash;
 2326:     }
 2327:     {
 2328: 	my $hfh;
 2329: 	if ($hfh=IO::File->new(">>$proname/chatroom.log")) { 
 2330: 	    print $hfh "$time:".&unescape($newchat)."\n";
 2331: 	}
 2332:     }
 2333: }
 2334: 
 2335: sub unsub {
 2336:     my ($fname,$clientip)=@_;
 2337:     my $result;
 2338:     if (unlink("$fname.$hostid{$clientip}")) {
 2339: 	$result="ok\n";
 2340:     } else {
 2341: 	$result="not_subscribed\n";
 2342:     }
 2343:     if (-e "$fname.subscription") {
 2344: 	my $found=&addline($fname,$hostid{$clientip},$clientip,'');
 2345: 	if ($found) { $result="ok\n"; }
 2346:     } else {
 2347: 	if ($result != "ok\n") { $result="not_subscribed\n"; }
 2348:     }
 2349:     return $result;
 2350: }
 2351: 
 2352: sub currentversion {
 2353:     my $fname=shift;
 2354:     my $version=-1;
 2355:     my $ulsdir='';
 2356:     if ($fname=~/^(.+)\/[^\/]+$/) {
 2357:        $ulsdir=$1;
 2358:     }
 2359:     my ($fnamere1,$fnamere2);
 2360:     # remove version if already specified
 2361:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
 2362:     # get the bits that go before and after the version number
 2363:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
 2364: 	$fnamere1=$1;
 2365: 	$fnamere2='.'.$2;
 2366:     }
 2367:     if (-e $fname) { $version=1; }
 2368:     if (-e $ulsdir) {
 2369: 	if(-d $ulsdir) {
 2370: 	    if (opendir(LSDIR,$ulsdir)) {
 2371: 		my $ulsfn;
 2372: 		while ($ulsfn=readdir(LSDIR)) {
 2373: # see if this is a regular file (ignore links produced earlier)
 2374: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
 2375: 		    unless (-l $thisfile) {
 2376: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E/) {
 2377: 			    if ($1>$version) { $version=$1; }
 2378: 			}
 2379: 		    }
 2380: 		}
 2381: 		closedir(LSDIR);
 2382: 		$version++;
 2383: 	    }
 2384: 	}
 2385:     }
 2386:     return $version;
 2387: }
 2388: 
 2389: sub thisversion {
 2390:     my $fname=shift;
 2391:     my $version=-1;
 2392:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
 2393: 	$version=$1;
 2394:     }
 2395:     return $version;
 2396: }
 2397: 
 2398: sub subscribe {
 2399:     my ($userinput,$clientip)=@_;
 2400:     my $result;
 2401:     my ($cmd,$fname)=split(/:/,$userinput);
 2402:     my $ownership=&ishome($fname);
 2403:     if ($ownership eq 'owner') {
 2404: # explitly asking for the current version?
 2405:         unless (-e $fname) {
 2406:             my $currentversion=&currentversion($fname);
 2407: 	    if (&thisversion($fname)==$currentversion) {
 2408:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
 2409: 		    my $root=$1;
 2410:                     my $extension=$2;
 2411:                     symlink($root.'.'.$extension,
 2412:                             $root.'.'.$currentversion.'.'.$extension);
 2413:                     unless ($extension=~/\.meta$/) {
 2414:                        symlink($root.'.'.$extension.'.meta',
 2415:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
 2416: 		    }
 2417:                 }
 2418:             }
 2419:         }
 2420: 	if (-e $fname) {
 2421: 	    if (-d $fname) {
 2422: 		$result="directory\n";
 2423: 	    } else {
 2424: 		if (-e "$fname.$hostid{$clientip}") {&unsub($fname,$clientip);}
 2425: 		my $now=time;
 2426: 		my $found=&addline($fname,$hostid{$clientip},$clientip,
 2427: 				   "$hostid{$clientip}:$clientip:$now\n");
 2428: 		if ($found) { $result="$fname\n"; }
 2429: 		# if they were subscribed to only meta data, delete that
 2430:                 # subscription, when you subscribe to a file you also get
 2431:                 # the metadata
 2432: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
 2433: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
 2434: 		$fname="http://$thisserver/".$fname;
 2435: 		$result="$fname\n";
 2436: 	    }
 2437: 	} else {
 2438: 	    $result="not_found\n";
 2439: 	}
 2440:     } else {
 2441: 	$result="rejected\n";
 2442:     }
 2443:     return $result;
 2444: }
 2445: 
 2446: sub make_passwd_file {
 2447:     my ($uname, $umode,$npass,$passfilename)=@_;
 2448:     my $result="ok\n";
 2449:     if ($umode eq 'krb4' or $umode eq 'krb5') {
 2450: 	{
 2451: 	    my $pf = IO::File->new(">$passfilename");
 2452: 	    print $pf "$umode:$npass\n";
 2453: 	}
 2454:     } elsif ($umode eq 'internal') {
 2455: 	my $salt=time;
 2456: 	$salt=substr($salt,6,2);
 2457: 	my $ncpass=crypt($npass,$salt);
 2458: 	{
 2459: 	    &Debug("Creating internal auth");
 2460: 	    my $pf = IO::File->new(">$passfilename");
 2461: 	    print $pf "internal:$ncpass\n"; 
 2462: 	}
 2463:     } elsif ($umode eq 'localauth') {
 2464: 	{
 2465: 	    my $pf = IO::File->new(">$passfilename");
 2466: 	    print $pf "localauth:$npass\n";
 2467: 	}
 2468:     } elsif ($umode eq 'unix') {
 2469: 	{
 2470: 	    my $execpath="$perlvar{'lonDaemons'}/"."lcuseradd";
 2471: 	    {
 2472: 		&Debug("Executing external: ".$execpath);
 2473: 		&Debug("user  = ".$uname.", Password =". $npass);
 2474: 		my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
 2475: 		print $se "$uname\n";
 2476: 		print $se "$npass\n";
 2477: 		print $se "$npass\n";
 2478: 	    }
 2479: 	    my $useraddok = $?;
 2480: 	    if($useraddok > 0) {
 2481: 		&logthis("Failed lcuseradd: ".&lcuseraddstrerror($useraddok));
 2482: 	    }
 2483: 	    my $pf = IO::File->new(">$passfilename");
 2484: 	    print $pf "unix:\n";
 2485: 	}
 2486:     } elsif ($umode eq 'none') {
 2487: 	{
 2488: 	    my $pf = IO::File->new(">$passfilename");
 2489: 	    print $pf "none:\n";
 2490: 	}
 2491:     } else {
 2492: 	$result="auth_mode_error\n";
 2493:     }
 2494:     return $result;
 2495: }
 2496: 
 2497: sub sethost {
 2498:     my ($remotereq) = @_;
 2499:     my (undef,$hostid)=split(/:/,$remotereq);
 2500:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
 2501:     if ($hostip{$perlvar{'lonHostID'}} eq $hostip{$hostid}) {
 2502: 	$currenthostid=$hostid;
 2503: 	$currentdomainid=$hostdom{$hostid};
 2504: 	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
 2505:     } else {
 2506: 	&logthis("Requested host id $hostid not an alias of ".
 2507: 		 $perlvar{'lonHostID'}." refusing connection");
 2508: 	return 'unable_to_set';
 2509:     }
 2510:     return 'ok';
 2511: }
 2512: 
 2513: sub version {
 2514:     my ($userinput)=@_;
 2515:     $remoteVERSION=(split(/:/,$userinput))[1];
 2516:     return "version:$VERSION";
 2517: }
 2518: 
 2519: #There is a copy of this in lonnet.pm
 2520: sub userload {
 2521:     my $numusers=0;
 2522:     {
 2523: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
 2524: 	my $filename;
 2525: 	my $curtime=time;
 2526: 	while ($filename=readdir(LONIDS)) {
 2527: 	    if ($filename eq '.' || $filename eq '..') {next;}
 2528: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
 2529: 	    if ($curtime-$mtime < 3600) { $numusers++; }
 2530: 	}
 2531: 	closedir(LONIDS);
 2532:     }
 2533:     my $userloadpercent=0;
 2534:     my $maxuserload=$perlvar{'lonUserLoadLim'};
 2535:     if ($maxuserload) {
 2536: 	$userloadpercent=100*$numusers/$maxuserload;
 2537:     }
 2538:     $userloadpercent=sprintf("%.2f",$userloadpercent);
 2539:     return $userloadpercent;
 2540: }
 2541: 
 2542: # ----------------------------------- POD (plain old documentation, CPAN style)
 2543: 
 2544: =head1 NAME
 2545: 
 2546: lond - "LON Daemon" Server (port "LOND" 5663)
 2547: 
 2548: =head1 SYNOPSIS
 2549: 
 2550: Usage: B<lond>
 2551: 
 2552: Should only be run as user=www.  This is a command-line script which
 2553: is invoked by B<loncron>.  There is no expectation that a typical user
 2554: will manually start B<lond> from the command-line.  (In other words,
 2555: DO NOT START B<lond> YOURSELF.)
 2556: 
 2557: =head1 DESCRIPTION
 2558: 
 2559: There are two characteristics associated with the running of B<lond>,
 2560: PROCESS MANAGEMENT (starting, stopping, handling child processes)
 2561: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
 2562: subscriptions, etc).  These are described in two large
 2563: sections below.
 2564: 
 2565: B<PROCESS MANAGEMENT>
 2566: 
 2567: Preforker - server who forks first. Runs as a daemon. HUPs.
 2568: Uses IDEA encryption
 2569: 
 2570: B<lond> forks off children processes that correspond to the other servers
 2571: in the network.  Management of these processes can be done at the
 2572: parent process level or the child process level.
 2573: 
 2574: B<logs/lond.log> is the location of log messages.
 2575: 
 2576: The process management is now explained in terms of linux shell commands,
 2577: subroutines internal to this code, and signal assignments:
 2578: 
 2579: =over 4
 2580: 
 2581: =item *
 2582: 
 2583: PID is stored in B<logs/lond.pid>
 2584: 
 2585: This is the process id number of the parent B<lond> process.
 2586: 
 2587: =item *
 2588: 
 2589: SIGTERM and SIGINT
 2590: 
 2591: Parent signal assignment:
 2592:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 2593: 
 2594: Child signal assignment:
 2595:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
 2596: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
 2597:  to restart a new child.)
 2598: 
 2599: Command-line invocations:
 2600:  B<kill> B<-s> SIGTERM I<PID>
 2601:  B<kill> B<-s> SIGINT I<PID>
 2602: 
 2603: Subroutine B<HUNTSMAN>:
 2604:  This is only invoked for the B<lond> parent I<PID>.
 2605: This kills all the children, and then the parent.
 2606: The B<lonc.pid> file is cleared.
 2607: 
 2608: =item *
 2609: 
 2610: SIGHUP
 2611: 
 2612: Current bug:
 2613:  This signal can only be processed the first time
 2614: on the parent process.  Subsequent SIGHUP signals
 2615: have no effect.
 2616: 
 2617: Parent signal assignment:
 2618:  $SIG{HUP}  = \&HUPSMAN;
 2619: 
 2620: Child signal assignment:
 2621:  none (nothing happens)
 2622: 
 2623: Command-line invocations:
 2624:  B<kill> B<-s> SIGHUP I<PID>
 2625: 
 2626: Subroutine B<HUPSMAN>:
 2627:  This is only invoked for the B<lond> parent I<PID>,
 2628: This kills all the children, and then the parent.
 2629: The B<lond.pid> file is cleared.
 2630: 
 2631: =item *
 2632: 
 2633: SIGUSR1
 2634: 
 2635: Parent signal assignment:
 2636:  $SIG{USR1} = \&USRMAN;
 2637: 
 2638: Child signal assignment:
 2639:  $SIG{USR1}= \&logstatus;
 2640: 
 2641: Command-line invocations:
 2642:  B<kill> B<-s> SIGUSR1 I<PID>
 2643: 
 2644: Subroutine B<USRMAN>:
 2645:  When invoked for the B<lond> parent I<PID>,
 2646: SIGUSR1 is sent to all the children, and the status of
 2647: each connection is logged.
 2648: 
 2649: =item *
 2650: 
 2651: SIGUSR2
 2652: 
 2653: Parent Signal assignment:
 2654:     $SIG{USR2} = \&UpdateHosts
 2655: 
 2656: Child signal assignment:
 2657:     NONE
 2658: 
 2659: 
 2660: =item *
 2661: 
 2662: SIGCHLD
 2663: 
 2664: Parent signal assignment:
 2665:  $SIG{CHLD} = \&REAPER;
 2666: 
 2667: Child signal assignment:
 2668:  none
 2669: 
 2670: Command-line invocations:
 2671:  B<kill> B<-s> SIGCHLD I<PID>
 2672: 
 2673: Subroutine B<REAPER>:
 2674:  This is only invoked for the B<lond> parent I<PID>.
 2675: Information pertaining to the child is removed.
 2676: The socket port is cleaned up.
 2677: 
 2678: =back
 2679: 
 2680: B<SERVER-SIDE ACTIVITIES>
 2681: 
 2682: Server-side information can be accepted in an encrypted or non-encrypted
 2683: method.
 2684: 
 2685: =over 4
 2686: 
 2687: =item ping
 2688: 
 2689: Query a client in the hosts.tab table; "Are you there?"
 2690: 
 2691: =item pong
 2692: 
 2693: Respond to a ping query.
 2694: 
 2695: =item ekey
 2696: 
 2697: Read in encrypted key, make cipher.  Respond with a buildkey.
 2698: 
 2699: =item load
 2700: 
 2701: Respond with CPU load based on a computation upon /proc/loadavg.
 2702: 
 2703: =item currentauth
 2704: 
 2705: Reply with current authentication information (only over an
 2706: encrypted channel).
 2707: 
 2708: =item auth
 2709: 
 2710: Only over an encrypted channel, reply as to whether a user's
 2711: authentication information can be validated.
 2712: 
 2713: =item passwd
 2714: 
 2715: Allow for a password to be set.
 2716: 
 2717: =item makeuser
 2718: 
 2719: Make a user.
 2720: 
 2721: =item passwd
 2722: 
 2723: Allow for authentication mechanism and password to be changed.
 2724: 
 2725: =item home
 2726: 
 2727: Respond to a question "are you the home for a given user?"
 2728: 
 2729: =item update
 2730: 
 2731: Update contents of a subscribed resource.
 2732: 
 2733: =item unsubscribe
 2734: 
 2735: The server is unsubscribing from a resource.
 2736: 
 2737: =item subscribe
 2738: 
 2739: The server is subscribing to a resource.
 2740: 
 2741: =item log
 2742: 
 2743: Place in B<logs/lond.log>
 2744: 
 2745: =item put
 2746: 
 2747: stores hash in namespace
 2748: 
 2749: =item rolesput
 2750: 
 2751: put a role into a user's environment
 2752: 
 2753: =item get
 2754: 
 2755: returns hash with keys from array
 2756: reference filled in from namespace
 2757: 
 2758: =item eget
 2759: 
 2760: returns hash with keys from array
 2761: reference filled in from namesp (encrypts the return communication)
 2762: 
 2763: =item rolesget
 2764: 
 2765: get a role from a user's environment
 2766: 
 2767: =item del
 2768: 
 2769: deletes keys out of array from namespace
 2770: 
 2771: =item keys
 2772: 
 2773: returns namespace keys
 2774: 
 2775: =item dump
 2776: 
 2777: dumps the complete (or key matching regexp) namespace into a hash
 2778: 
 2779: =item store
 2780: 
 2781: stores hash permanently
 2782: for this url; hashref needs to be given and should be a \%hashname; the
 2783: remaining args aren't required and if they aren't passed or are '' they will
 2784: be derived from the ENV
 2785: 
 2786: =item restore
 2787: 
 2788: returns a hash for a given url
 2789: 
 2790: =item querysend
 2791: 
 2792: Tells client about the lonsql process that has been launched in response
 2793: to a sent query.
 2794: 
 2795: =item queryreply
 2796: 
 2797: Accept information from lonsql and make appropriate storage in temporary
 2798: file space.
 2799: 
 2800: =item idput
 2801: 
 2802: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
 2803: for each student, defined perhaps by the institutional Registrar.)
 2804: 
 2805: =item idget
 2806: 
 2807: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
 2808: for each student, defined perhaps by the institutional Registrar.)
 2809: 
 2810: =item tmpput
 2811: 
 2812: Accept and store information in temporary space.
 2813: 
 2814: =item tmpget
 2815: 
 2816: Send along temporarily stored information.
 2817: 
 2818: =item ls
 2819: 
 2820: List part of a user's directory.
 2821: 
 2822: =item pushtable
 2823: 
 2824: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
 2825: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
 2826: must be restored manually in case of a problem with the new table file.
 2827: pushtable requires that the request be encrypted and validated via
 2828: ValidateManager.  The form of the command is:
 2829: enc:pushtable tablename <tablecontents> \n
 2830: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
 2831: cleartext newline.
 2832: 
 2833: =item Hanging up (exit or init)
 2834: 
 2835: What to do when a client tells the server that they (the client)
 2836: are leaving the network.
 2837: 
 2838: =item unknown command
 2839: 
 2840: If B<lond> is sent an unknown command (not in the list above),
 2841: it replys to the client "unknown_cmd".
 2842: 
 2843: 
 2844: =item UNKNOWN CLIENT
 2845: 
 2846: If the anti-spoofing algorithm cannot verify the client,
 2847: the client is rejected (with a "refused" message sent
 2848: to the client, and the connection is closed.
 2849: 
 2850: =back
 2851: 
 2852: =head1 PREREQUISITES
 2853: 
 2854: IO::Socket
 2855: IO::File
 2856: Apache::File
 2857: Symbol
 2858: POSIX
 2859: Crypt::IDEA
 2860: LWP::UserAgent()
 2861: GDBM_File
 2862: Authen::Krb4
 2863: Authen::Krb5
 2864: 
 2865: =head1 COREQUISITES
 2866: 
 2867: =head1 OSNAMES
 2868: 
 2869: linux
 2870: 
 2871: =head1 SCRIPT CATEGORIES
 2872: 
 2873: Server/Process
 2874: 
 2875: =cut

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