File:  [LON-CAPA] / loncom / lond
Revision 1.179: download - view: text, annotated - select for diffs
Tue Feb 24 16:53:16 2004 UTC (20 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- don't study regexp, we won't be tested on it

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

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