File:  [LON-CAPA] / loncom / lond
Revision 1.157: download - view: text, annotated - select for diffs
Tue Oct 14 10:15:27 2003 UTC (20 years, 6 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Supported rewrite of hosts.tab on the fly so that the local host's ip
can be correct if it's hiding behind a masquerading network device such as a
firewall.

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

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