File:  [LON-CAPA] / loncom / lond
Revision 1.169: download - view: text, annotated - select for diffs
Tue Dec 30 11:28:16 2003 UTC (20 years, 10 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Debug editing support for configuration files.

    1: #!/usr/bin/perl
    2: # The LearningOnline Network
    3: # lond "LON Daemon" Server (port "LOND" 5663)
    4: #
    5: # $Id: lond,v 1.169 2003/12/30 11:28:16 foxr Exp $
    6: #
    7: # Copyright Michigan State University Board of Trustees
    8: #
    9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
   10: #
   11: # LON-CAPA is free software; you can redistribute it and/or modify
   12: # it under the terms of the GNU General Public License as published by
   13: # the Free Software Foundation; either version 2 of the License, or 
   14: # (at your option) any later version.
   15: #
   16: # LON-CAPA is distributed in the hope that it will be useful,
   17: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   18: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   19: # GNU General Public License for more details.
   20: #
   21: # You should have received a copy of the GNU General Public License
   22: # along with LON-CAPA; if not, write to the Free Software
   23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   24: #
   25: # /home/httpd/html/adm/gpl.txt
   26: #
   27: 
   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.169 $'; #' 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: my $children               = 0;        # current number of children
  816: 
  817: sub REAPER {                        # takes care of dead children
  818:     $SIG{CHLD} = \&REAPER;
  819:     &status("Handling child death");
  820:     my $pid = wait;
  821:     if (defined($children{$pid})) {
  822: 	&logthis("Child $pid died");
  823: 	$children --;
  824: 	delete $children{$pid};
  825:     } else {
  826: 	&logthis("Unknown Child $pid died");
  827:     }
  828:     &status("Finished Handling child death");
  829: }
  830: 
  831: sub HUNTSMAN {                      # signal handler for SIGINT
  832:     &status("Killing children (INT)");
  833:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
  834:     kill 'INT' => keys %children;
  835:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
  836:     my $execdir=$perlvar{'lonDaemons'};
  837:     unlink("$execdir/logs/lond.pid");
  838:     &logthis("<font color=red>CRITICAL: Shutting down</font>");
  839:     &status("Done killing children");
  840:     exit;                           # clean up with dignity
  841: }
  842: 
  843: sub HUPSMAN {                      # signal handler for SIGHUP
  844:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
  845:     &status("Killing children for restart (HUP)");
  846:     kill 'INT' => keys %children;
  847:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
  848:     &logthis("<font color=red>CRITICAL: Restarting</font>");
  849:     my $execdir=$perlvar{'lonDaemons'};
  850:     unlink("$execdir/logs/lond.pid");
  851:     &status("Restarting self (HUP)");
  852:     exec("$execdir/lond");         # here we go again
  853: }
  854: 
  855: #
  856: #    Kill off hashes that describe the host table prior to re-reading it.
  857: #    Hashes affected are:
  858: #       %hostid, %hostdom %hostip
  859: #
  860: sub KillHostHashes {
  861:     foreach my $key (keys %hostid) {
  862: 	delete $hostid{$key};
  863:     }
  864:     foreach my $key (keys %hostdom) {
  865: 	delete $hostdom{$key};
  866:     }
  867:     foreach my $key (keys %hostip) {
  868: 	delete $hostip{$key};
  869:     }
  870: }
  871: #
  872: #   Read in the host table from file and distribute it into the various hashes:
  873: #
  874: #    - %hostid  -  Indexed by IP, the loncapa hostname.
  875: #    - %hostdom -  Indexed by  loncapa hostname, the domain.
  876: #    - %hostip  -  Indexed by hostid, the Ip address of the host.
  877: sub ReadHostTable {
  878: 
  879:     open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
  880:     
  881:     while (my $configline=<CONFIG>) {
  882: 	my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
  883: 	chomp($ip); $ip=~s/\D+$//;
  884: 	$hostid{$ip}=$id;
  885: 	$hostdom{$id}=$domain;
  886: 	$hostip{$id}=$ip;
  887: 	if ($id eq $perlvar{'lonHostID'}) { $thisserver=$name; }
  888:     }
  889:     close(CONFIG);
  890: }
  891: #
  892: #  Reload the Apache daemon's state.
  893: #  This is done by invoking /home/httpd/perl/apachereload
  894: #  a setuid perl script that can be root for us to do this job.
  895: #
  896: sub ReloadApache {
  897:     my $execdir = $perlvar{'lonDaemons'};
  898:     my $script  = $execdir."/apachereload";
  899:     system($script);
  900: }
  901: 
  902: #
  903: #   Called in response to a USR2 signal.
  904: #   - Reread hosts.tab
  905: #   - All children connected to hosts that were removed from hosts.tab
  906: #     are killed via SIGINT
  907: #   - All children connected to previously existing hosts are sent SIGUSR1
  908: #   - Our internal hosts hash is updated to reflect the new contents of
  909: #     hosts.tab causing connections from hosts added to hosts.tab to
  910: #     now be honored.
  911: #
  912: sub UpdateHosts {
  913:     &status("Reload hosts.tab");
  914:     logthis('<font color="blue"> Updating connections </font>');
  915:     #
  916:     #  The %children hash has the set of IP's we currently have children
  917:     #  on.  These need to be matched against records in the hosts.tab
  918:     #  Any ip's no longer in the table get killed off they correspond to
  919:     #  either dropped or changed hosts.  Note that the re-read of the table
  920:     #  will take care of new and changed hosts as connections come into being.
  921: 
  922: 
  923:     KillHostHashes;
  924:     ReadHostTable;
  925: 
  926:     foreach my $child (keys %children) {
  927: 	my $childip = $children{$child};
  928: 	if(!$hostid{$childip}) {
  929: 	    logthis('<font color="blue"> UpdateHosts killing child '
  930: 		    ." $child for ip $childip </font>");
  931: 	    kill('INT', $child);
  932: 	} else {
  933: 	    logthis('<font color="green"> keeping child for ip '
  934: 		    ." $childip (pid=$child) </font>");
  935: 	}
  936:     }
  937:     ReloadApache;
  938:     &status("Finished reloading hosts.tab");
  939: }
  940: 
  941: 
  942: sub checkchildren {
  943:     &status("Checking on the children (sending signals)");
  944:     &initnewstatus();
  945:     &logstatus();
  946:     &logthis('Going to check on the children');
  947:     my $docdir=$perlvar{'lonDocRoot'};
  948:     foreach (sort keys %children) {
  949: 	sleep 1;
  950:         unless (kill 'USR1' => $_) {
  951: 	    &logthis ('Child '.$_.' is dead');
  952:             &logstatus($$.' is dead');
  953:         } 
  954:     }
  955:     sleep 5;
  956:     $SIG{ALRM} = sub { die "timeout" };
  957:     $SIG{__DIE__} = 'DEFAULT';
  958:     &status("Checking on the children (waiting for reports)");
  959:     foreach (sort keys %children) {
  960:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
  961:           eval {
  962:             alarm(300);
  963: 	    &logthis('Child '.$_.' did not respond');
  964: 	    kill 9 => $_;
  965: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
  966: 	    #$subj="LON: $currenthostid killed lond process $_";
  967: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
  968: 	    #$execdir=$perlvar{'lonDaemons'};
  969: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
  970: 	    alarm(0);
  971: 	  }
  972:         }
  973:     }
  974:     $SIG{ALRM} = 'DEFAULT';
  975:     $SIG{__DIE__} = \&catchexception;
  976:     &status("Finished checking children");
  977: }
  978: 
  979: # --------------------------------------------------------------------- Logging
  980: 
  981: sub logthis {
  982:     my $message=shift;
  983:     my $execdir=$perlvar{'lonDaemons'};
  984:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
  985:     my $now=time;
  986:     my $local=localtime($now);
  987:     $lastlog=$local.': '.$message;
  988:     print $fh "$local ($$): $message\n";
  989: }
  990: 
  991: # ------------------------- Conditional log if $DEBUG true.
  992: sub Debug {
  993:     my $message = shift;
  994:     if($DEBUG) {
  995: 	&logthis($message);
  996:     }
  997: }
  998: 
  999: #
 1000: #   Sub to do replies to client.. this gives a hook for some
 1001: #   debug tracing too:
 1002: #  Parameters:
 1003: #     fd      - File open on client.
 1004: #     reply   - Text to send to client.
 1005: #     request - Original request from client.
 1006: #
 1007: sub Reply {
 1008:     my $fd      = shift;
 1009:     my $reply   = shift;
 1010:     my $request = shift;
 1011: 
 1012:     print $fd $reply;
 1013:     Debug("Request was $request  Reply was $reply");
 1014: 
 1015: }
 1016: # ------------------------------------------------------------------ Log status
 1017: 
 1018: sub logstatus {
 1019:     &status("Doing logging");
 1020:     my $docdir=$perlvar{'lonDocRoot'};
 1021:     {
 1022:     my $fh=IO::File->new(">>$docdir/lon-status/londstatus.txt");
 1023:     print $fh $$."\t".$currenthostid."\t".$status."\t".$lastlog."\n";
 1024:     $fh->close();
 1025:     }
 1026:     &status("Finished londstatus.txt");
 1027:     {
 1028: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
 1029:         print $fh $status."\n".$lastlog."\n".time;
 1030:         $fh->close();
 1031:     }
 1032:     &status("Finished logging");
 1033: }
 1034: 
 1035: sub initnewstatus {
 1036:     my $docdir=$perlvar{'lonDocRoot'};
 1037:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
 1038:     my $now=time;
 1039:     my $local=localtime($now);
 1040:     print $fh "LOND status $local - parent $$\n\n";
 1041:     opendir(DIR,"$docdir/lon-status/londchld");
 1042:     while (my $filename=readdir(DIR)) {
 1043:         unlink("$docdir/lon-status/londchld/$filename");
 1044:     }
 1045:     closedir(DIR);
 1046: }
 1047: 
 1048: # -------------------------------------------------------------- Status setting
 1049: 
 1050: sub status {
 1051:     my $what=shift;
 1052:     my $now=time;
 1053:     my $local=localtime($now);
 1054:     $status=$local.': '.$what;
 1055:     $0='lond: '.$what.' '.$local;
 1056: }
 1057: 
 1058: # -------------------------------------------------------- Escape Special Chars
 1059: 
 1060: sub escape {
 1061:     my $str=shift;
 1062:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
 1063:     return $str;
 1064: }
 1065: 
 1066: # ----------------------------------------------------- Un-Escape Special Chars
 1067: 
 1068: sub unescape {
 1069:     my $str=shift;
 1070:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 1071:     return $str;
 1072: }
 1073: 
 1074: # ----------------------------------------------------------- Send USR1 to lonc
 1075: 
 1076: sub reconlonc {
 1077:     my $peerfile=shift;
 1078:     &logthis("Trying to reconnect for $peerfile");
 1079:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
 1080:     if (my $fh=IO::File->new("$loncfile")) {
 1081: 	my $loncpid=<$fh>;
 1082:         chomp($loncpid);
 1083:         if (kill 0 => $loncpid) {
 1084: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
 1085:             kill USR1 => $loncpid;
 1086:         } else {
 1087: 	    &logthis(
 1088:               "<font color=red>CRITICAL: "
 1089:              ."lonc at pid $loncpid not responding, giving up</font>");
 1090:         }
 1091:     } else {
 1092:       &logthis('<font color=red>CRITICAL: lonc not running, giving up</font>');
 1093:     }
 1094: }
 1095: 
 1096: # -------------------------------------------------- Non-critical communication
 1097: 
 1098: sub subreply {
 1099:     my ($cmd,$server)=@_;
 1100:     my $peerfile="$perlvar{'lonSockDir'}/$server";
 1101:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
 1102:                                       Type    => SOCK_STREAM,
 1103:                                       Timeout => 10)
 1104:        or return "con_lost";
 1105:     print $sclient "$cmd\n";
 1106:     my $answer=<$sclient>;
 1107:     chomp($answer);
 1108:     if (!$answer) { $answer="con_lost"; }
 1109:     return $answer;
 1110: }
 1111: 
 1112: sub reply {
 1113:   my ($cmd,$server)=@_;
 1114:   my $answer;
 1115:   if ($server ne $currenthostid) { 
 1116:     $answer=subreply($cmd,$server);
 1117:     if ($answer eq 'con_lost') {
 1118: 	$answer=subreply("ping",$server);
 1119:         if ($answer ne $server) {
 1120: 	    &logthis("sub reply: answer != server answer is $answer, server is $server");
 1121:            &reconlonc("$perlvar{'lonSockDir'}/$server");
 1122:         }
 1123:         $answer=subreply($cmd,$server);
 1124:     }
 1125:   } else {
 1126:     $answer='self_reply';
 1127:   } 
 1128:   return $answer;
 1129: }
 1130: 
 1131: # -------------------------------------------------------------- Talk to lonsql
 1132: 
 1133: sub sqlreply {
 1134:     my ($cmd)=@_;
 1135:     my $answer=subsqlreply($cmd);
 1136:     if ($answer eq 'con_lost') { $answer=subsqlreply($cmd); }
 1137:     return $answer;
 1138: }
 1139: 
 1140: sub subsqlreply {
 1141:     my ($cmd)=@_;
 1142:     my $unixsock="mysqlsock";
 1143:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
 1144:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
 1145:                                       Type    => SOCK_STREAM,
 1146:                                       Timeout => 10)
 1147:        or return "con_lost";
 1148:     print $sclient "$cmd\n";
 1149:     my $answer=<$sclient>;
 1150:     chomp($answer);
 1151:     if (!$answer) { $answer="con_lost"; }
 1152:     return $answer;
 1153: }
 1154: 
 1155: # -------------------------------------------- Return path to profile directory
 1156: 
 1157: sub propath {
 1158:     my ($udom,$uname)=@_;
 1159:     $udom=~s/\W//g;
 1160:     $uname=~s/\W//g;
 1161:     my $subdir=$uname.'__';
 1162:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 1163:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
 1164:     return $proname;
 1165: } 
 1166: 
 1167: # --------------------------------------- Is this the home server of an author?
 1168: 
 1169: sub ishome {
 1170:     my $author=shift;
 1171:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1172:     my ($udom,$uname)=split(/\//,$author);
 1173:     my $proname=propath($udom,$uname);
 1174:     if (-e $proname) {
 1175: 	return 'owner';
 1176:     } else {
 1177:         return 'not_owner';
 1178:     }
 1179: }
 1180: 
 1181: # ======================================================= Continue main program
 1182: # ---------------------------------------------------- Fork once and dissociate
 1183: 
 1184: my $fpid=fork;
 1185: exit if $fpid;
 1186: die "Couldn't fork: $!" unless defined ($fpid);
 1187: 
 1188: POSIX::setsid() or die "Can't start new session: $!";
 1189: 
 1190: # ------------------------------------------------------- Write our PID on disk
 1191: 
 1192: my $execdir=$perlvar{'lonDaemons'};
 1193: open (PIDSAVE,">$execdir/logs/lond.pid");
 1194: print PIDSAVE "$$\n";
 1195: close(PIDSAVE);
 1196: &logthis("<font color=red>CRITICAL: ---------- Starting ----------</font>");
 1197: &status('Starting');
 1198: 
 1199: 
 1200: 
 1201: # ----------------------------------------------------- Install signal handlers
 1202: 
 1203: 
 1204: $SIG{CHLD} = \&REAPER;
 1205: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 1206: $SIG{HUP}  = \&HUPSMAN;
 1207: $SIG{USR1} = \&checkchildren;
 1208: $SIG{USR2} = \&UpdateHosts;
 1209: 
 1210: #  Read the host hashes:
 1211: 
 1212: ReadHostTable;
 1213: 
 1214: # --------------------------------------------------------------
 1215: #   Accept connections.  When a connection comes in, it is validated
 1216: #   and if good, a child process is created to process transactions
 1217: #   along the connection.
 1218: 
 1219: while (1) {
 1220:     &status('Starting accept');
 1221:     $client = $server->accept() or next;
 1222:     &status('Accepted '.$client.' off to spawn');
 1223:     make_new_child($client);
 1224:     &status('Finished spawning');
 1225: }
 1226: 
 1227: sub make_new_child {
 1228:     my $pid;
 1229:     my $cipher;
 1230:     my $sigset;
 1231: 
 1232:     $client = shift;
 1233:     &status('Starting new child '.$client);
 1234:     &logthis('<font color="green"> Attempting to start child ('.$client.
 1235: 	     ")</font>");    
 1236:     # block signal for fork
 1237:     $sigset = POSIX::SigSet->new(SIGINT);
 1238:     sigprocmask(SIG_BLOCK, $sigset)
 1239:         or die "Can't block SIGINT for fork: $!\n";
 1240: 
 1241:     die "fork: $!" unless defined ($pid = fork);
 1242: 
 1243:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
 1244: 	                               # connection liveness.
 1245: 
 1246:     #
 1247:     #  Figure out who we're talking to so we can record the peer in 
 1248:     #  the pid hash.
 1249:     #
 1250:     my $caller = getpeername($client);
 1251:     my ($port,$iaddr)=unpack_sockaddr_in($caller);
 1252:     $clientip=inet_ntoa($iaddr);
 1253:     
 1254:     if ($pid) {
 1255:         # Parent records the child's birth and returns.
 1256:         sigprocmask(SIG_UNBLOCK, $sigset)
 1257:             or die "Can't unblock SIGINT for fork: $!\n";
 1258:         $children{$pid} = $clientip;
 1259:         $children++;
 1260:         &status('Started child '.$pid);
 1261:         return;
 1262:     } else {
 1263:         # Child can *not* return from this subroutine.
 1264:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
 1265:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
 1266:                                 #don't get intercepted
 1267:         $SIG{USR1}= \&logstatus;
 1268:         $SIG{ALRM}= \&timeout;
 1269:         $lastlog='Forked ';
 1270:         $status='Forked';
 1271: 
 1272:         # unblock signals
 1273:         sigprocmask(SIG_UNBLOCK, $sigset)
 1274:             or die "Can't unblock SIGINT for fork: $!\n";
 1275: 
 1276:         my $tmpsnum=0;
 1277: #---------------------------------------------------- kerberos 5 initialization
 1278:         &Authen::Krb5::init_context();
 1279:         &Authen::Krb5::init_ets();
 1280: 
 1281: 	&status('Accepted connection');
 1282: # =============================================================================
 1283:             # do something with the connection
 1284: # -----------------------------------------------------------------------------
 1285: 	# see if we know client and check for spoof IP by challenge
 1286: 
 1287: 	ReadManagerTable;	# May also be a manager!!
 1288: 	
 1289: 	my $clientrec=($hostid{$clientip}     ne undef);
 1290: 	my $ismanager=($managers{$clientip}    ne undef);
 1291: 	$clientname  = "[unknonwn]";
 1292: 	if($clientrec) {	# Establish client type.
 1293: 	    $ConnectionType = "client";
 1294: 	    $clientname = $hostid{$clientip};
 1295: 	    if($ismanager) {
 1296: 		$ConnectionType = "both";
 1297: 	    }
 1298: 	} else {
 1299: 	    $ConnectionType = "manager";
 1300: 	    $clientname = $managers{$clientip};
 1301: 	}
 1302: 	my $clientok;
 1303: 	if ($clientrec || $ismanager) {
 1304: 	    &status("Waiting for init from $clientip $clientname");
 1305: 	    &logthis('<font color="yellow">INFO: Connection, '.
 1306: 		     $clientip.
 1307: 		  " ($clientname) connection type = $ConnectionType </font>" );
 1308: 	    &status("Connecting $clientip  ($clientname))"); 
 1309: 	    my $remotereq=<$client>;
 1310: 	    $remotereq=~s/[^\w:]//g;
 1311: 	    if ($remotereq =~ /^init/) {
 1312: 		&sethost("sethost:$perlvar{'lonHostID'}");
 1313: 		my $challenge="$$".time;
 1314: 		print $client "$challenge\n";
 1315: 		&status(
 1316: 			"Waiting for challenge reply from $clientip ($clientname)"); 
 1317: 		$remotereq=<$client>;
 1318: 		$remotereq=~s/\W//g;
 1319: 		if ($challenge eq $remotereq) {
 1320: 		    $clientok=1;
 1321: 		    print $client "ok\n";
 1322: 		} else {
 1323: 		    &logthis(
 1324: 			     "<font color=blue>WARNING: $clientip did not reply challenge</font>");
 1325: 		    &status('No challenge reply '.$clientip);
 1326: 		}
 1327: 	    } else {
 1328: 		&logthis(
 1329: 			 "<font color=blue>WARNING: "
 1330: 			 ."$clientip failed to initialize: >$remotereq< </font>");
 1331: 		&status('No init '.$clientip);
 1332: 	    }
 1333: 	} else {
 1334: 	    &logthis(
 1335: 		     "<font color=blue>WARNING: Unknown client $clientip</font>");
 1336: 	    &status('Hung up on '.$clientip);
 1337: 	}
 1338: 	if ($clientok) {
 1339: # ---------------- New known client connecting, could mean machine online again
 1340: 	    
 1341: 	    foreach my $id (keys(%hostip)) {
 1342: 		if ($hostip{$id} ne $clientip ||
 1343: 		    $hostip{$currenthostid} eq $clientip) {
 1344: 		    # no need to try to do recon's to myself
 1345: 		    next;
 1346: 		}
 1347: 		&reconlonc("$perlvar{'lonSockDir'}/$id");
 1348: 	    }
 1349: 	    &logthis("<font color=green>Established connection: $clientname</font>");
 1350: 	    &status('Will listen to '.$clientname);
 1351: # ------------------------------------------------------------ Process requests
 1352: 	    while (my $userinput=<$client>) {
 1353:                 chomp($userinput);
 1354: 		Debug("Request = $userinput\n");
 1355:                 &status('Processing '.$clientname.': '.$userinput);
 1356:                 my $wasenc=0;
 1357:                 alarm(120);
 1358: # ------------------------------------------------------------ See if encrypted
 1359: 		if ($userinput =~ /^enc/) {
 1360: 		    if ($cipher) {
 1361: 			my ($cmd,$cmdlength,$encinput)=split(/:/,$userinput);
 1362: 			$userinput='';
 1363: 			for (my $encidx=0;$encidx<length($encinput);$encidx+=16) {
 1364: 			    $userinput.=
 1365: 				$cipher->decrypt(
 1366: 						 pack("H16",substr($encinput,$encidx,16))
 1367: 						 );
 1368: 			}
 1369: 			$userinput=substr($userinput,0,$cmdlength);
 1370: 			$wasenc=1;
 1371: 		    }
 1372: 		}
 1373: 		
 1374: # ------------------------------------------------------------- Normal commands
 1375: # ------------------------------------------------------------------------ ping
 1376: 		if ($userinput =~ /^ping/) {	# client only
 1377: 		    if(isClient) {
 1378: 			print $client "$currenthostid\n";
 1379: 		    } else {
 1380: 			Reply($client, "refused\n", $userinput);
 1381: 		    }
 1382: # ------------------------------------------------------------------------ pong
 1383: 		}elsif ($userinput =~ /^pong/) { # client only
 1384: 		    if(isClient) {
 1385: 			my $reply=&reply("ping",$clientname);
 1386: 			print $client "$currenthostid:$reply\n"; 
 1387: 		    } else {
 1388: 			Reply($client, "refused\n", $userinput);
 1389: 		    }
 1390: # ------------------------------------------------------------------------ ekey
 1391: 		} elsif ($userinput =~ /^ekey/) { # ok for both clients & mgrs
 1392: 		    my $buildkey=time.$$.int(rand 100000);
 1393: 		    $buildkey=~tr/1-6/A-F/;
 1394: 		    $buildkey=int(rand 100000).$buildkey.int(rand 100000);
 1395: 		    my $key=$currenthostid.$clientname;
 1396: 		    $key=~tr/a-z/A-Z/;
 1397: 		    $key=~tr/G-P/0-9/;
 1398: 		    $key=~tr/Q-Z/0-9/;
 1399: 		    $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
 1400: 		    $key=substr($key,0,32);
 1401: 		    my $cipherkey=pack("H32",$key);
 1402: 		    $cipher=new IDEA $cipherkey;
 1403: 		    print $client "$buildkey\n"; 
 1404: # ------------------------------------------------------------------------ load
 1405: 		} elsif ($userinput =~ /^load/) { # client only
 1406: 		    if (isClient) {
 1407: 			my $loadavg;
 1408: 			{
 1409: 			    my $loadfile=IO::File->new('/proc/loadavg');
 1410: 			    $loadavg=<$loadfile>;
 1411: 			}
 1412: 			$loadavg =~ s/\s.*//g;
 1413: 			my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
 1414: 			print $client "$loadpercent\n";
 1415: 		    } else {
 1416: 			Reply($client, "refused\n", $userinput);
 1417: 	       
 1418: 		    }
 1419: # -------------------------------------------------------------------- userload
 1420: 		} elsif ($userinput =~ /^userload/) { # client only
 1421: 		    if(isClient) {
 1422: 			my $userloadpercent=&userload();
 1423: 			print $client "$userloadpercent\n";
 1424: 		    } else {
 1425: 			Reply($client, "refused\n", $userinput);
 1426: 		     
 1427: 		    }
 1428: #
 1429: #        Transactions requiring encryption:
 1430: #
 1431: # ----------------------------------------------------------------- currentauth
 1432: 		} elsif ($userinput =~ /^currentauth/) {
 1433: 		    if (($wasenc==1)  && isClient) { # Encoded & client only.
 1434: 			my ($cmd,$udom,$uname)=split(/:/,$userinput);
 1435: 			my $result = GetAuthType($udom, $uname);
 1436: 			if($result eq "nouser") {
 1437: 			    print $client "unknown_user\n";
 1438: 			}
 1439: 			else {
 1440: 			    print $client "$result\n"
 1441: 			    }
 1442: 		    } else {
 1443: 			Reply($client, "refused\n", $userinput);
 1444: 			
 1445: 		    }
 1446: #--------------------------------------------------------------------- pushfile
 1447: 		} elsif($userinput =~ /^pushfile/) {	# encoded & manager.
 1448: 		    if(($wasenc == 1) && isManager) {
 1449: 			my $cert = GetCertificate($userinput);
 1450: 			if(ValidManager($cert)) {
 1451: 			    my $reply = PushFile($userinput);
 1452: 			    print $client "$reply\n";
 1453: 			} else {
 1454: 			    print $client "refused\n";
 1455: 			} 
 1456: 		    } else {
 1457: 			Reply($client, "refused\n", $userinput);
 1458: 			
 1459: 		    }
 1460: #--------------------------------------------------------------------- reinit
 1461: 		} elsif($userinput =~ /^reinit/) { # Encoded and manager
 1462: 			if (($wasenc == 1) && isManager) {
 1463: 				my $cert = GetCertificate($userinput);
 1464: 				if(ValidManager($cert)) {
 1465: 					chomp($userinput);
 1466: 					my $reply = ReinitProcess($userinput);
 1467: 					print $client  "$reply\n";
 1468: 				} else {
 1469: 					 print $client "refused\n";
 1470: 				}
 1471: 			} else {
 1472: 				Reply($client, "refused\n", $userinput);
 1473: 			}
 1474: #------------------------------------------------------------------------- edit
 1475: 		    } elsif ($userinput =~ /^edit/) {    # encoded and manager:
 1476: 			if(($wasenc ==1) && (isManager)) {
 1477: 			    my $cert = GetCertificate($userinput);
 1478: 			    if(ValidManager($cert)) {
 1479:                my($command, $filetype, $script) = split(/:/, $userinput);
 1480:                if (($filetype eq "hosts") || ($filetype eq "domain")) {
 1481:                   if($script ne "") {
 1482: 		      Reply($client, EditFile($userinput));
 1483:                   } else {
 1484:                      Reply($client,"refused\n",$userinput);
 1485:                   }
 1486:                } else {
 1487:                   Reply($client,"refused\n",$userinput);
 1488:                }
 1489:             } else {
 1490:                Reply($client,"refused\n",$userinput);
 1491:             }
 1492:          } else {
 1493: 	     Reply($client,"refused\n",$userinput);
 1494: 	 }
 1495: # ------------------------------------------------------------------------ auth
 1496: 		    } elsif ($userinput =~ /^auth/) { # Encoded and client only.
 1497: 		    if (($wasenc==1) && isClient) {
 1498: 			my ($cmd,$udom,$uname,$upass)=split(/:/,$userinput);
 1499: 			chomp($upass);
 1500: 			$upass=unescape($upass);
 1501: 			my $proname=propath($udom,$uname);
 1502: 			my $passfilename="$proname/passwd";
 1503: 			if (-e $passfilename) {
 1504: 			    my $pf = IO::File->new($passfilename);
 1505: 			    my $realpasswd=<$pf>;
 1506: 			    chomp($realpasswd);
 1507: 			    my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
 1508: 			    my $pwdcorrect=0;
 1509: 			    if ($howpwd eq 'internal') {
 1510: 				&Debug("Internal auth");
 1511: 				$pwdcorrect=
 1512: 				    (crypt($upass,$contentpwd) eq $contentpwd);
 1513: 			    } elsif ($howpwd eq 'unix') {
 1514: 				&Debug("Unix auth");
 1515: 				if((getpwnam($uname))[1] eq "") { #no such user!
 1516: 				    $pwdcorrect = 0;
 1517: 				} else {
 1518: 				    $contentpwd=(getpwnam($uname))[1];
 1519: 				    my $pwauth_path="/usr/local/sbin/pwauth";
 1520: 				    unless ($contentpwd eq 'x') {
 1521: 					$pwdcorrect=
 1522: 					    (crypt($upass,$contentpwd) eq 
 1523: 					     $contentpwd);
 1524: 				    }
 1525: 				    
 1526: 				    elsif (-e $pwauth_path) {
 1527: 					open PWAUTH, "|$pwauth_path" or
 1528: 					    die "Cannot invoke authentication";
 1529: 					print PWAUTH "$uname\n$upass\n";
 1530: 					close PWAUTH;
 1531: 					$pwdcorrect=!$?;
 1532: 				    }
 1533: 				}
 1534: 			    } elsif ($howpwd eq 'krb4') {
 1535: 				my $null=pack("C",0);
 1536: 				unless ($upass=~/$null/) {
 1537: 				    my $krb4_error = &Authen::Krb4::get_pw_in_tkt
 1538: 					($uname,"",$contentpwd,'krbtgt',
 1539: 					 $contentpwd,1,$upass);
 1540: 				    if (!$krb4_error) {
 1541: 					$pwdcorrect = 1;
 1542: 				    } else { 
 1543: 					$pwdcorrect=0; 
 1544: 					# log error if it is not a bad password
 1545: 					if ($krb4_error != 62) {
 1546: 					    &logthis('krb4:'.$uname.','.$contentpwd.','.
 1547: 						     &Authen::Krb4::get_err_txt($Authen::Krb4::error));
 1548: 					}
 1549: 				    }
 1550: 				}
 1551: 			    } elsif ($howpwd eq 'krb5') {
 1552: 				my $null=pack("C",0);
 1553: 				unless ($upass=~/$null/) {
 1554: 				    my $krbclient=&Authen::Krb5::parse_name($uname.'@'.$contentpwd);
 1555: 				    my $krbservice="krbtgt/".$contentpwd."\@".$contentpwd;
 1556: 				    my $krbserver=&Authen::Krb5::parse_name($krbservice);
 1557: 				    my $credentials=&Authen::Krb5::cc_default();
 1558: 				    $credentials->initialize($krbclient);
 1559: 				    my $krbreturn = 
 1560: 					&Authen::Krb5::get_in_tkt_with_password(
 1561: 										$krbclient,$krbserver,$upass,$credentials);
 1562: #				  unless ($krbreturn) {
 1563: #				      &logthis("Krb5 Error: ".
 1564: #					       &Authen::Krb5::error());
 1565: #				  }
 1566: 				    $pwdcorrect = ($krbreturn == 1);
 1567: 				} else { $pwdcorrect=0; }
 1568: 			    } elsif ($howpwd eq 'localauth') {
 1569: 				$pwdcorrect=&localauth::localauth($uname,$upass,
 1570: 								  $contentpwd);
 1571: 			    }
 1572: 			    if ($pwdcorrect) {
 1573: 				print $client "authorized\n";
 1574: 			    } else {
 1575: 				print $client "non_authorized\n";
 1576: 			    }  
 1577: 			} else {
 1578: 			    print $client "unknown_user\n";
 1579: 			}
 1580: 		    } else {
 1581: 			Reply($client, "refused\n", $userinput);
 1582: 		       
 1583: 		    }
 1584: # ---------------------------------------------------------------------- passwd
 1585: 		} elsif ($userinput =~ /^passwd/) { # encoded and client
 1586: 		    if (($wasenc==1) && isClient) {
 1587: 			my 
 1588: 			    ($cmd,$udom,$uname,$upass,$npass)=split(/:/,$userinput);
 1589: 			chomp($npass);
 1590: 			$upass=&unescape($upass);
 1591: 			$npass=&unescape($npass);
 1592: 			&Debug("Trying to change password for $uname");
 1593: 			my $proname=propath($udom,$uname);
 1594: 			my $passfilename="$proname/passwd";
 1595: 			if (-e $passfilename) {
 1596: 			    my $realpasswd;
 1597: 			    { my $pf = IO::File->new($passfilename);
 1598: 			      $realpasswd=<$pf>; }
 1599: 			    chomp($realpasswd);
 1600: 			    my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
 1601: 			    if ($howpwd eq 'internal') {
 1602: 				&Debug("internal auth");
 1603: 				if (crypt($upass,$contentpwd) eq $contentpwd) {
 1604: 				    my $salt=time;
 1605: 				    $salt=substr($salt,6,2);
 1606: 				    my $ncpass=crypt($npass,$salt);
 1607: 				    {
 1608: 					my $pf;
 1609: 					if ($pf = IO::File->new(">$passfilename")) {
 1610: 					    print $pf "internal:$ncpass\n";
 1611: 					    &logthis("Result of password change for $uname: pwchange_success");
 1612: 					    print $client "ok\n";
 1613: 					} else {
 1614: 					    &logthis("Unable to open $uname passwd to change password");
 1615: 					    print $client "non_authorized\n";
 1616: 					}
 1617: 				    }             
 1618: 				    
 1619: 				} else {
 1620: 				    print $client "non_authorized\n";
 1621: 				}
 1622: 			    } elsif ($howpwd eq 'unix') {
 1623: 				# Unix means we have to access /etc/password
 1624: 				# one way or another.
 1625: 				# First: Make sure the current password is
 1626: 				#        correct
 1627: 				&Debug("auth is unix");
 1628: 				$contentpwd=(getpwnam($uname))[1];
 1629: 				my $pwdcorrect = "0";
 1630: 				my $pwauth_path="/usr/local/sbin/pwauth";
 1631: 				unless ($contentpwd eq 'x') {
 1632: 				    $pwdcorrect=
 1633: 					(crypt($upass,$contentpwd) eq $contentpwd);
 1634: 				} elsif (-e $pwauth_path) {
 1635: 				    open PWAUTH, "|$pwauth_path" or
 1636: 					die "Cannot invoke authentication";
 1637: 				    print PWAUTH "$uname\n$upass\n";
 1638: 				    close PWAUTH;
 1639: 				    &Debug("exited pwauth with $? ($uname,$upass) ");
 1640: 				    $pwdcorrect=($? == 0);
 1641: 				}
 1642: 				if ($pwdcorrect) {
 1643: 				    my $execdir=$perlvar{'lonDaemons'};
 1644: 				    &Debug("Opening lcpasswd pipeline");
 1645: 				    my $pf = IO::File->new("|$execdir/lcpasswd > $perlvar{'lonDaemons'}/logs/lcpasswd.log");
 1646: 				    print $pf "$uname\n$npass\n$npass\n";
 1647: 				    close $pf;
 1648: 				    my $err = $?;
 1649: 				    my $result = ($err>0 ? 'pwchange_failure' 
 1650: 						  : 'ok');
 1651: 				    &logthis("Result of password change for $uname: ".
 1652: 					     &lcpasswdstrerror($?));
 1653: 				    print $client "$result\n";
 1654: 				} else {
 1655: 				    print $client "non_authorized\n";
 1656: 				}
 1657: 			    } else {
 1658: 				print $client "auth_mode_error\n";
 1659: 			    }  
 1660: 			} else {
 1661: 			    print $client "unknown_user\n";
 1662: 			}
 1663: 		    } else {
 1664: 			Reply($client, "refused\n", $userinput);
 1665: 		       
 1666: 		    }
 1667: # -------------------------------------------------------------------- makeuser
 1668: 		} elsif ($userinput =~ /^makeuser/) { # encoded and client.
 1669: 		    &Debug("Make user received");
 1670: 		    my $oldumask=umask(0077);
 1671: 		    if (($wasenc==1) && isClient) {
 1672: 			my 
 1673: 			    ($cmd,$udom,$uname,$umode,$npass)=split(/:/,$userinput);
 1674: 			&Debug("cmd =".$cmd." $udom =".$udom.
 1675: 			       " uname=".$uname);
 1676: 			chomp($npass);
 1677: 			$npass=&unescape($npass);
 1678: 			my $proname=propath($udom,$uname);
 1679: 			my $passfilename="$proname/passwd";
 1680: 			&Debug("Password file created will be:".
 1681: 			       $passfilename);
 1682: 			if (-e $passfilename) {
 1683: 			    print $client "already_exists\n";
 1684: 			} elsif ($udom ne $currentdomainid) {
 1685: 			    print $client "not_right_domain\n";
 1686: 			} else {
 1687: 			    my @fpparts=split(/\//,$proname);
 1688: 			    my $fpnow=$fpparts[0].'/'.$fpparts[1].'/'.$fpparts[2];
 1689: 			    my $fperror='';
 1690: 			    for (my $i=3;$i<=$#fpparts;$i++) {
 1691: 				$fpnow.='/'.$fpparts[$i]; 
 1692: 				unless (-e $fpnow) {
 1693: 				    unless (mkdir($fpnow,0777)) {
 1694: 					$fperror="error: ".($!+0)
 1695: 					    ." mkdir failed while attempting "
 1696: 					    ."makeuser\n";
 1697: 				    }
 1698: 				}
 1699: 			    }
 1700: 			    unless ($fperror) {
 1701: 				my $result=&make_passwd_file($uname, $umode,$npass,
 1702: 							     $passfilename);
 1703: 				print $client $result;
 1704: 			    } else {
 1705: 				print $client "$fperror\n";
 1706: 			    }
 1707: 			}
 1708: 		    } else {
 1709: 			Reply($client, "refused\n", $userinput);
 1710: 	      
 1711: 		    }
 1712: 		    umask($oldumask);
 1713: # -------------------------------------------------------------- changeuserauth
 1714: 		} elsif ($userinput =~ /^changeuserauth/) { # encoded & client
 1715: 		    &Debug("Changing authorization");
 1716: 		    if (($wasenc==1) && isClient) {
 1717: 			my 
 1718: 			    ($cmd,$udom,$uname,$umode,$npass)=split(/:/,$userinput);
 1719: 			chomp($npass);
 1720: 			&Debug("cmd = ".$cmd." domain= ".$udom.
 1721: 			       "uname =".$uname." umode= ".$umode);
 1722: 			$npass=&unescape($npass);
 1723: 			my $proname=&propath($udom,$uname);
 1724: 			my $passfilename="$proname/passwd";
 1725: 			if ($udom ne $currentdomainid) {
 1726: 			    print $client "not_right_domain\n";
 1727: 			} else {
 1728: 			    my $result=&make_passwd_file($uname, $umode,$npass,
 1729: 							 $passfilename);
 1730: 			    print $client $result;
 1731: 			}
 1732: 		    } else {
 1733: 			Reply($client, "refused\n", $userinput);
 1734: 		   
 1735: 		    }
 1736: # ------------------------------------------------------------------------ home
 1737: 		} elsif ($userinput =~ /^home/) { # client clear or encoded
 1738: 		    if(isClient) {
 1739: 			my ($cmd,$udom,$uname)=split(/:/,$userinput);
 1740: 			chomp($uname);
 1741: 			my $proname=propath($udom,$uname);
 1742: 			if (-e $proname) {
 1743: 			    print $client "found\n";
 1744: 			} else {
 1745: 			    print $client "not_found\n";
 1746: 			}
 1747: 		    } else {
 1748: 			Reply($client, "refused\n", $userinput);
 1749: 
 1750: 		    }
 1751: # ---------------------------------------------------------------------- update
 1752: 		} elsif ($userinput =~ /^update/) { # client clear or encoded.
 1753: 		    if(isClient) {
 1754: 			my ($cmd,$fname)=split(/:/,$userinput);
 1755: 			my $ownership=ishome($fname);
 1756: 			if ($ownership eq 'not_owner') {
 1757: 			    if (-e $fname) {
 1758: 				my ($dev,$ino,$mode,$nlink,
 1759: 				    $uid,$gid,$rdev,$size,
 1760: 				    $atime,$mtime,$ctime,
 1761: 				    $blksize,$blocks)=stat($fname);
 1762: 				my $now=time;
 1763: 				my $since=$now-$atime;
 1764: 				if ($since>$perlvar{'lonExpire'}) {
 1765: 				    my $reply=
 1766: 					&reply("unsub:$fname","$clientname");
 1767: 				    unlink("$fname");
 1768: 				} else {
 1769: 				    my $transname="$fname.in.transfer";
 1770: 				    my $remoteurl=
 1771: 					&reply("sub:$fname","$clientname");
 1772: 				    my $response;
 1773: 				    {
 1774: 					my $ua=new LWP::UserAgent;
 1775: 					my $request=new HTTP::Request('GET',"$remoteurl");
 1776: 					$response=$ua->request($request,$transname);
 1777: 				    }
 1778: 				    if ($response->is_error()) {
 1779: 					unlink($transname);
 1780: 					my $message=$response->status_line;
 1781: 					&logthis(
 1782: 						 "LWP GET: $message for $fname ($remoteurl)");
 1783: 				    } else {
 1784: 					if ($remoteurl!~/\.meta$/) {
 1785: 					    my $ua=new LWP::UserAgent;
 1786: 					    my $mrequest=
 1787: 						new HTTP::Request('GET',$remoteurl.'.meta');
 1788: 					    my $mresponse=
 1789: 						$ua->request($mrequest,$fname.'.meta');
 1790: 					    if ($mresponse->is_error()) {
 1791: 						unlink($fname.'.meta');
 1792: 					    }
 1793: 					}
 1794: 					rename($transname,$fname);
 1795: 				    }
 1796: 				}
 1797: 				print $client "ok\n";
 1798: 			    } else {
 1799: 				print $client "not_found\n";
 1800: 			    }
 1801: 			} else {
 1802: 			    print $client "rejected\n";
 1803: 			}
 1804: 		    } else {
 1805: 			Reply($client, "refused\n", $userinput);
 1806: 
 1807: 		    }
 1808: # -------------------------------------- fetch a user file from a remote server
 1809: 		} elsif ($userinput =~ /^fetchuserfile/) { # Client clear or enc.
 1810: 		    if(isClient) {
 1811: 			my ($cmd,$fname)=split(/:/,$userinput);
 1812: 			my ($udom,$uname,$ufile)=split(/\//,$fname);
 1813: 			my $udir=propath($udom,$uname).'/userfiles';
 1814: 			unless (-e $udir) { mkdir($udir,0770); }
 1815: 			if (-e $udir) {
 1816: 			    $ufile=~s/^[\.\~]+//;
 1817: 			    $ufile=~s/\///g;
 1818: 			    my $destname=$udir.'/'.$ufile;
 1819: 			    my $transname=$udir.'/'.$ufile.'.in.transit';
 1820: 			    my $remoteurl='http://'.$clientip.'/userfiles/'.$fname;
 1821: 			    my $response;
 1822: 			    {
 1823: 				my $ua=new LWP::UserAgent;
 1824: 				my $request=new HTTP::Request('GET',"$remoteurl");
 1825: 				$response=$ua->request($request,$transname);
 1826: 			    }
 1827: 			    if ($response->is_error()) {
 1828: 				unlink($transname);
 1829: 				my $message=$response->status_line;
 1830: 				&logthis("LWP GET: $message for $fname ($remoteurl)");
 1831: 				print $client "failed\n";
 1832: 			    } else {
 1833: 				if (!rename($transname,$destname)) {
 1834: 				    &logthis("Unable to move $transname to $destname");
 1835: 				    unlink($transname);
 1836: 				    print $client "failed\n";
 1837: 				} else {
 1838: 				    print $client "ok\n";
 1839: 				}
 1840: 			    }
 1841: 			} else {
 1842: 			    print $client "not_home\n";
 1843: 			}
 1844: 		    } else {
 1845: 			Reply($client, "refused\n", $userinput);
 1846: 
 1847: 		    }
 1848: # ------------------------------------------ authenticate access to a user file
 1849: 		} elsif ($userinput =~ /^tokenauthuserfile/) { # Client only
 1850: 		    if(isClient) {
 1851: 			my ($cmd,$fname,$session)=split(/:/,$userinput);
 1852: 			chomp($session);
 1853: 			my $reply='non_auth';
 1854: 			if (open(ENVIN,$perlvar{'lonIDsDir'}.'/'.
 1855: 				 $session.'.id')) {
 1856: 			    while (my $line=<ENVIN>) {
 1857: 				if ($line=~/userfile\.$fname\=/) { $reply='ok'; }
 1858: 			    }
 1859: 			    close(ENVIN);
 1860: 			    print $client $reply."\n";
 1861: 			} else {
 1862: 			    print $client "invalid_token\n";
 1863: 			}
 1864: 		    } else {
 1865: 			Reply($client, "refused\n", $userinput);
 1866: 
 1867: 		    }
 1868: # ----------------------------------------------------------------- unsubscribe
 1869: 		} elsif ($userinput =~ /^unsub/) {
 1870: 		    if(isClient) {
 1871: 			my ($cmd,$fname)=split(/:/,$userinput);
 1872: 			if (-e $fname) {
 1873: 			    print $client &unsub($client,$fname,$clientip);
 1874: 			} else {
 1875: 			    print $client "not_found\n";
 1876: 			}
 1877: 		    } else {
 1878: 			Reply($client, "refused\n", $userinput);
 1879: 
 1880: 		    }
 1881: # ------------------------------------------------------------------- subscribe
 1882: 		} elsif ($userinput =~ /^sub/) {
 1883: 		    if(isClient) {
 1884: 			print $client &subscribe($userinput,$clientip);
 1885: 		    } else {
 1886: 			Reply($client, "refused\n", $userinput);
 1887: 
 1888: 		    }
 1889: # ------------------------------------------------------------- current version
 1890: 		} elsif ($userinput =~ /^currentversion/) {
 1891: 		    if(isClient) {
 1892: 			my ($cmd,$fname)=split(/:/,$userinput);
 1893: 			print $client &currentversion($fname)."\n";
 1894: 		    } else {
 1895: 			Reply($client, "refused\n", $userinput);
 1896: 
 1897: 		    }
 1898: # ------------------------------------------------------------------------- log
 1899: 		} elsif ($userinput =~ /^log/) {
 1900: 		    if(isClient) {
 1901: 			my ($cmd,$udom,$uname,$what)=split(/:/,$userinput);
 1902: 			chomp($what);
 1903: 			my $proname=propath($udom,$uname);
 1904: 			my $now=time;
 1905: 			{
 1906: 			    my $hfh;
 1907: 			    if ($hfh=IO::File->new(">>$proname/activity.log")) { 
 1908: 				print $hfh "$now:$clientname:$what\n";
 1909: 				print $client "ok\n"; 
 1910: 			    } else {
 1911: 				print $client "error: ".($!+0)
 1912: 				    ." IO::File->new Failed "
 1913: 				    ."while attempting log\n";
 1914: 			    }
 1915: 			}
 1916: 		    } else {
 1917: 			Reply($client, "refused\n", $userinput);
 1918: 
 1919: 		    }
 1920: # ------------------------------------------------------------------------- put
 1921: 		} elsif ($userinput =~ /^put/) {
 1922: 		    if(isClient) {
 1923: 			my ($cmd,$udom,$uname,$namespace,$what)
 1924: 			    =split(/:/,$userinput);
 1925: 			$namespace=~s/\//\_/g;
 1926: 			$namespace=~s/\W//g;
 1927: 			if ($namespace ne 'roles') {
 1928: 			    chomp($what);
 1929: 			    my $proname=propath($udom,$uname);
 1930: 			    my $now=time;
 1931: 			    unless ($namespace=~/^nohist\_/) {
 1932: 				my $hfh;
 1933: 				if (
 1934: 				    $hfh=IO::File->new(">>$proname/$namespace.hist")
 1935: 				    ) { print $hfh "P:$now:$what\n"; }
 1936: 			    }
 1937: 			    my @pairs=split(/\&/,$what);
 1938: 			    my %hash;
 1939: 			    if (tie(%hash,'GDBM_File',
 1940: 				    "$proname/$namespace.db",
 1941: 				    &GDBM_WRCREAT(),0640)) {
 1942: 				foreach my $pair (@pairs) {
 1943: 				    my ($key,$value)=split(/=/,$pair);
 1944: 				    $hash{$key}=$value;
 1945: 				}
 1946: 				if (untie(%hash)) {
 1947: 				    print $client "ok\n";
 1948: 				} else {
 1949: 				    print $client "error: ".($!+0)
 1950: 					." untie(GDBM) failed ".
 1951: 					"while attempting put\n";
 1952: 				}
 1953: 			    } else {
 1954: 				print $client "error: ".($!)
 1955: 				    ." tie(GDBM) Failed ".
 1956: 				    "while attempting put\n";
 1957: 			    }
 1958: 			} else {
 1959: 			    print $client "refused\n";
 1960: 			}
 1961: 		    } else {
 1962: 			Reply($client, "refused\n", $userinput);
 1963: 
 1964: 		    }
 1965: # ------------------------------------------------------------------- inc
 1966: 		} elsif ($userinput =~ /^inc:/) {
 1967: 		    if(isClient) {
 1968: 			my ($cmd,$udom,$uname,$namespace,$what)
 1969: 			    =split(/:/,$userinput);
 1970: 			$namespace=~s/\//\_/g;
 1971: 			$namespace=~s/\W//g;
 1972: 			if ($namespace ne 'roles') {
 1973: 			    chomp($what);
 1974: 			    my $proname=propath($udom,$uname);
 1975: 			    my $now=time;
 1976: 			    unless ($namespace=~/^nohist\_/) {
 1977: 				my $hfh;
 1978: 				if (
 1979: 				    $hfh=IO::File->new(">>$proname/$namespace.hist")
 1980: 				    ) { print $hfh "P:$now:$what\n"; }
 1981: 			    }
 1982: 			    my @pairs=split(/\&/,$what);
 1983: 			    my %hash;
 1984: 			    if (tie(%hash,'GDBM_File',
 1985: 				    "$proname/$namespace.db",
 1986: 				    &GDBM_WRCREAT(),0640)) {
 1987: 				foreach my $pair (@pairs) {
 1988: 				    my ($key,$value)=split(/=/,$pair);
 1989:                                     # We could check that we have a number...
 1990:                                     if (! defined($value) || $value eq '') {
 1991:                                         $value = 1;
 1992:                                     }
 1993: 				    $hash{$key}+=$value;
 1994: 				}
 1995: 				if (untie(%hash)) {
 1996: 				    print $client "ok\n";
 1997: 				} else {
 1998: 				    print $client "error: ".($!+0)
 1999: 					." untie(GDBM) failed ".
 2000: 					"while attempting put\n";
 2001: 				}
 2002: 			    } else {
 2003: 				print $client "error: ".($!)
 2004: 				    ." tie(GDBM) Failed ".
 2005: 				    "while attempting put\n";
 2006: 			    }
 2007: 			} else {
 2008: 			    print $client "refused\n";
 2009: 			}
 2010: 		    } else {
 2011: 			Reply($client, "refused\n", $userinput);
 2012: 
 2013: 		    }
 2014: # -------------------------------------------------------------------- rolesput
 2015: 		} elsif ($userinput =~ /^rolesput/) {
 2016: 		    if(isClient) {
 2017: 			&Debug("rolesput");
 2018: 			if ($wasenc==1) {
 2019: 			    my ($cmd,$exedom,$exeuser,$udom,$uname,$what)
 2020: 				=split(/:/,$userinput);
 2021: 			    &Debug("cmd = ".$cmd." exedom= ".$exedom.
 2022: 				   "user = ".$exeuser." udom=".$udom.
 2023: 				   "what = ".$what);
 2024: 			    my $namespace='roles';
 2025: 			    chomp($what);
 2026: 			    my $proname=propath($udom,$uname);
 2027: 			    my $now=time;
 2028: 			    {
 2029: 				my $hfh;
 2030: 				if (
 2031: 				    $hfh=IO::File->new(">>$proname/$namespace.hist")
 2032: 				    ) { 
 2033: 				    print $hfh "P:$now:$exedom:$exeuser:$what\n";
 2034: 				}
 2035: 			    }
 2036: 			    my @pairs=split(/\&/,$what);
 2037: 			    my %hash;
 2038: 			    if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
 2039: 				foreach my $pair (@pairs) {
 2040: 				    my ($key,$value)=split(/=/,$pair);
 2041: 				    &ManagePermissions($key, $udom, $uname,
 2042: 						       &GetAuthType( $udom, 
 2043: 								     $uname));
 2044: 				    $hash{$key}=$value;
 2045: 				}
 2046: 				if (untie(%hash)) {
 2047: 				    print $client "ok\n";
 2048: 				} else {
 2049: 				    print $client "error: ".($!+0)
 2050: 					." untie(GDBM) Failed ".
 2051: 					"while attempting rolesput\n";
 2052: 				}
 2053: 			    } else {
 2054: 				print $client "error: ".($!+0)
 2055: 				    ." tie(GDBM) Failed ".
 2056: 				    "while attempting rolesput\n";
 2057: 			    }
 2058: 			} else {
 2059: 			    print $client "refused\n";
 2060: 			}
 2061: 		    } else {
 2062: 			Reply($client, "refused\n", $userinput);
 2063: 		  
 2064: 		    }
 2065: # -------------------------------------------------------------------- rolesdel
 2066: 		} elsif ($userinput =~ /^rolesdel/) {
 2067: 		    if(isClient) {
 2068: 			&Debug("rolesdel");
 2069: 			if ($wasenc==1) {
 2070: 			    my ($cmd,$exedom,$exeuser,$udom,$uname,$what)
 2071: 				=split(/:/,$userinput);
 2072: 			    &Debug("cmd = ".$cmd." exedom= ".$exedom.
 2073: 				   "user = ".$exeuser." udom=".$udom.
 2074: 				   "what = ".$what);
 2075: 			    my $namespace='roles';
 2076: 			    chomp($what);
 2077: 			    my $proname=propath($udom,$uname);
 2078: 			    my $now=time;
 2079: 			    {
 2080: 				my $hfh;
 2081: 				if (
 2082: 				    $hfh=IO::File->new(">>$proname/$namespace.hist")
 2083: 				    ) { 
 2084: 				    print $hfh "D:$now:$exedom:$exeuser:$what\n";
 2085: 				}
 2086: 			    }
 2087: 			    my @rolekeys=split(/\&/,$what);
 2088: 			    my %hash;
 2089: 			    if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
 2090: 				foreach my $key (@rolekeys) {
 2091: 				    delete $hash{$key};
 2092: 				}
 2093: 				if (untie(%hash)) {
 2094: 				    print $client "ok\n";
 2095: 				} else {
 2096: 				    print $client "error: ".($!+0)
 2097: 					." untie(GDBM) Failed ".
 2098: 					"while attempting rolesdel\n";
 2099: 				}
 2100: 			    } else {
 2101: 				print $client "error: ".($!+0)
 2102: 				    ." tie(GDBM) Failed ".
 2103: 				    "while attempting rolesdel\n";
 2104: 			    }
 2105: 			} else {
 2106: 			    print $client "refused\n";
 2107: 			}
 2108: 		    } else {
 2109: 			Reply($client, "refused\n", $userinput);
 2110: 		      
 2111: 		    }
 2112: # ------------------------------------------------------------------------- get
 2113: 		} elsif ($userinput =~ /^get/) {
 2114: 		    if(isClient) {
 2115: 			my ($cmd,$udom,$uname,$namespace,$what)
 2116: 			    =split(/:/,$userinput);
 2117: 			$namespace=~s/\//\_/g;
 2118: 			$namespace=~s/\W//g;
 2119: 			chomp($what);
 2120: 			my @queries=split(/\&/,$what);
 2121: 			my $proname=propath($udom,$uname);
 2122: 			my $qresult='';
 2123: 			my %hash;
 2124: 			if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
 2125: 			    for (my $i=0;$i<=$#queries;$i++) {
 2126: 				$qresult.="$hash{$queries[$i]}&";
 2127: 			    }
 2128: 			    if (untie(%hash)) {
 2129: 				$qresult=~s/\&$//;
 2130: 				print $client "$qresult\n";
 2131: 			    } else {
 2132: 				print $client "error: ".($!+0)
 2133: 				    ." untie(GDBM) Failed ".
 2134: 				    "while attempting get\n";
 2135: 			    }
 2136: 			} else {
 2137: 			    if ($!+0 == 2) {
 2138: 				print $client "error:No such file or ".
 2139: 				    "GDBM reported bad block error\n";
 2140: 			    } else {
 2141: 				print $client "error: ".($!+0)
 2142: 				    ." tie(GDBM) Failed ".
 2143: 				    "while attempting get\n";
 2144: 			    }
 2145: 			}
 2146: 		    } else {
 2147: 			Reply($client, "refused\n", $userinput);
 2148: 		       
 2149: 		    }
 2150: # ------------------------------------------------------------------------ eget
 2151: 		} elsif ($userinput =~ /^eget/) {
 2152: 		    if (isClient) {
 2153: 			my ($cmd,$udom,$uname,$namespace,$what)
 2154: 			    =split(/:/,$userinput);
 2155: 			$namespace=~s/\//\_/g;
 2156: 			$namespace=~s/\W//g;
 2157: 			chomp($what);
 2158: 			my @queries=split(/\&/,$what);
 2159: 			my $proname=propath($udom,$uname);
 2160: 			my $qresult='';
 2161: 			my %hash;
 2162: 			if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
 2163: 			    for (my $i=0;$i<=$#queries;$i++) {
 2164: 				$qresult.="$hash{$queries[$i]}&";
 2165: 			    }
 2166: 			    if (untie(%hash)) {
 2167: 				$qresult=~s/\&$//;
 2168: 				if ($cipher) {
 2169: 				    my $cmdlength=length($qresult);
 2170: 				    $qresult.="         ";
 2171: 				    my $encqresult='';
 2172: 				    for 
 2173: 					(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 2174: 					    $encqresult.=
 2175: 						unpack("H16",
 2176: 						       $cipher->encrypt(substr($qresult,$encidx,8)));
 2177: 					}
 2178: 				    print $client "enc:$cmdlength:$encqresult\n";
 2179: 				} else {
 2180: 				    print $client "error:no_key\n";
 2181: 				}
 2182: 			    } else {
 2183: 				print $client "error: ".($!+0)
 2184: 				    ." untie(GDBM) Failed ".
 2185: 				    "while attempting eget\n";
 2186: 			    }
 2187: 			} else {
 2188: 			    print $client "error: ".($!+0)
 2189: 				." tie(GDBM) Failed ".
 2190: 				"while attempting eget\n";
 2191: 			}
 2192: 		    } else {
 2193: 			Reply($client, "refused\n", $userinput);
 2194: 		    
 2195: 		    }
 2196: # ------------------------------------------------------------------------- del
 2197: 		} elsif ($userinput =~ /^del/) {
 2198: 		    if(isClient) {
 2199: 			my ($cmd,$udom,$uname,$namespace,$what)
 2200: 			    =split(/:/,$userinput);
 2201: 			$namespace=~s/\//\_/g;
 2202: 			$namespace=~s/\W//g;
 2203: 			chomp($what);
 2204: 			my $proname=propath($udom,$uname);
 2205: 			my $now=time;
 2206: 			unless ($namespace=~/^nohist\_/) {
 2207: 			    my $hfh;
 2208: 			    if (
 2209: 				$hfh=IO::File->new(">>$proname/$namespace.hist")
 2210: 				) { print $hfh "D:$now:$what\n"; }
 2211: 			}
 2212: 			my @keys=split(/\&/,$what);
 2213: 			my %hash;
 2214: 			if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
 2215: 			    foreach my $key (@keys) {
 2216: 				delete($hash{$key});
 2217: 			    }
 2218: 			    if (untie(%hash)) {
 2219: 				print $client "ok\n";
 2220: 			    } else {
 2221: 				print $client "error: ".($!+0)
 2222: 				    ." untie(GDBM) Failed ".
 2223: 				    "while attempting del\n";
 2224: 			    }
 2225: 			} else {
 2226: 			    print $client "error: ".($!+0)
 2227: 				." tie(GDBM) Failed ".
 2228: 				"while attempting del\n";
 2229: 			}
 2230: 		    } else {
 2231: 			Reply($client, "refused\n", $userinput);
 2232: 			
 2233: 		    }
 2234: # ------------------------------------------------------------------------ keys
 2235: 		} elsif ($userinput =~ /^keys/) {
 2236: 		    if(isClient) {
 2237: 			my ($cmd,$udom,$uname,$namespace)
 2238: 			    =split(/:/,$userinput);
 2239: 			$namespace=~s/\//\_/g;
 2240: 			$namespace=~s/\W//g;
 2241: 			my $proname=propath($udom,$uname);
 2242: 			my $qresult='';
 2243: 			my %hash;
 2244: 			if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
 2245: 			    foreach my $key (keys %hash) {
 2246: 				$qresult.="$key&";
 2247: 			    }
 2248: 			    if (untie(%hash)) {
 2249: 				$qresult=~s/\&$//;
 2250: 				print $client "$qresult\n";
 2251: 			    } else {
 2252: 				print $client "error: ".($!+0)
 2253: 				    ." untie(GDBM) Failed ".
 2254: 				    "while attempting keys\n";
 2255: 			    }
 2256: 			} else {
 2257: 			    print $client "error: ".($!+0)
 2258: 				." tie(GDBM) Failed ".
 2259: 				"while attempting keys\n";
 2260: 			}
 2261: 		    } else {
 2262: 			Reply($client, "refused\n", $userinput);
 2263: 		   
 2264: 		    }
 2265: # ----------------------------------------------------------------- dumpcurrent
 2266: 		} elsif ($userinput =~ /^currentdump/) {
 2267: 		    if (isClient) {
 2268: 			my ($cmd,$udom,$uname,$namespace)
 2269: 			    =split(/:/,$userinput);
 2270: 			$namespace=~s/\//\_/g;
 2271: 			$namespace=~s/\W//g;
 2272: 			my $qresult='';
 2273: 			my $proname=propath($udom,$uname);
 2274: 			my %hash;
 2275: 			if (tie(%hash,'GDBM_File',
 2276: 				"$proname/$namespace.db",
 2277: 				&GDBM_READER(),0640)) {
 2278: 			    # Structure of %data:
 2279: 			    # $data{$symb}->{$parameter}=$value;
 2280: 			    # $data{$symb}->{'v.'.$parameter}=$version;
 2281: 			    # since $parameter will be unescaped, we do not
 2282: 			    # have to worry about silly parameter names...
 2283: 			    my %data = ();
 2284: 			    while (my ($key,$value) = each(%hash)) {
 2285: 				my ($v,$symb,$param) = split(/:/,$key);
 2286: 				next if ($v eq 'version' || $symb eq 'keys');
 2287: 				next if (exists($data{$symb}) && 
 2288: 					 exists($data{$symb}->{$param}) &&
 2289: 					 $data{$symb}->{'v.'.$param} > $v);
 2290: 				$data{$symb}->{$param}=$value;
 2291: 				$data{$symb}->{'v.'.$param}=$v;
 2292: 			    }
 2293: 			    if (untie(%hash)) {
 2294: 				while (my ($symb,$param_hash) = each(%data)) {
 2295: 				    while(my ($param,$value) = each (%$param_hash)){
 2296: 					next if ($param =~ /^v\./);
 2297: 					$qresult.=$symb.':'.$param.'='.$value.'&';
 2298: 				    }
 2299: 				}
 2300: 				chop($qresult);
 2301: 				print $client "$qresult\n";
 2302: 			    } else {
 2303: 				print $client "error: ".($!+0)
 2304: 				    ." untie(GDBM) Failed ".
 2305: 				    "while attempting currentdump\n";
 2306: 			    }
 2307: 			} else {
 2308: 			    print $client "error: ".($!+0)
 2309: 				." tie(GDBM) Failed ".
 2310: 				"while attempting currentdump\n";
 2311: 			}
 2312: 		    } else {
 2313: 			Reply($client, "refused\n", $userinput);
 2314: 		    }
 2315: # ------------------------------------------------------------------------ dump
 2316: 		} elsif ($userinput =~ /^dump/) {
 2317: 		    if(isClient) {
 2318: 			my ($cmd,$udom,$uname,$namespace,$regexp)
 2319: 			    =split(/:/,$userinput);
 2320: 			$namespace=~s/\//\_/g;
 2321: 			$namespace=~s/\W//g;
 2322: 			if (defined($regexp)) {
 2323: 			    $regexp=&unescape($regexp);
 2324: 			} else {
 2325: 			    $regexp='.';
 2326: 			}
 2327: 			my $qresult='';
 2328: 			my $proname=propath($udom,$uname);
 2329: 			my %hash;
 2330: 			if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
 2331: 			       study($regexp);
 2332: 			       while (my ($key,$value) = each(%hash)) {
 2333: 				   if ($regexp eq '.') {
 2334: 				       $qresult.=$key.'='.$value.'&';
 2335: 				   } else {
 2336: 				       my $unescapeKey = &unescape($key);
 2337: 				       if (eval('$unescapeKey=~/$regexp/')) {
 2338: 					   $qresult.="$key=$value&";
 2339: 				       }
 2340: 				   }
 2341: 			       }
 2342: 			       if (untie(%hash)) {
 2343: 				   chop($qresult);
 2344: 				   print $client "$qresult\n";
 2345: 			       } else {
 2346: 				   print $client "error: ".($!+0)
 2347: 				       ." untie(GDBM) Failed ".
 2348:                                        "while attempting dump\n";
 2349: 			       }
 2350: 			   } else {
 2351: 			       print $client "error: ".($!+0)
 2352: 				   ." tie(GDBM) Failed ".
 2353: 				   "while attempting dump\n";
 2354: 			   }
 2355: 		    } else {
 2356: 			Reply($client, "refused\n", $userinput);
 2357: 		 
 2358: 		    }
 2359: # ----------------------------------------------------------------------- store
 2360: 		} elsif ($userinput =~ /^store/) {
 2361: 		    if(isClient) {
 2362: 			my ($cmd,$udom,$uname,$namespace,$rid,$what)
 2363: 			    =split(/:/,$userinput);
 2364: 			$namespace=~s/\//\_/g;
 2365: 			$namespace=~s/\W//g;
 2366: 			if ($namespace ne 'roles') {
 2367: 			    chomp($what);
 2368: 			    my $proname=propath($udom,$uname);
 2369: 			    my $now=time;
 2370: 			    unless ($namespace=~/^nohist\_/) {
 2371: 				my $hfh;
 2372: 				if (
 2373: 				    $hfh=IO::File->new(">>$proname/$namespace.hist")
 2374: 				    ) { print $hfh "P:$now:$rid:$what\n"; }
 2375: 			    }
 2376: 			    my @pairs=split(/\&/,$what);
 2377: 			    my %hash;
 2378: 			    if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
 2379: 				my @previouskeys=split(/&/,$hash{"keys:$rid"});
 2380: 				my $key;
 2381: 				$hash{"version:$rid"}++;
 2382: 				my $version=$hash{"version:$rid"};
 2383: 				my $allkeys=''; 
 2384: 				foreach my $pair (@pairs) {
 2385: 				    my ($key,$value)=split(/=/,$pair);
 2386: 				    $allkeys.=$key.':';
 2387: 				    $hash{"$version:$rid:$key"}=$value;
 2388: 				}
 2389: 				$hash{"$version:$rid:timestamp"}=$now;
 2390: 				$allkeys.='timestamp';
 2391: 				$hash{"$version:keys:$rid"}=$allkeys;
 2392: 				if (untie(%hash)) {
 2393: 				    print $client "ok\n";
 2394: 				} else {
 2395: 				    print $client "error: ".($!+0)
 2396: 					." untie(GDBM) Failed ".
 2397: 					"while attempting store\n";
 2398: 				}
 2399: 			    } else {
 2400: 				print $client "error: ".($!+0)
 2401: 				    ." tie(GDBM) Failed ".
 2402: 				    "while attempting store\n";
 2403: 			    }
 2404: 			} else {
 2405: 			    print $client "refused\n";
 2406: 			}
 2407: 		    } else {
 2408: 			Reply($client, "refused\n", $userinput);
 2409: 		     
 2410: 		    }
 2411: # --------------------------------------------------------------------- restore
 2412: 		} elsif ($userinput =~ /^restore/) {
 2413: 		    if(isClient) {
 2414: 			my ($cmd,$udom,$uname,$namespace,$rid)
 2415: 			    =split(/:/,$userinput);
 2416: 			$namespace=~s/\//\_/g;
 2417: 			$namespace=~s/\W//g;
 2418: 			chomp($rid);
 2419: 			my $proname=propath($udom,$uname);
 2420: 			my $qresult='';
 2421: 			my %hash;
 2422: 			if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
 2423: 			    my $version=$hash{"version:$rid"};
 2424: 			    $qresult.="version=$version&";
 2425: 			    my $scope;
 2426: 			    for ($scope=1;$scope<=$version;$scope++) {
 2427: 				my $vkeys=$hash{"$scope:keys:$rid"};
 2428: 				my @keys=split(/:/,$vkeys);
 2429: 				my $key;
 2430: 				$qresult.="$scope:keys=$vkeys&";
 2431: 				foreach $key (@keys) {
 2432: 				    $qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
 2433: 				}                                  
 2434: 			    }
 2435: 			    if (untie(%hash)) {
 2436: 				$qresult=~s/\&$//;
 2437: 				print $client "$qresult\n";
 2438: 			    } else {
 2439: 				print $client "error: ".($!+0)
 2440: 				    ." untie(GDBM) Failed ".
 2441: 				    "while attempting restore\n";
 2442: 			    }
 2443: 			} else {
 2444: 			    print $client "error: ".($!+0)
 2445: 				." tie(GDBM) Failed ".
 2446: 				"while attempting restore\n";
 2447: 			}
 2448: 		    } else  {
 2449: 			Reply($client, "refused\n", $userinput);
 2450: 		       
 2451: 		    }
 2452: # -------------------------------------------------------------------- chatsend
 2453: 		} elsif ($userinput =~ /^chatsend/) {
 2454: 		    if(isClient) {
 2455: 			my ($cmd,$cdom,$cnum,$newpost)=split(/\:/,$userinput);
 2456: 			&chatadd($cdom,$cnum,$newpost);
 2457: 			print $client "ok\n";
 2458: 		    } else {
 2459: 			Reply($client, "refused\n", $userinput);
 2460: 		      
 2461: 		    }
 2462: # -------------------------------------------------------------------- chatretr
 2463: 		} elsif ($userinput =~ /^chatretr/) {
 2464: 		    if(isClient) {
 2465: 			my 
 2466: 			    ($cmd,$cdom,$cnum,$udom,$uname)=split(/\:/,$userinput);
 2467: 			my $reply='';
 2468: 			foreach (&getchat($cdom,$cnum,$udom,$uname)) {
 2469: 			    $reply.=&escape($_).':';
 2470: 			}
 2471: 			$reply=~s/\:$//;
 2472: 			print $client $reply."\n";
 2473: 		    } else {
 2474: 			Reply($client, "refused\n", $userinput);
 2475: 		       
 2476: 		    }
 2477: # ------------------------------------------------------------------- querysend
 2478: 		} elsif ($userinput =~ /^querysend/) {
 2479: 		    if(isClient) {
 2480: 			my ($cmd,$query,
 2481: 			    $arg1,$arg2,$arg3)=split(/\:/,$userinput);
 2482: 			$query=~s/\n*$//g;
 2483: 			print $client "".
 2484: 			    sqlreply("$clientname\&$query".
 2485: 				     "\&$arg1"."\&$arg2"."\&$arg3")."\n";
 2486: 		    } else {
 2487: 			Reply($client, "refused\n", $userinput);
 2488: 		      
 2489: 		    }
 2490: # ------------------------------------------------------------------ queryreply
 2491: 		} elsif ($userinput =~ /^queryreply/) {
 2492: 		    if(isClient) {
 2493: 			my ($cmd,$id,$reply)=split(/:/,$userinput); 
 2494: 			my $store;
 2495: 			my $execdir=$perlvar{'lonDaemons'};
 2496: 			if ($store=IO::File->new(">$execdir/tmp/$id")) {
 2497: 			    $reply=~s/\&/\n/g;
 2498: 			    print $store $reply;
 2499: 			    close $store;
 2500: 			    my $store2=IO::File->new(">$execdir/tmp/$id.end");
 2501: 			    print $store2 "done\n";
 2502: 			    close $store2;
 2503: 			    print $client "ok\n";
 2504: 			}
 2505: 			else {
 2506: 			    print $client "error: ".($!+0)
 2507: 				." IO::File->new Failed ".
 2508: 				"while attempting queryreply\n";
 2509: 			}
 2510: 		    } else {
 2511: 			Reply($client, "refused\n", $userinput);
 2512: 		     
 2513: 		    }
 2514: # ----------------------------------------------------------------- courseidput
 2515: 		} elsif ($userinput =~ /^courseidput/) {
 2516: 		    if(isClient) {
 2517: 			my ($cmd,$udom,$what)=split(/:/,$userinput);
 2518: 			chomp($what);
 2519: 			$udom=~s/\W//g;
 2520: 			my $proname=
 2521: 			    "$perlvar{'lonUsersDir'}/$udom/nohist_courseids";
 2522: 			my $now=time;
 2523: 			my @pairs=split(/\&/,$what);
 2524: 			my %hash;
 2525: 			if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT(),0640)) {
 2526: 			    foreach my $pair (@pairs) {
 2527: 				my ($key,$value)=split(/=/,$pair);
 2528: 				$hash{$key}=$value.':'.$now;
 2529: 			    }
 2530: 			    if (untie(%hash)) {
 2531: 				print $client "ok\n";
 2532: 			    } else {
 2533: 				print $client "error: ".($!+0)
 2534: 				    ." untie(GDBM) Failed ".
 2535: 				    "while attempting courseidput\n";
 2536: 			    }
 2537: 			} else {
 2538: 			    print $client "error: ".($!+0)
 2539: 				." tie(GDBM) Failed ".
 2540: 				"while attempting courseidput\n";
 2541: 			}
 2542: 		    } else {
 2543: 			Reply($client, "refused\n", $userinput);
 2544: 		       
 2545: 		    }
 2546: # ---------------------------------------------------------------- courseiddump
 2547: 		} elsif ($userinput =~ /^courseiddump/) {
 2548: 		    if(isClient) {
 2549: 			my ($cmd,$udom,$since,$description)
 2550: 			    =split(/:/,$userinput);
 2551: 			if (defined($description)) {
 2552: 			    $description=&unescape($description);
 2553: 			} else {
 2554: 			    $description='.';
 2555: 			}
 2556: 			unless (defined($since)) { $since=0; }
 2557: 			my $qresult='';
 2558: 			my $proname=
 2559: 			    "$perlvar{'lonUsersDir'}/$udom/nohist_courseids";
 2560: 			my %hash;
 2561: 			if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER(),0640)) {
 2562: 			    while (my ($key,$value) = each(%hash)) {
 2563: 				my ($descr,$lasttime)=split(/\:/,$value);
 2564: 				if ($lasttime<$since) { next; }
 2565: 				if ($description eq '.') {
 2566: 				    $qresult.=$key.'='.$descr.'&';
 2567: 				} else {
 2568: 				    my $unescapeVal = &unescape($descr);
 2569: 				    if (eval('$unescapeVal=~/$description/i')) {
 2570: 					$qresult.="$key=$descr&";
 2571: 				    }
 2572: 				}
 2573: 			    }
 2574: 			    if (untie(%hash)) {
 2575: 				chop($qresult);
 2576: 				print $client "$qresult\n";
 2577: 			    } else {
 2578: 				print $client "error: ".($!+0)
 2579: 				    ." untie(GDBM) Failed ".
 2580: 				    "while attempting courseiddump\n";
 2581: 			    }
 2582: 			} else {
 2583: 			    print $client "error: ".($!+0)
 2584: 				." tie(GDBM) Failed ".
 2585: 				"while attempting courseiddump\n";
 2586: 			}
 2587: 		    } else {
 2588: 			Reply($client, "refused\n", $userinput);
 2589: 		       
 2590: 		    }
 2591: # ----------------------------------------------------------------------- idput
 2592: 		} elsif ($userinput =~ /^idput/) {
 2593: 		    if(isClient) {
 2594: 			my ($cmd,$udom,$what)=split(/:/,$userinput);
 2595: 			chomp($what);
 2596: 			$udom=~s/\W//g;
 2597: 			my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
 2598: 			my $now=time;
 2599: 			{
 2600: 			    my $hfh;
 2601: 			    if (
 2602: 				$hfh=IO::File->new(">>$proname.hist")
 2603: 				) { print $hfh "P:$now:$what\n"; }
 2604: 			}
 2605: 			my @pairs=split(/\&/,$what);
 2606: 			my %hash;
 2607: 			if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT(),0640)) {
 2608: 			    foreach my $pair (@pairs) {
 2609: 				my ($key,$value)=split(/=/,$pair);
 2610: 				$hash{$key}=$value;
 2611: 			    }
 2612: 			    if (untie(%hash)) {
 2613: 				print $client "ok\n";
 2614: 			    } else {
 2615: 				print $client "error: ".($!+0)
 2616: 				    ." untie(GDBM) Failed ".
 2617: 				    "while attempting idput\n";
 2618: 			    }
 2619: 			} else {
 2620: 			    print $client "error: ".($!+0)
 2621: 				." tie(GDBM) Failed ".
 2622: 				"while attempting idput\n";
 2623: 			}
 2624: 		    } else {
 2625: 			Reply($client, "refused\n", $userinput);
 2626: 		       
 2627: 		    }
 2628: # ----------------------------------------------------------------------- idget
 2629: 		} elsif ($userinput =~ /^idget/) {
 2630: 		    if(isClient) {
 2631: 			my ($cmd,$udom,$what)=split(/:/,$userinput);
 2632: 			chomp($what);
 2633: 			$udom=~s/\W//g;
 2634: 			my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
 2635: 			my @queries=split(/\&/,$what);
 2636: 			my $qresult='';
 2637: 			my %hash;
 2638: 			if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER(),0640)) {
 2639: 			    for (my $i=0;$i<=$#queries;$i++) {
 2640: 				$qresult.="$hash{$queries[$i]}&";
 2641: 			    }
 2642: 			    if (untie(%hash)) {
 2643: 				$qresult=~s/\&$//;
 2644: 				print $client "$qresult\n";
 2645: 			    } else {
 2646: 				print $client "error: ".($!+0)
 2647: 				    ." untie(GDBM) Failed ".
 2648: 				    "while attempting idget\n";
 2649: 			    }
 2650: 			} else {
 2651: 			    print $client "error: ".($!+0)
 2652: 				." tie(GDBM) Failed ".
 2653: 				"while attempting idget\n";
 2654: 			}
 2655: 		    } else {
 2656: 			Reply($client, "refused\n", $userinput);
 2657: 		       
 2658: 		    }
 2659: # ---------------------------------------------------------------------- tmpput
 2660: 		} elsif ($userinput =~ /^tmpput/) {
 2661: 		    if(isClient) {
 2662: 			my ($cmd,$what)=split(/:/,$userinput);
 2663: 			my $store;
 2664: 			$tmpsnum++;
 2665: 			my $id=$$.'_'.$clientip.'_'.$tmpsnum;
 2666: 			$id=~s/\W/\_/g;
 2667: 			$what=~s/\n//g;
 2668: 			my $execdir=$perlvar{'lonDaemons'};
 2669: 			if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
 2670: 			    print $store $what;
 2671: 			    close $store;
 2672: 			    print $client "$id\n";
 2673: 			}
 2674: 			else {
 2675: 			    print $client "error: ".($!+0)
 2676: 				."IO::File->new Failed ".
 2677: 				"while attempting tmpput\n";
 2678: 			}
 2679: 		    } else {
 2680: 			Reply($client, "refused\n", $userinput);
 2681: 		    
 2682: 		    }
 2683: 		    
 2684: # ---------------------------------------------------------------------- tmpget
 2685: 		} elsif ($userinput =~ /^tmpget/) {
 2686: 		    if(isClient) {
 2687: 			my ($cmd,$id)=split(/:/,$userinput);
 2688: 			chomp($id);
 2689: 			$id=~s/\W/\_/g;
 2690: 			my $store;
 2691: 			my $execdir=$perlvar{'lonDaemons'};
 2692: 			if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
 2693: 			    my $reply=<$store>;
 2694: 			    print $client "$reply\n";
 2695: 			    close $store;
 2696: 			}
 2697: 			else {
 2698: 			    print $client "error: ".($!+0)
 2699: 				."IO::File->new Failed ".
 2700: 				"while attempting tmpget\n";
 2701: 			}
 2702: 		    } else {
 2703: 			Reply($client, "refused\n", $userinput);
 2704: 		      
 2705: 		    }
 2706: # ---------------------------------------------------------------------- tmpdel
 2707: 		} elsif ($userinput =~ /^tmpdel/) {
 2708: 		    if(isClient) {
 2709: 			my ($cmd,$id)=split(/:/,$userinput);
 2710: 			chomp($id);
 2711: 			$id=~s/\W/\_/g;
 2712: 			my $execdir=$perlvar{'lonDaemons'};
 2713: 			if (unlink("$execdir/tmp/$id.tmp")) {
 2714: 			    print $client "ok\n";
 2715: 			} else {
 2716: 			    print $client "error: ".($!+0)
 2717: 				."Unlink tmp Failed ".
 2718: 				"while attempting tmpdel\n";
 2719: 			}
 2720: 		    } else {
 2721: 			Reply($client, "refused\n", $userinput);
 2722: 		     
 2723: 		    }
 2724: # -------------------------------------------------------------------------- ls
 2725: 		} elsif ($userinput =~ /^ls/) {
 2726: 		    if(isClient) {
 2727: 			my ($cmd,$ulsdir)=split(/:/,$userinput);
 2728: 			my $ulsout='';
 2729: 			my $ulsfn;
 2730: 			if (-e $ulsdir) {
 2731: 			    if(-d $ulsdir) {
 2732: 				if (opendir(LSDIR,$ulsdir)) {
 2733: 				    while ($ulsfn=readdir(LSDIR)) {
 2734: 					my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 2735: 					$ulsout.=$ulsfn.'&'.
 2736: 					    join('&',@ulsstats).':';
 2737: 				    }
 2738: 				    closedir(LSDIR);
 2739: 				}
 2740: 			    } else {
 2741: 				my @ulsstats=stat($ulsdir);
 2742: 				$ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 2743: 			    }
 2744: 			} else {
 2745: 			    $ulsout='no_such_dir';
 2746: 			}
 2747: 			if ($ulsout eq '') { $ulsout='empty'; }
 2748: 			print $client "$ulsout\n";
 2749: 		    } else {
 2750: 			Reply($client, "refused\n", $userinput);
 2751: 		     
 2752: 		    }
 2753: # ----------------------------------------------------------------- setannounce
 2754: 		} elsif ($userinput =~ /^setannounce/) {
 2755: 		    if (isClient) {
 2756: 			my ($cmd,$announcement)=split(/:/,$userinput);
 2757: 			chomp($announcement);
 2758: 			$announcement=&unescape($announcement);
 2759: 			if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
 2760: 						    '/announcement.txt')) {
 2761: 			    print $store $announcement;
 2762: 			    close $store;
 2763: 			    print $client "ok\n";
 2764: 			} else {
 2765: 			    print $client "error: ".($!+0)."\n";
 2766: 			}
 2767: 		    } else {
 2768: 			Reply($client, "refused\n", $userinput);
 2769: 		       
 2770: 		    }
 2771: # ------------------------------------------------------------------ Hanging up
 2772: 		} elsif (($userinput =~ /^exit/) ||
 2773: 			 ($userinput =~ /^init/)) { # no restrictions.
 2774: 		    &logthis(
 2775: 			     "Client $clientip ($clientname) hanging up: $userinput");
 2776: 		    print $client "bye\n";
 2777: 		    $client->shutdown(2);        # shutdown the socket forcibly.
 2778: 		    $client->close();
 2779: 		    last;
 2780: 
 2781: # ---------------------------------- set current host/domain
 2782: 		} elsif ($userinput =~ /^sethost:/) {
 2783: 		    if (isClient) {
 2784: 			print $client &sethost($userinput)."\n";
 2785: 		    } else {
 2786: 			print $client "refused\n";
 2787: 		    }
 2788: #---------------------------------- request file (?) version.
 2789: 		} elsif ($userinput =~/^version:/) {
 2790: 		    if (isClient) {
 2791: 			print $client &version($userinput)."\n";
 2792: 		    } else {
 2793: 			print $client "refused\n";
 2794: 		    }
 2795: # ------------------------------------------------------------- unknown command
 2796: 
 2797: 		} else {
 2798: 		    # unknown command
 2799: 		    print $client "unknown_cmd\n";
 2800: 		}
 2801: # -------------------------------------------------------------------- complete
 2802: 		alarm(0);
 2803: 		&status('Listening to '.$clientname);
 2804: 	    }
 2805: # --------------------------------------------- client unknown or fishy, refuse
 2806: 	} else {
 2807: 	    print $client "refused\n";
 2808: 	    $client->close();
 2809: 	    &logthis("<font color=blue>WARNING: "
 2810: 		     ."Rejected client $clientip, closing connection</font>");
 2811: 	}
 2812:     }             
 2813:     
 2814: # =============================================================================
 2815:     
 2816:     &logthis("<font color=red>CRITICAL: "
 2817: 	     ."Disconnect from $clientip ($clientname)</font>");    
 2818:     
 2819:     
 2820:     # this exit is VERY important, otherwise the child will become
 2821:     # a producer of more and more children, forking yourself into
 2822:     # process death.
 2823:     exit;
 2824:     
 2825: }
 2826: 
 2827: 
 2828: #
 2829: #   Checks to see if the input roleput request was to set
 2830: # an author role.  If so, invokes the lchtmldir script to set
 2831: # up a correct public_html 
 2832: # Parameters:
 2833: #    request   - The request sent to the rolesput subchunk.
 2834: #                We're looking for  /domain/_au
 2835: #    domain    - The domain in which the user is having roles doctored.
 2836: #    user      - Name of the user for which the role is being put.
 2837: #    authtype  - The authentication type associated with the user.
 2838: #
 2839: sub ManagePermissions
 2840: {
 2841:     my $request = shift;
 2842:     my $domain  = shift;
 2843:     my $user    = shift;
 2844:     my $authtype= shift;
 2845: 
 2846:     # See if the request is of the form /$domain/_au
 2847:     &logthis("ruequest is $request");
 2848:     if($request =~ /^(\/$domain\/_au)$/) { # It's an author rolesput...
 2849: 	my $execdir = $perlvar{'lonDaemons'};
 2850: 	my $userhome= "/home/$user" ;
 2851: 	&logthis("system $execdir/lchtmldir $userhome $user $authtype");
 2852: 	system("$execdir/lchtmldir $userhome $user $authtype");
 2853:     }
 2854: }
 2855: #
 2856: #   GetAuthType - Determines the authorization type of a user in a domain.
 2857: 
 2858: #     Returns the authorization type or nouser if there is no such user.
 2859: #
 2860: sub GetAuthType 
 2861: {
 2862:     my $domain = shift;
 2863:     my $user   = shift;
 2864: 
 2865:     Debug("GetAuthType( $domain, $user ) \n");
 2866:     my $proname    = &propath($domain, $user); 
 2867:     my $passwdfile = "$proname/passwd";
 2868:     if( -e $passwdfile ) {
 2869: 	my $pf = IO::File->new($passwdfile);
 2870: 	my $realpassword = <$pf>;
 2871: 	chomp($realpassword);
 2872: 	Debug("Password info = $realpassword\n");
 2873: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
 2874: 	Debug("Authtype = $authtype, content = $contentpwd\n");
 2875: 	my $availinfo = '';
 2876: 	if($authtype eq 'krb4' or $authtype eq 'krb5') {
 2877: 	    $availinfo = $contentpwd;
 2878: 	}
 2879: 
 2880: 	return "$authtype:$availinfo";
 2881:     }
 2882:     else {
 2883: 	Debug("Returning nouser");
 2884: 	return "nouser";
 2885:     }
 2886: }
 2887: 
 2888: sub addline {
 2889:     my ($fname,$hostid,$ip,$newline)=@_;
 2890:     my $contents;
 2891:     my $found=0;
 2892:     my $expr='^'.$hostid.':'.$ip.':';
 2893:     $expr =~ s/\./\\\./g;
 2894:     my $sh;
 2895:     if ($sh=IO::File->new("$fname.subscription")) {
 2896: 	while (my $subline=<$sh>) {
 2897: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
 2898: 	}
 2899: 	$sh->close();
 2900:     }
 2901:     $sh=IO::File->new(">$fname.subscription");
 2902:     if ($contents) { print $sh $contents; }
 2903:     if ($newline) { print $sh $newline; }
 2904:     $sh->close();
 2905:     return $found;
 2906: }
 2907: 
 2908: sub getchat {
 2909:     my ($cdom,$cname,$udom,$uname)=@_;
 2910:     my %hash;
 2911:     my $proname=&propath($cdom,$cname);
 2912:     my @entries=();
 2913:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
 2914: 	    &GDBM_READER(),0640)) {
 2915: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
 2916: 	untie %hash;
 2917:     }
 2918:     my @participants=();
 2919:     my $cutoff=time-60;
 2920:     if (tie(%hash,'GDBM_File',"$proname/nohist_inchatroom.db",
 2921: 	    &GDBM_WRCREAT(),0640)) {
 2922:         $hash{$uname.':'.$udom}=time;
 2923:         foreach (sort keys %hash) {
 2924: 	    if ($hash{$_}>$cutoff) {
 2925: 		$participants[$#participants+1]='active_participant:'.$_;
 2926:             }
 2927:         }
 2928:         untie %hash;
 2929:     }
 2930:     return (@participants,@entries);
 2931: }
 2932: 
 2933: sub chatadd {
 2934:     my ($cdom,$cname,$newchat)=@_;
 2935:     my %hash;
 2936:     my $proname=&propath($cdom,$cname);
 2937:     my @entries=();
 2938:     my $time=time;
 2939:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
 2940: 	    &GDBM_WRCREAT(),0640)) {
 2941: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
 2942: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
 2943: 	my ($thentime,$idnum)=split(/\_/,$lastid);
 2944: 	my $newid=$time.'_000000';
 2945: 	if ($thentime==$time) {
 2946: 	    $idnum=~s/^0+//;
 2947: 	    $idnum++;
 2948: 	    $idnum=substr('000000'.$idnum,-6,6);
 2949: 	    $newid=$time.'_'.$idnum;
 2950: 	}
 2951: 	$hash{$newid}=$newchat;
 2952: 	my $expired=$time-3600;
 2953: 	foreach (keys %hash) {
 2954: 	    my ($thistime)=($_=~/(\d+)\_/);
 2955: 	    if ($thistime<$expired) {
 2956: 		delete $hash{$_};
 2957: 	    }
 2958: 	}
 2959: 	untie %hash;
 2960:     }
 2961:     {
 2962: 	my $hfh;
 2963: 	if ($hfh=IO::File->new(">>$proname/chatroom.log")) { 
 2964: 	    print $hfh "$time:".&unescape($newchat)."\n";
 2965: 	}
 2966:     }
 2967: }
 2968: 
 2969: sub unsub {
 2970:     my ($fname,$clientip)=@_;
 2971:     my $result;
 2972:     if (unlink("$fname.$clientname")) {
 2973: 	$result="ok\n";
 2974:     } else {
 2975: 	$result="not_subscribed\n";
 2976:     }
 2977:     if (-e "$fname.subscription") {
 2978: 	my $found=&addline($fname,$clientname,$clientip,'');
 2979: 	if ($found) { $result="ok\n"; }
 2980:     } else {
 2981: 	if ($result != "ok\n") { $result="not_subscribed\n"; }
 2982:     }
 2983:     return $result;
 2984: }
 2985: 
 2986: sub currentversion {
 2987:     my $fname=shift;
 2988:     my $version=-1;
 2989:     my $ulsdir='';
 2990:     if ($fname=~/^(.+)\/[^\/]+$/) {
 2991:        $ulsdir=$1;
 2992:     }
 2993:     my ($fnamere1,$fnamere2);
 2994:     # remove version if already specified
 2995:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
 2996:     # get the bits that go before and after the version number
 2997:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
 2998: 	$fnamere1=$1;
 2999: 	$fnamere2='.'.$2;
 3000:     }
 3001:     if (-e $fname) { $version=1; }
 3002:     if (-e $ulsdir) {
 3003: 	if(-d $ulsdir) {
 3004: 	    if (opendir(LSDIR,$ulsdir)) {
 3005: 		my $ulsfn;
 3006: 		while ($ulsfn=readdir(LSDIR)) {
 3007: # see if this is a regular file (ignore links produced earlier)
 3008: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
 3009: 		    unless (-l $thisfile) {
 3010: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
 3011: 			    if ($1>$version) { $version=$1; }
 3012: 			}
 3013: 		    }
 3014: 		}
 3015: 		closedir(LSDIR);
 3016: 		$version++;
 3017: 	    }
 3018: 	}
 3019:     }
 3020:     return $version;
 3021: }
 3022: 
 3023: sub thisversion {
 3024:     my $fname=shift;
 3025:     my $version=-1;
 3026:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
 3027: 	$version=$1;
 3028:     }
 3029:     return $version;
 3030: }
 3031: 
 3032: sub subscribe {
 3033:     my ($userinput,$clientip)=@_;
 3034:     my $result;
 3035:     my ($cmd,$fname)=split(/:/,$userinput);
 3036:     my $ownership=&ishome($fname);
 3037:     if ($ownership eq 'owner') {
 3038: # explitly asking for the current version?
 3039:         unless (-e $fname) {
 3040:             my $currentversion=&currentversion($fname);
 3041: 	    if (&thisversion($fname)==$currentversion) {
 3042:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
 3043: 		    my $root=$1;
 3044:                     my $extension=$2;
 3045:                     symlink($root.'.'.$extension,
 3046:                             $root.'.'.$currentversion.'.'.$extension);
 3047:                     unless ($extension=~/\.meta$/) {
 3048:                        symlink($root.'.'.$extension.'.meta',
 3049:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
 3050: 		    }
 3051:                 }
 3052:             }
 3053:         }
 3054: 	if (-e $fname) {
 3055: 	    if (-d $fname) {
 3056: 		$result="directory\n";
 3057: 	    } else {
 3058: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
 3059: 		my $now=time;
 3060: 		my $found=&addline($fname,$clientname,$clientip,
 3061: 				   "$clientname:$clientip:$now\n");
 3062: 		if ($found) { $result="$fname\n"; }
 3063: 		# if they were subscribed to only meta data, delete that
 3064:                 # subscription, when you subscribe to a file you also get
 3065:                 # the metadata
 3066: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
 3067: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
 3068: 		$fname="http://$thisserver/".$fname;
 3069: 		$result="$fname\n";
 3070: 	    }
 3071: 	} else {
 3072: 	    $result="not_found\n";
 3073: 	}
 3074:     } else {
 3075: 	$result="rejected\n";
 3076:     }
 3077:     return $result;
 3078: }
 3079: 
 3080: sub make_passwd_file {
 3081:     my ($uname, $umode,$npass,$passfilename)=@_;
 3082:     my $result="ok\n";
 3083:     if ($umode eq 'krb4' or $umode eq 'krb5') {
 3084: 	{
 3085: 	    my $pf = IO::File->new(">$passfilename");
 3086: 	    print $pf "$umode:$npass\n";
 3087: 	}
 3088:     } elsif ($umode eq 'internal') {
 3089: 	my $salt=time;
 3090: 	$salt=substr($salt,6,2);
 3091: 	my $ncpass=crypt($npass,$salt);
 3092: 	{
 3093: 	    &Debug("Creating internal auth");
 3094: 	    my $pf = IO::File->new(">$passfilename");
 3095: 	    print $pf "internal:$ncpass\n"; 
 3096: 	}
 3097:     } elsif ($umode eq 'localauth') {
 3098: 	{
 3099: 	    my $pf = IO::File->new(">$passfilename");
 3100: 	    print $pf "localauth:$npass\n";
 3101: 	}
 3102:     } elsif ($umode eq 'unix') {
 3103: 	{
 3104: 	    my $execpath="$perlvar{'lonDaemons'}/"."lcuseradd";
 3105: 	    {
 3106: 		&Debug("Executing external: ".$execpath);
 3107: 		&Debug("user  = ".$uname.", Password =". $npass);
 3108: 		my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
 3109: 		print $se "$uname\n";
 3110: 		print $se "$npass\n";
 3111: 		print $se "$npass\n";
 3112: 	    }
 3113: 	    my $useraddok = $?;
 3114: 	    if($useraddok > 0) {
 3115: 		&logthis("Failed lcuseradd: ".&lcuseraddstrerror($useraddok));
 3116: 	    }
 3117: 	    my $pf = IO::File->new(">$passfilename");
 3118: 	    print $pf "unix:\n";
 3119: 	}
 3120:     } elsif ($umode eq 'none') {
 3121: 	{
 3122: 	    my $pf = IO::File->new(">$passfilename");
 3123: 	    print $pf "none:\n";
 3124: 	}
 3125:     } else {
 3126: 	$result="auth_mode_error\n";
 3127:     }
 3128:     return $result;
 3129: }
 3130: 
 3131: sub sethost {
 3132:     my ($remotereq) = @_;
 3133:     my (undef,$hostid)=split(/:/,$remotereq);
 3134:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
 3135:     if ($hostip{$perlvar{'lonHostID'}} eq $hostip{$hostid}) {
 3136: 	$currenthostid=$hostid;
 3137: 	$currentdomainid=$hostdom{$hostid};
 3138: 	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
 3139:     } else {
 3140: 	&logthis("Requested host id $hostid not an alias of ".
 3141: 		 $perlvar{'lonHostID'}." refusing connection");
 3142: 	return 'unable_to_set';
 3143:     }
 3144:     return 'ok';
 3145: }
 3146: 
 3147: sub version {
 3148:     my ($userinput)=@_;
 3149:     $remoteVERSION=(split(/:/,$userinput))[1];
 3150:     return "version:$VERSION";
 3151: }
 3152: 
 3153: #There is a copy of this in lonnet.pm
 3154: sub userload {
 3155:     my $numusers=0;
 3156:     {
 3157: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
 3158: 	my $filename;
 3159: 	my $curtime=time;
 3160: 	while ($filename=readdir(LONIDS)) {
 3161: 	    if ($filename eq '.' || $filename eq '..') {next;}
 3162: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
 3163: 	    if ($curtime-$mtime < 1800) { $numusers++; }
 3164: 	}
 3165: 	closedir(LONIDS);
 3166:     }
 3167:     my $userloadpercent=0;
 3168:     my $maxuserload=$perlvar{'lonUserLoadLim'};
 3169:     if ($maxuserload) {
 3170: 	$userloadpercent=100*$numusers/$maxuserload;
 3171:     }
 3172:     $userloadpercent=sprintf("%.2f",$userloadpercent);
 3173:     return $userloadpercent;
 3174: }
 3175: 
 3176: # ----------------------------------- POD (plain old documentation, CPAN style)
 3177: 
 3178: =head1 NAME
 3179: 
 3180: lond - "LON Daemon" Server (port "LOND" 5663)
 3181: 
 3182: =head1 SYNOPSIS
 3183: 
 3184: Usage: B<lond>
 3185: 
 3186: Should only be run as user=www.  This is a command-line script which
 3187: is invoked by B<loncron>.  There is no expectation that a typical user
 3188: will manually start B<lond> from the command-line.  (In other words,
 3189: DO NOT START B<lond> YOURSELF.)
 3190: 
 3191: =head1 DESCRIPTION
 3192: 
 3193: There are two characteristics associated with the running of B<lond>,
 3194: PROCESS MANAGEMENT (starting, stopping, handling child processes)
 3195: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
 3196: subscriptions, etc).  These are described in two large
 3197: sections below.
 3198: 
 3199: B<PROCESS MANAGEMENT>
 3200: 
 3201: Preforker - server who forks first. Runs as a daemon. HUPs.
 3202: Uses IDEA encryption
 3203: 
 3204: B<lond> forks off children processes that correspond to the other servers
 3205: in the network.  Management of these processes can be done at the
 3206: parent process level or the child process level.
 3207: 
 3208: B<logs/lond.log> is the location of log messages.
 3209: 
 3210: The process management is now explained in terms of linux shell commands,
 3211: subroutines internal to this code, and signal assignments:
 3212: 
 3213: =over 4
 3214: 
 3215: =item *
 3216: 
 3217: PID is stored in B<logs/lond.pid>
 3218: 
 3219: This is the process id number of the parent B<lond> process.
 3220: 
 3221: =item *
 3222: 
 3223: SIGTERM and SIGINT
 3224: 
 3225: Parent signal assignment:
 3226:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 3227: 
 3228: Child signal assignment:
 3229:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
 3230: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
 3231:  to restart a new child.)
 3232: 
 3233: Command-line invocations:
 3234:  B<kill> B<-s> SIGTERM I<PID>
 3235:  B<kill> B<-s> SIGINT I<PID>
 3236: 
 3237: Subroutine B<HUNTSMAN>:
 3238:  This is only invoked for the B<lond> parent I<PID>.
 3239: This kills all the children, and then the parent.
 3240: The B<lonc.pid> file is cleared.
 3241: 
 3242: =item *
 3243: 
 3244: SIGHUP
 3245: 
 3246: Current bug:
 3247:  This signal can only be processed the first time
 3248: on the parent process.  Subsequent SIGHUP signals
 3249: have no effect.
 3250: 
 3251: Parent signal assignment:
 3252:  $SIG{HUP}  = \&HUPSMAN;
 3253: 
 3254: Child signal assignment:
 3255:  none (nothing happens)
 3256: 
 3257: Command-line invocations:
 3258:  B<kill> B<-s> SIGHUP I<PID>
 3259: 
 3260: Subroutine B<HUPSMAN>:
 3261:  This is only invoked for the B<lond> parent I<PID>,
 3262: This kills all the children, and then the parent.
 3263: The B<lond.pid> file is cleared.
 3264: 
 3265: =item *
 3266: 
 3267: SIGUSR1
 3268: 
 3269: Parent signal assignment:
 3270:  $SIG{USR1} = \&USRMAN;
 3271: 
 3272: Child signal assignment:
 3273:  $SIG{USR1}= \&logstatus;
 3274: 
 3275: Command-line invocations:
 3276:  B<kill> B<-s> SIGUSR1 I<PID>
 3277: 
 3278: Subroutine B<USRMAN>:
 3279:  When invoked for the B<lond> parent I<PID>,
 3280: SIGUSR1 is sent to all the children, and the status of
 3281: each connection is logged.
 3282: 
 3283: =item *
 3284: 
 3285: SIGUSR2
 3286: 
 3287: Parent Signal assignment:
 3288:     $SIG{USR2} = \&UpdateHosts
 3289: 
 3290: Child signal assignment:
 3291:     NONE
 3292: 
 3293: 
 3294: =item *
 3295: 
 3296: SIGCHLD
 3297: 
 3298: Parent signal assignment:
 3299:  $SIG{CHLD} = \&REAPER;
 3300: 
 3301: Child signal assignment:
 3302:  none
 3303: 
 3304: Command-line invocations:
 3305:  B<kill> B<-s> SIGCHLD I<PID>
 3306: 
 3307: Subroutine B<REAPER>:
 3308:  This is only invoked for the B<lond> parent I<PID>.
 3309: Information pertaining to the child is removed.
 3310: The socket port is cleaned up.
 3311: 
 3312: =back
 3313: 
 3314: B<SERVER-SIDE ACTIVITIES>
 3315: 
 3316: Server-side information can be accepted in an encrypted or non-encrypted
 3317: method.
 3318: 
 3319: =over 4
 3320: 
 3321: =item ping
 3322: 
 3323: Query a client in the hosts.tab table; "Are you there?"
 3324: 
 3325: =item pong
 3326: 
 3327: Respond to a ping query.
 3328: 
 3329: =item ekey
 3330: 
 3331: Read in encrypted key, make cipher.  Respond with a buildkey.
 3332: 
 3333: =item load
 3334: 
 3335: Respond with CPU load based on a computation upon /proc/loadavg.
 3336: 
 3337: =item currentauth
 3338: 
 3339: Reply with current authentication information (only over an
 3340: encrypted channel).
 3341: 
 3342: =item auth
 3343: 
 3344: Only over an encrypted channel, reply as to whether a user's
 3345: authentication information can be validated.
 3346: 
 3347: =item passwd
 3348: 
 3349: Allow for a password to be set.
 3350: 
 3351: =item makeuser
 3352: 
 3353: Make a user.
 3354: 
 3355: =item passwd
 3356: 
 3357: Allow for authentication mechanism and password to be changed.
 3358: 
 3359: =item home
 3360: 
 3361: Respond to a question "are you the home for a given user?"
 3362: 
 3363: =item update
 3364: 
 3365: Update contents of a subscribed resource.
 3366: 
 3367: =item unsubscribe
 3368: 
 3369: The server is unsubscribing from a resource.
 3370: 
 3371: =item subscribe
 3372: 
 3373: The server is subscribing to a resource.
 3374: 
 3375: =item log
 3376: 
 3377: Place in B<logs/lond.log>
 3378: 
 3379: =item put
 3380: 
 3381: stores hash in namespace
 3382: 
 3383: =item rolesput
 3384: 
 3385: put a role into a user's environment
 3386: 
 3387: =item get
 3388: 
 3389: returns hash with keys from array
 3390: reference filled in from namespace
 3391: 
 3392: =item eget
 3393: 
 3394: returns hash with keys from array
 3395: reference filled in from namesp (encrypts the return communication)
 3396: 
 3397: =item rolesget
 3398: 
 3399: get a role from a user's environment
 3400: 
 3401: =item del
 3402: 
 3403: deletes keys out of array from namespace
 3404: 
 3405: =item keys
 3406: 
 3407: returns namespace keys
 3408: 
 3409: =item dump
 3410: 
 3411: dumps the complete (or key matching regexp) namespace into a hash
 3412: 
 3413: =item store
 3414: 
 3415: stores hash permanently
 3416: for this url; hashref needs to be given and should be a \%hashname; the
 3417: remaining args aren't required and if they aren't passed or are '' they will
 3418: be derived from the ENV
 3419: 
 3420: =item restore
 3421: 
 3422: returns a hash for a given url
 3423: 
 3424: =item querysend
 3425: 
 3426: Tells client about the lonsql process that has been launched in response
 3427: to a sent query.
 3428: 
 3429: =item queryreply
 3430: 
 3431: Accept information from lonsql and make appropriate storage in temporary
 3432: file space.
 3433: 
 3434: =item idput
 3435: 
 3436: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
 3437: for each student, defined perhaps by the institutional Registrar.)
 3438: 
 3439: =item idget
 3440: 
 3441: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
 3442: for each student, defined perhaps by the institutional Registrar.)
 3443: 
 3444: =item tmpput
 3445: 
 3446: Accept and store information in temporary space.
 3447: 
 3448: =item tmpget
 3449: 
 3450: Send along temporarily stored information.
 3451: 
 3452: =item ls
 3453: 
 3454: List part of a user's directory.
 3455: 
 3456: =item pushtable
 3457: 
 3458: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
 3459: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
 3460: must be restored manually in case of a problem with the new table file.
 3461: pushtable requires that the request be encrypted and validated via
 3462: ValidateManager.  The form of the command is:
 3463: enc:pushtable tablename <tablecontents> \n
 3464: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
 3465: cleartext newline.
 3466: 
 3467: =item Hanging up (exit or init)
 3468: 
 3469: What to do when a client tells the server that they (the client)
 3470: are leaving the network.
 3471: 
 3472: =item unknown command
 3473: 
 3474: If B<lond> is sent an unknown command (not in the list above),
 3475: it replys to the client "unknown_cmd".
 3476: 
 3477: 
 3478: =item UNKNOWN CLIENT
 3479: 
 3480: If the anti-spoofing algorithm cannot verify the client,
 3481: the client is rejected (with a "refused" message sent
 3482: to the client, and the connection is closed.
 3483: 
 3484: =back
 3485: 
 3486: =head1 PREREQUISITES
 3487: 
 3488: IO::Socket
 3489: IO::File
 3490: Apache::File
 3491: Symbol
 3492: POSIX
 3493: Crypt::IDEA
 3494: LWP::UserAgent()
 3495: GDBM_File
 3496: Authen::Krb4
 3497: Authen::Krb5
 3498: 
 3499: =head1 COREQUISITES
 3500: 
 3501: =head1 OSNAMES
 3502: 
 3503: linux
 3504: 
 3505: =head1 SCRIPT CATEGORIES
 3506: 
 3507: Server/Process
 3508: 
 3509: =cut

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