File:  [LON-CAPA] / loncom / lond
Revision 1.180: download - view: text, annotated - select for diffs
Mon Mar 8 20:59:41 2004 UTC (20 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: HEAD
- lond has been dieing on my machine, I think due to port probes trying to defend against an invalid connection

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

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