File:  [LON-CAPA] / loncom / lond
Revision 1.486: download - view: text, annotated - select for diffs
Tue Feb 28 15:54:07 2012 UTC (12 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Use hostname in place of IP address to avoid a "certificate verify failed"
  issue with certain SSL configurations.

    1: #!/usr/bin/perl
    2: # The LearningOnline Network
    3: # lond "LON Daemon" Server (port "LOND" 5663)
    4: #
    5: # $Id: lond,v 1.486 2012/02/28 15:54:07 raeburn 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: 
   19: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   20: # GNU General Public License for more details.
   21: #
   22: # You should have received a copy of the GNU General Public License
   23: # along with LON-CAPA; if not, write to the Free Software
   24: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   25: #
   26: # /home/httpd/html/adm/gpl.txt
   27: #
   28: 
   29: 
   30: # http://www.lon-capa.org/
   31: #
   32: 
   33: use strict;
   34: use lib '/home/httpd/lib/perl/';
   35: use LONCAPA;
   36: use LONCAPA::Configuration;
   37: 
   38: use IO::Socket;
   39: use IO::File;
   40: #use Apache::File;
   41: use POSIX;
   42: use Crypt::IDEA;
   43: use LWP::UserAgent();
   44: use Digest::MD5 qw(md5_hex);
   45: use GDBM_File;
   46: use Authen::Krb5;
   47: use localauth;
   48: use localenroll;
   49: use localstudentphoto;
   50: use File::Copy;
   51: use File::Find;
   52: use LONCAPA::lonlocal;
   53: use LONCAPA::lonssl;
   54: use Fcntl qw(:flock);
   55: use Apache::lonnet;
   56: use Mail::Send;
   57: 
   58: my $DEBUG = 0;		       # Non zero to enable debug log entries.
   59: 
   60: my $status='';
   61: my $lastlog='';
   62: 
   63: my $VERSION='$Revision: 1.486 $'; #' stupid emacs
   64: my $remoteVERSION;
   65: my $currenthostid="default";
   66: my $currentdomainid;
   67: 
   68: my $client;
   69: my $clientip;			# IP address of client.
   70: my $clientname;			# LonCAPA name of client.
   71: my $clientversion;              # LonCAPA version running on client.
   72: my $clienthomedom;              # LonCAPA domain of homeID for client. 
   73:                                 # primary library server. 
   74: 
   75: my $server;
   76: 
   77: my $keymode;
   78: 
   79: my $cipher;			# Cipher key negotiated with client
   80: my $tmpsnum = 0;		# Id of tmpputs.
   81: 
   82: # 
   83: #   Connection type is:
   84: #      client                   - All client actions are allowed
   85: #      manager                  - only management functions allowed.
   86: #      both                     - Both management and client actions are allowed
   87: #
   88: 
   89: my $ConnectionType;
   90: 
   91: my %managers;			# Ip -> manager names
   92: 
   93: my %perlvar;			# Will have the apache conf defined perl vars.
   94: 
   95: my $dist;
   96: 
   97: #
   98: #   The hash below is used for command dispatching, and is therefore keyed on the request keyword.
   99: #    Each element of the hash contains a reference to an array that contains:
  100: #          A reference to a sub that executes the request corresponding to the keyword.
  101: #          A flag that is true if the request must be encoded to be acceptable.
  102: #          A mask with bits as follows:
  103: #                      CLIENT_OK    - Set when the function is allowed by ordinary clients
  104: #                      MANAGER_OK   - Set when the function is allowed to manager clients.
  105: #
  106: my $CLIENT_OK  = 1;
  107: my $MANAGER_OK = 2;
  108: my %Dispatcher;
  109: 
  110: 
  111: #
  112: #  The array below are password error strings."
  113: #
  114: my $lastpwderror    = 13;		# Largest error number from lcpasswd.
  115: my @passwderrors = ("ok",
  116: 		   "pwchange_failure - lcpasswd must be run as user 'www'",
  117: 		   "pwchange_failure - lcpasswd got incorrect number of arguments",
  118: 		   "pwchange_failure - lcpasswd did not get the right nubmer of input text lines",
  119: 		   "pwchange_failure - lcpasswd too many simultaneous pwd changes in progress",
  120: 		   "pwchange_failure - lcpasswd User does not exist.",
  121: 		   "pwchange_failure - lcpasswd Incorrect current passwd",
  122: 		   "pwchange_failure - lcpasswd Unable to su to root.",
  123: 		   "pwchange_failure - lcpasswd Cannot set new passwd.",
  124: 		   "pwchange_failure - lcpasswd Username has invalid characters",
  125: 		   "pwchange_failure - lcpasswd Invalid characters in password",
  126: 		   "pwchange_failure - lcpasswd User already exists", 
  127:                    "pwchange_failure - lcpasswd Something went wrong with user addition.",
  128: 		   "pwchange_failure - lcpasswd Password mismatch",
  129: 		   "pwchange_failure - lcpasswd Error filename is invalid");
  130: 
  131: 
  132: #  The array below are lcuseradd error strings.:
  133: 
  134: my $lastadderror = 13;
  135: my @adderrors    = ("ok",
  136: 		    "User ID mismatch, lcuseradd must run as user www",
  137: 		    "lcuseradd Incorrect number of command line parameters must be 3",
  138: 		    "lcuseradd Incorrect number of stdinput lines, must be 3",
  139: 		    "lcuseradd Too many other simultaneous pwd changes in progress",
  140: 		    "lcuseradd User does not exist",
  141: 		    "lcuseradd Unable to make www member of users's group",
  142: 		    "lcuseradd Unable to su to root",
  143: 		    "lcuseradd Unable to set password",
  144: 		    "lcuseradd Username has invalid characters",
  145: 		    "lcuseradd Password has an invalid character",
  146: 		    "lcuseradd User already exists",
  147: 		    "lcuseradd Could not add user.",
  148: 		    "lcuseradd Password mismatch");
  149: 
  150: 
  151: # This array are the errors from lcinstallfile:
  152: 
  153: my @installerrors = ("ok",
  154: 		     "Initial user id of client not that of www",
  155: 		     "Usage error, not enough command line arguments",
  156: 		     "Source file name does not exist",
  157: 		     "Destination file name does not exist",
  158: 		     "Some file operation failed",
  159: 		     "Invalid table filename."
  160: 		     );
  161: 
  162: #
  163: #   Statistics that are maintained and dislayed in the status line.
  164: #
  165: my $Transactions = 0;		# Number of attempted transactions.
  166: my $Failures     = 0;		# Number of transcations failed.
  167: 
  168: #   ResetStatistics: 
  169: #      Resets the statistics counters:
  170: #
  171: sub ResetStatistics {
  172:     $Transactions = 0;
  173:     $Failures     = 0;
  174: }
  175: 
  176: #------------------------------------------------------------------------
  177: #
  178: #   LocalConnection
  179: #     Completes the formation of a locally authenticated connection.
  180: #     This function will ensure that the 'remote' client is really the
  181: #     local host.  If not, the connection is closed, and the function fails.
  182: #     If so, initcmd is parsed for the name of a file containing the
  183: #     IDEA session key.  The fie is opened, read, deleted and the session
  184: #     key returned to the caller.
  185: #
  186: # Parameters:
  187: #   $Socket      - Socket open on client.
  188: #   $initcmd     - The full text of the init command.
  189: #
  190: # Returns:
  191: #     IDEA session key on success.
  192: #     undef on failure.
  193: #
  194: sub LocalConnection {
  195:     my ($Socket, $initcmd) = @_;
  196:     Debug("Attempting local connection: $initcmd client: $clientip");
  197:     if($clientip ne "127.0.0.1") {
  198: 	&logthis('<font color="red"> LocalConnection rejecting non local: '
  199: 		 ."$clientip ne 127.0.0.1 </font>");
  200: 	close $Socket;
  201: 	return undef;
  202:     }  else {
  203: 	chomp($initcmd);	# Get rid of \n in filename.
  204: 	my ($init, $type, $name) = split(/:/, $initcmd);
  205: 	Debug(" Init command: $init $type $name ");
  206: 
  207: 	# Require that $init = init, and $type = local:  Otherwise
  208: 	# the caller is insane:
  209: 
  210: 	if(($init ne "init") && ($type ne "local")) {
  211: 	    &logthis('<font color = "red"> LocalConnection: caller is insane! '
  212: 		     ."init = $init, and type = $type </font>");
  213: 	    close($Socket);;
  214: 	    return undef;
  215: 		
  216: 	}
  217: 	#  Now get the key filename:
  218: 
  219: 	my $IDEAKey = lonlocal::ReadKeyFile($name);
  220: 	return $IDEAKey;
  221:     }
  222: }
  223: #------------------------------------------------------------------------------
  224: #
  225: #  SSLConnection
  226: #   Completes the formation of an ssh authenticated connection. The
  227: #   socket is promoted to an ssl socket.  If this promotion and the associated
  228: #   certificate exchange are successful, the IDEA key is generated and sent
  229: #   to the remote peer via the SSL tunnel. The IDEA key is also returned to
  230: #   the caller after the SSL tunnel is torn down.
  231: #
  232: # Parameters:
  233: #   Name              Type             Purpose
  234: #   $Socket          IO::Socket::INET  Plaintext socket.
  235: #
  236: # Returns:
  237: #    IDEA key on success.
  238: #    undef on failure.
  239: #
  240: sub SSLConnection {
  241:     my $Socket   = shift;
  242: 
  243:     Debug("SSLConnection: ");
  244:     my $KeyFile         = lonssl::KeyFile();
  245:     if(!$KeyFile) {
  246: 	my $err = lonssl::LastError();
  247: 	&logthis("<font color=\"red\"> CRITICAL"
  248: 		 ."Can't get key file $err </font>");
  249: 	return undef;
  250:     }
  251:     my ($CACertificate,
  252: 	$Certificate) = lonssl::CertificateFile();
  253: 
  254: 
  255:     # If any of the key, certificate or certificate authority 
  256:     # certificate filenames are not defined, this can't work.
  257: 
  258:     if((!$Certificate) || (!$CACertificate)) {
  259: 	my $err = lonssl::LastError();
  260: 	&logthis("<font color=\"red\"> CRITICAL"
  261: 		 ."Can't get certificates: $err </font>");
  262: 
  263: 	return undef;
  264:     }
  265:     Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
  266: 
  267:     # Indicate to our peer that we can procede with
  268:     # a transition to ssl authentication:
  269: 
  270:     print $Socket "ok:ssl\n";
  271: 
  272:     Debug("Approving promotion -> ssl");
  273:     #  And do so:
  274: 
  275:     my $SSLSocket = lonssl::PromoteServerSocket($Socket,
  276: 						$CACertificate,
  277: 						$Certificate,
  278: 						$KeyFile);
  279:     if(! ($SSLSocket) ) {	# SSL socket promotion failed.
  280: 	my $err = lonssl::LastError();
  281: 	&logthis("<font color=\"red\"> CRITICAL "
  282: 		 ."SSL Socket promotion failed: $err </font>");
  283: 	return undef;
  284:     }
  285:     Debug("SSL Promotion successful");
  286: 
  287:     # 
  288:     #  The only thing we'll use the socket for is to send the IDEA key
  289:     #  to the peer:
  290: 
  291:     my $Key = lonlocal::CreateCipherKey();
  292:     print $SSLSocket "$Key\n";
  293: 
  294:     lonssl::Close($SSLSocket); 
  295: 
  296:     Debug("Key exchange complete: $Key");
  297: 
  298:     return $Key;
  299: }
  300: #
  301: #     InsecureConnection: 
  302: #        If insecure connections are allowd,
  303: #        exchange a challenge with the client to 'validate' the
  304: #        client (not really, but that's the protocol):
  305: #        We produce a challenge string that's sent to the client.
  306: #        The client must then echo the challenge verbatim to us.
  307: #
  308: #  Parameter:
  309: #      Socket      - Socket open on the client.
  310: #  Returns:
  311: #      1           - success.
  312: #      0           - failure (e.g.mismatch or insecure not allowed).
  313: #
  314: sub InsecureConnection {
  315:     my $Socket  =  shift;
  316: 
  317:     #   Don't even start if insecure connections are not allowed.
  318: 
  319:     if(! $perlvar{londAllowInsecure}) {	# Insecure connections not allowed.
  320: 	return 0;
  321:     }
  322: 
  323:     #   Fabricate a challenge string and send it..
  324: 
  325:     my $challenge = "$$".time;	# pid + time.
  326:     print $Socket "$challenge\n";
  327:     &status("Waiting for challenge reply");
  328: 
  329:     my $answer = <$Socket>;
  330:     $answer    =~s/\W//g;
  331:     if($challenge eq $answer) {
  332: 	return 1;
  333:     } else {
  334: 	logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
  335: 	&status("No challenge reqply");
  336: 	return 0;
  337:     }
  338:     
  339: 
  340: }
  341: #
  342: #   Safely execute a command (as long as it's not a shel command and doesn
  343: #   not require/rely on shell escapes.   The function operates by doing a
  344: #   a pipe based fork and capturing stdout and stderr  from the pipe.
  345: #
  346: # Formal Parameters:
  347: #     $line                    - A line of text to be executed as a command.
  348: # Returns:
  349: #     The output from that command.  If the output is multiline the caller
  350: #     must know how to split up the output.
  351: #
  352: #
  353: sub execute_command {
  354:     my ($line)    = @_;
  355:     my @words     = split(/\s/, $line);	# Bust the command up into words.
  356:     my $output    = "";
  357: 
  358:     my $pid = open(CHILD, "-|");
  359:     
  360:     if($pid) {			# Parent process
  361: 	Debug("In parent process for execute_command");
  362: 	my @data = <CHILD>;	# Read the child's outupt...
  363: 	close CHILD;
  364: 	foreach my $output_line (@data) {
  365: 	    Debug("Adding $output_line");
  366: 	    $output .= $output_line; # Presumably has a \n on it.
  367: 	}
  368: 
  369:     } else {			# Child process
  370: 	close (STDERR);
  371: 	open  (STDERR, ">&STDOUT");# Combine stderr, and stdout...
  372: 	exec(@words);		# won't return.
  373:     }
  374:     return $output;
  375: }
  376: 
  377: 
  378: #   GetCertificate: Given a transaction that requires a certificate,
  379: #   this function will extract the certificate from the transaction
  380: #   request.  Note that at this point, the only concept of a certificate
  381: #   is the hostname to which we are connected.
  382: #
  383: #   Parameter:
  384: #      request   - The request sent by our client (this parameterization may
  385: #                  need to change when we really use a certificate granting
  386: #                  authority.
  387: #
  388: sub GetCertificate {
  389:     my $request = shift;
  390: 
  391:     return $clientip;
  392: }
  393: 
  394: #
  395: #   Return true if client is a manager.
  396: #
  397: sub isManager {
  398:     return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
  399: }
  400: #
  401: #   Return tru if client can do client functions
  402: #
  403: sub isClient {
  404:     return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
  405: }
  406: 
  407: 
  408: #
  409: #   ReadManagerTable: Reads in the current manager table. For now this is
  410: #                     done on each manager authentication because:
  411: #                     - These authentications are not frequent
  412: #                     - This allows dynamic changes to the manager table
  413: #                       without the need to signal to the lond.
  414: #
  415: sub ReadManagerTable {
  416: 
  417:     &Debug("Reading manager table");
  418:     #   Clean out the old table first..
  419: 
  420:    foreach my $key (keys %managers) {
  421:       delete $managers{$key};
  422:    }
  423: 
  424:    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
  425:    if (!open (MANAGERS, $tablename)) {
  426:        my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
  427:        if (&Apache::lonnet::is_LC_dns($hostname)) {
  428:            &logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
  429:        }
  430:        return;
  431:    }
  432:    while(my $host = <MANAGERS>) {
  433:       chomp($host);
  434:       if ($host =~ "^#") {                  # Comment line.
  435:          next;
  436:       }
  437:       if (!defined &Apache::lonnet::get_host_ip($host)) { # This is a non cluster member
  438: 	    #  The entry is of the form:
  439: 	    #    cluname:hostname
  440: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
  441: 	    #            the host key.
  442: 	    #  hostname- The dns name of the host.
  443: 	    #
  444:           my($cluname, $dnsname) = split(/:/, $host);
  445:           
  446:           my $ip = gethostbyname($dnsname);
  447:           if(defined($ip)) {                 # bad names don't deserve entry.
  448:             my $hostip = inet_ntoa($ip);
  449:             $managers{$hostip} = $cluname;
  450:             logthis('<font color="green"> registering manager '.
  451:                     "$dnsname as $cluname with $hostip </font>\n");
  452:          }
  453:       } else {
  454:          logthis('<font color="green"> existing host'." $host</font>\n");
  455:          $managers{&Apache::lonnet::get_host_ip($host)} = $host;  # Use info from cluster tab if cluster memeber
  456:       }
  457:    }
  458: }
  459: 
  460: #
  461: #  ValidManager: Determines if a given certificate represents a valid manager.
  462: #                in this primitive implementation, the 'certificate' is
  463: #                just the connecting loncapa client name.  This is checked
  464: #                against a valid client list in the configuration.
  465: #
  466: #                  
  467: sub ValidManager {
  468:     my $certificate = shift; 
  469: 
  470:     return isManager;
  471: }
  472: #
  473: #  CopyFile:  Called as part of the process of installing a 
  474: #             new configuration file.  This function copies an existing
  475: #             file to a backup file.
  476: # Parameters:
  477: #     oldfile  - Name of the file to backup.
  478: #     newfile  - Name of the backup file.
  479: # Return:
  480: #     0   - Failure (errno has failure reason).
  481: #     1   - Success.
  482: #
  483: sub CopyFile {
  484: 
  485:     my ($oldfile, $newfile) = @_;
  486: 
  487:     if (! copy($oldfile,$newfile)) {
  488:         return 0;
  489:     }
  490:     chmod(0660, $newfile);
  491:     return 1;
  492: }
  493: #
  494: #  Host files are passed out with externally visible host IPs.
  495: #  If, for example, we are behind a fire-wall or NAT host, our 
  496: #  internally visible IP may be different than the externally
  497: #  visible IP.  Therefore, we always adjust the contents of the
  498: #  host file so that the entry for ME is the IP that we believe
  499: #  we have.  At present, this is defined as the entry that
  500: #  DNS has for us.  If by some chance we are not able to get a
  501: #  DNS translation for us, then we assume that the host.tab file
  502: #  is correct.  
  503: #    BUGBUGBUG - in the future, we really should see if we can
  504: #       easily query the interface(s) instead.
  505: # Parameter(s):
  506: #     contents    - The contents of the host.tab to check.
  507: # Returns:
  508: #     newcontents - The adjusted contents.
  509: #
  510: #
  511: sub AdjustHostContents {
  512:     my $contents  = shift;
  513:     my $adjusted;
  514:     my $me        = $perlvar{'lonHostID'};
  515: 
  516:     foreach my $line (split(/\n/,$contents)) {
  517: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/) ||
  518:              ($line =~ /^\s*\^/))) {
  519: 	    chomp($line);
  520: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
  521: 	    if ($id eq $me) {
  522: 		my $ip = gethostbyname($name);
  523: 		my $ipnew = inet_ntoa($ip);
  524: 		$ip = $ipnew;
  525: 		#  Reconstruct the host line and append to adjusted:
  526: 		
  527: 		my $newline = "$id:$domain:$role:$name:$ip";
  528: 		if($maxcon ne "") { # Not all hosts have loncnew tuning params
  529: 		    $newline .= ":$maxcon:$idleto:$mincon";
  530: 		}
  531: 		$adjusted .= $newline."\n";
  532: 		
  533: 	    } else {		# Not me, pass unmodified.
  534: 		$adjusted .= $line."\n";
  535: 	    }
  536: 	} else {                  # Blank or comment never re-written.
  537: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
  538: 	}
  539:     }
  540:     return $adjusted;
  541: }
  542: #
  543: #   InstallFile: Called to install an administrative file:
  544: #       - The file is created int a temp directory called <name>.tmp
  545: #       - lcinstall file is called to install the file.
  546: #         since the web app has no direct write access to the table directory
  547: #
  548: #  Parameters:
  549: #       Name of the file
  550: #       File Contents.
  551: #  Return:
  552: #      nonzero - success.
  553: #      0       - failure and $! has an errno.
  554: # Assumptions:
  555: #    File installtion is a relatively infrequent
  556: #
  557: sub InstallFile {
  558: 
  559:     my ($Filename, $Contents) = @_;
  560: #     my $TempFile = $Filename.".tmp";
  561:     my $exedir = $perlvar{'lonDaemons'};
  562:     my $tmpdir = $exedir.'/tmp/';
  563:     my $TempFile = $tmpdir."TempTableFile.tmp";
  564: 
  565:     #  Open the file for write:
  566: 
  567:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
  568:     if(!(defined $fh)) {
  569: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
  570: 	return 0;
  571:     }
  572:     #  write the contents of the file:
  573: 
  574:     print $fh ($Contents); 
  575:     $fh->close;			# In case we ever have a filesystem w. locking
  576: 
  577:     chmod(0664, $TempFile);	# Everyone can write it.
  578: 
  579:     # Use lcinstall file to put the file in the table directory...
  580: 
  581:     &Debug("Opening pipe to $exedir/lcinstallfile $TempFile $Filename");
  582:     my $pf = IO::File->new("| $exedir/lcinstallfile   $TempFile $Filename > $exedir/logs/lcinstallfile.log");
  583:     close $pf;
  584:     my $err = $?;
  585:     &Debug("Status is $err");
  586:     if ($err != 0) {
  587: 	my $msg = $err;
  588: 	if ($err < @installerrors) {
  589: 	    $msg = $installerrors[$err];
  590: 	}
  591: 	&logthis("Install failed for table file $Filename : $msg");
  592: 	return 0;
  593:     }
  594: 
  595:     # Remove the temp file:
  596: 
  597:     unlink($TempFile);
  598: 
  599:     return 1;
  600: }
  601: 
  602: 
  603: #
  604: #   ConfigFileFromSelector: converts a configuration file selector
  605: #                 into a configuration file pathname.
  606: #                 Supports the following file selectors: 
  607: #                 hosts, domain, dns_hosts, dns_domain  
  608: #
  609: #
  610: #  Parameters:
  611: #      selector  - Configuration file selector.
  612: #  Returns:
  613: #      Full path to the file or undef if the selector is invalid.
  614: #
  615: sub ConfigFileFromSelector {
  616:     my $selector   = shift;
  617:     my $tablefile;
  618: 
  619:     my $tabledir = $perlvar{'lonTabDir'}.'/';
  620:     if (($selector eq "hosts") || ($selector eq "domain") || 
  621:         ($selector eq "dns_hosts") || ($selector eq "dns_domain")) {
  622: 	$tablefile =  $tabledir.$selector.'.tab';
  623:     }
  624:     return $tablefile;
  625: }
  626: #
  627: #   PushFile:  Called to do an administrative push of a file.
  628: #              - Ensure the file being pushed is one we support.
  629: #              - Backup the old file to <filename.saved>
  630: #              - Separate the contents of the new file out from the
  631: #                rest of the request.
  632: #              - Write the new file.
  633: #  Parameter:
  634: #     Request - The entire user request.  This consists of a : separated
  635: #               string pushfile:tablename:contents.
  636: #     NOTE:  The contents may have :'s in it as well making things a bit
  637: #            more interesting... but not much.
  638: #  Returns:
  639: #     String to send to client ("ok" or "refused" if bad file).
  640: #
  641: sub PushFile {
  642:     my $request = shift;    
  643:     my ($command, $filename, $contents) = split(":", $request, 3);
  644:     &Debug("PushFile");
  645:     
  646:     #  At this point in time, pushes for only the following tables are
  647:     #  supported:
  648:     #   hosts.tab  ($filename eq host).
  649:     #   domain.tab ($filename eq domain).
  650:     #   dns_hosts.tab ($filename eq dns_host).
  651:     #   dns_domain.tab ($filename eq dns_domain). 
  652:     # Construct the destination filename or reject the request.
  653:     #
  654:     # lonManage is supposed to ensure this, however this session could be
  655:     # part of some elaborate spoof that managed somehow to authenticate.
  656:     #
  657: 
  658: 
  659:     my $tablefile = ConfigFileFromSelector($filename);
  660:     if(! (defined $tablefile)) {
  661: 	return "refused";
  662:     }
  663: 
  664:     #  If the file being pushed is the host file, we adjust the entry for ourself so that the
  665:     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
  666:     #  to conceive of conditions where we don't have a DNS entry locally.  This is possible in a 
  667:     #  network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
  668:     #  that possibilty.
  669: 
  670:     if($filename eq "host") {
  671: 	$contents = AdjustHostContents($contents);
  672:     }
  673: 
  674:     #  Install the new file:
  675: 
  676:     &logthis("Installing new $tablefile contents:\n$contents");
  677:     if(!InstallFile($tablefile, $contents)) {
  678: 	&logthis('<font color="red"> Pushfile: unable to install '
  679: 	 .$tablefile." $! </font>");
  680: 	return "error:$!";
  681:     } else {
  682: 	&logthis('<font color="green"> Installed new '.$tablefile
  683: 		 ." - transaction by: $clientname ($clientip)</font>");
  684:         my $adminmail = $perlvar{'lonAdmEMail'};
  685:         my $admindom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
  686:         if ($admindom ne '') {
  687:             my %domconfig =
  688:                 &Apache::lonnet::get_dom('configuration',['contacts'],$admindom);
  689:             if (ref($domconfig{'contacts'}) eq 'HASH') {
  690:                 if ($domconfig{'contacts'}{'adminemail'} ne '') {
  691:                     $adminmail = $domconfig{'contacts'}{'adminemail'};
  692:                 }
  693:             }
  694:         }
  695:         if ($adminmail =~ /^[^\@]+\@[^\@]+$/) {
  696:             my $msg = new Mail::Send;
  697:             $msg->to($adminmail);
  698:             $msg->subject('LON-CAPA DNS update on '.$perlvar{'lonHostID'});
  699:             $msg->add('Content-type','text/plain; charset=UTF-8');
  700:             if (my $fh = $msg->open()) {
  701:                 print $fh 'Update to '.$tablefile.' from Cluster Manager '.
  702:                           "$clientname ($clientip)\n";
  703:                 $fh->close;
  704:             }
  705:         }
  706:     }
  707: 
  708:     #  Indicate success:
  709:  
  710:     return "ok";
  711: 
  712: }
  713: 
  714: #
  715: #  Called to re-init either lonc or lond.
  716: #
  717: #  Parameters:
  718: #    request   - The full request by the client.  This is of the form
  719: #                reinit:<process>  
  720: #                where <process> is allowed to be either of 
  721: #                lonc or lond
  722: #
  723: #  Returns:
  724: #     The string to be sent back to the client either:
  725: #   ok         - Everything worked just fine.
  726: #   error:why  - There was a failure and why describes the reason.
  727: #
  728: #
  729: sub ReinitProcess {
  730:     my $request = shift;
  731: 
  732: 
  733:     # separate the request (reinit) from the process identifier and
  734:     # validate it producing the name of the .pid file for the process.
  735:     #
  736:     #
  737:     my ($junk, $process) = split(":", $request);
  738:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
  739:     if($process eq 'lonc') {
  740: 	$processpidfile = $processpidfile."lonc.pid";
  741: 	if (!open(PIDFILE, "< $processpidfile")) {
  742: 	    return "error:Open failed for $processpidfile";
  743: 	}
  744: 	my $loncpid = <PIDFILE>;
  745: 	close(PIDFILE);
  746: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
  747: 		."</font>");
  748: 	kill("USR2", $loncpid);
  749:     } elsif ($process eq 'lond') {
  750: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
  751: 	&UpdateHosts;			# Lond is us!!
  752:     } else {
  753: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
  754: 		 ."</font>");
  755: 	return "error:Invalid process identifier $process";
  756:     }
  757:     return 'ok';
  758: }
  759: #   Validate a line in a configuration file edit script:
  760: #   Validation includes:
  761: #     - Ensuring the command is valid.
  762: #     - Ensuring the command has sufficient parameters
  763: #   Parameters:
  764: #     scriptline - A line to validate (\n has been stripped for what it's worth).
  765: #
  766: #   Return:
  767: #      0     - Invalid scriptline.
  768: #      1     - Valid scriptline
  769: #  NOTE:
  770: #     Only the command syntax is checked, not the executability of the
  771: #     command.
  772: #
  773: sub isValidEditCommand {
  774:     my $scriptline = shift;
  775: 
  776:     #   Line elements are pipe separated:
  777: 
  778:     my ($command, $key, $newline)  = split(/\|/, $scriptline);
  779:     &logthis('<font color="green"> isValideditCommand checking: '.
  780: 	     "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
  781:     
  782:     if ($command eq "delete") {
  783: 	#
  784: 	#   key with no newline.
  785: 	#
  786: 	if( ($key eq "") || ($newline ne "")) {
  787: 	    return 0;		# Must have key but no newline.
  788: 	} else {
  789: 	    return 1;		# Valid syntax.
  790: 	}
  791:     } elsif ($command eq "replace") {
  792: 	#
  793: 	#   key and newline:
  794: 	#
  795: 	if (($key eq "") || ($newline eq "")) {
  796: 	    return 0;
  797: 	} else {
  798: 	    return 1;
  799: 	}
  800:     } elsif ($command eq "append") {
  801: 	if (($key ne "") && ($newline eq "")) {
  802: 	    return 1;
  803: 	} else {
  804: 	    return 0;
  805: 	}
  806:     } else {
  807: 	return 0;		# Invalid command.
  808:     }
  809:     return 0;			# Should not get here!!!
  810: }
  811: #
  812: #   ApplyEdit - Applies an edit command to a line in a configuration 
  813: #               file.  It is the caller's responsiblity to validate the
  814: #               edit line.
  815: #   Parameters:
  816: #      $directive - A single edit directive to apply.  
  817: #                   Edit directives are of the form:
  818: #                  append|newline      - Appends a new line to the file.
  819: #                  replace|key|newline - Replaces the line with key value 'key'
  820: #                  delete|key          - Deletes the line with key value 'key'.
  821: #      $editor   - A config file editor object that contains the
  822: #                  file being edited.
  823: #
  824: sub ApplyEdit {
  825: 
  826:     my ($directive, $editor) = @_;
  827: 
  828:     # Break the directive down into its command and its parameters
  829:     # (at most two at this point.  The meaning of the parameters, if in fact
  830:     #  they exist depends on the command).
  831: 
  832:     my ($command, $p1, $p2) = split(/\|/, $directive);
  833: 
  834:     if($command eq "append") {
  835: 	$editor->Append($p1);	          # p1 - key p2 null.
  836:     } elsif ($command eq "replace") {
  837: 	$editor->ReplaceLine($p1, $p2);   # p1 - key p2 = newline.
  838:     } elsif ($command eq "delete") {
  839: 	$editor->DeleteLine($p1);         # p1 - key p2 null.
  840:     } else {			          # Should not get here!!!
  841: 	die "Invalid command given to ApplyEdit $command"
  842:     }
  843: }
  844: #
  845: # AdjustOurHost:
  846: #           Adjusts a host file stored in a configuration file editor object
  847: #           for the true IP address of this host. This is necessary for hosts
  848: #           that live behind a firewall.
  849: #           Those hosts have a publicly distributed IP of the firewall, but
  850: #           internally must use their actual IP.  We assume that a given
  851: #           host only has a single IP interface for now.
  852: # Formal Parameters:
  853: #     editor   - The configuration file editor to adjust.  This
  854: #                editor is assumed to contain a hosts.tab file.
  855: # Strategy:
  856: #    - Figure out our hostname.
  857: #    - Lookup the entry for this host.
  858: #    - Modify the line to contain our IP
  859: #    - Do a replace for this host.
  860: sub AdjustOurHost {
  861:     my $editor        = shift;
  862: 
  863:     # figure out who I am.
  864: 
  865:     my $myHostName    = $perlvar{'lonHostID'}; # LonCAPA hostname.
  866: 
  867:     #  Get my host file entry.
  868: 
  869:     my $ConfigLine    = $editor->Find($myHostName);
  870:     if(! (defined $ConfigLine)) {
  871: 	die "AdjustOurHost - no entry for me in hosts file $myHostName";
  872:     }
  873:     # figure out my IP:
  874:     #   Use the config line to get my hostname.
  875:     #   Use gethostbyname to translate that into an IP address.
  876:     #
  877:     my ($id,$domain,$role,$name,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
  878:     #
  879:     #  Reassemble the config line from the elements in the list.
  880:     #  Note that if the loncnew items were not present before, they will
  881:     #  be now even if they would be empty
  882:     #
  883:     my $newConfigLine = $id;
  884:     foreach my $item ($domain, $role, $name, $maxcon, $idleto, $mincon) {
  885: 	$newConfigLine .= ":".$item;
  886:     }
  887:     #  Replace the line:
  888: 
  889:     $editor->ReplaceLine($id, $newConfigLine);
  890:     
  891: }
  892: #
  893: #   ReplaceConfigFile:
  894: #              Replaces a configuration file with the contents of a
  895: #              configuration file editor object.
  896: #              This is done by:
  897: #              - Copying the target file to <filename>.old
  898: #              - Writing the new file to <filename>.tmp
  899: #              - Moving <filename.tmp>  -> <filename>
  900: #              This laborious process ensures that the system is never without
  901: #              a configuration file that's at least valid (even if the contents
  902: #              may be dated).
  903: #   Parameters:
  904: #        filename   - Name of the file to modify... this is a full path.
  905: #        editor     - Editor containing the file.
  906: #
  907: sub ReplaceConfigFile {
  908:     
  909:     my ($filename, $editor) = @_;
  910: 
  911:     CopyFile ($filename, $filename.".old");
  912: 
  913:     my $contents  = $editor->Get(); # Get the contents of the file.
  914: 
  915:     InstallFile($filename, $contents);
  916: }
  917: #   
  918: #
  919: #   Called to edit a configuration table  file
  920: #   Parameters:
  921: #      request           - The entire command/request sent by lonc or lonManage
  922: #   Return:
  923: #      The reply to send to the client.
  924: #
  925: sub EditFile {
  926:     my $request = shift;
  927: 
  928:     #  Split the command into it's pieces:  edit:filetype:script
  929: 
  930:     my ($cmd, $filetype, $script) = split(/:/, $request,3);	# : in script
  931: 
  932:     #  Check the pre-coditions for success:
  933: 
  934:     if($cmd != "edit") {	# Something is amiss afoot alack.
  935: 	return "error:edit request detected, but request != 'edit'\n";
  936:     }
  937:     if( ($filetype ne "hosts")  &&
  938: 	($filetype ne "domain")) {
  939: 	return "error:edit requested with invalid file specifier: $filetype \n";
  940:     }
  941: 
  942:     #   Split the edit script and check it's validity.
  943: 
  944:     my @scriptlines = split(/\n/, $script);  # one line per element.
  945:     my $linecount   = scalar(@scriptlines);
  946:     for(my $i = 0; $i < $linecount; $i++) {
  947: 	chomp($scriptlines[$i]);
  948: 	if(!isValidEditCommand($scriptlines[$i])) {
  949: 	    return "error:edit with bad script line: '$scriptlines[$i]' \n";
  950: 	}
  951:     }
  952: 
  953:     #   Execute the edit operation.
  954:     #   - Create a config file editor for the appropriate file and 
  955:     #   - execute each command in the script:
  956:     #
  957:     my $configfile = ConfigFileFromSelector($filetype);
  958:     if (!(defined $configfile)) {
  959: 	return "refused\n";
  960:     }
  961:     my $editor = ConfigFileEdit->new($configfile);
  962: 
  963:     for (my $i = 0; $i < $linecount; $i++) {
  964: 	ApplyEdit($scriptlines[$i], $editor);
  965:     }
  966:     # If the file is the host file, ensure that our host is
  967:     # adjusted to have our ip:
  968:     #
  969:     if($filetype eq "host") {
  970: 	AdjustOurHost($editor);
  971:     }
  972:     #  Finally replace the current file with our file.
  973:     #
  974:     ReplaceConfigFile($configfile, $editor);
  975: 
  976:     return "ok\n";
  977: }
  978: 
  979: #   read_profile
  980: #
  981: #   Returns a set of specific entries from a user's profile file.
  982: #   this is a utility function that is used by both get_profile_entry and
  983: #   get_profile_entry_encrypted.
  984: #
  985: # Parameters:
  986: #    udom       - Domain in which the user exists.
  987: #    uname      - User's account name (loncapa account)
  988: #    namespace  - The profile namespace to open.
  989: #    what       - A set of & separated queries.
  990: # Returns:
  991: #    If all ok: - The string that needs to be shipped back to the user.
  992: #    If failure - A string that starts with error: followed by the failure
  993: #                 reason.. note that this probabyl gets shipped back to the
  994: #                 user as well.
  995: #
  996: sub read_profile {
  997:     my ($udom, $uname, $namespace, $what) = @_;
  998:     
  999:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 1000: 				 &GDBM_READER());
 1001:     if ($hashref) {
 1002:         my @queries=split(/\&/,$what);
 1003:         if ($namespace eq 'roles') {
 1004:             @queries = map { &unescape($_); } @queries; 
 1005:         }
 1006:         my $qresult='';
 1007: 	
 1008: 	for (my $i=0;$i<=$#queries;$i++) {
 1009: 	    $qresult.="$hashref->{$queries[$i]}&";    # Presumably failure gives empty string.
 1010: 	}
 1011: 	$qresult=~s/\&$//;              # Remove trailing & from last lookup.
 1012: 	if (&untie_user_hash($hashref)) {
 1013: 	    return $qresult;
 1014: 	} else {
 1015: 	    return "error: ".($!+0)." untie (GDBM) Failed";
 1016: 	}
 1017:     } else {
 1018: 	if ($!+0 == 2) {
 1019: 	    return "error:No such file or GDBM reported bad block error";
 1020: 	} else {
 1021: 	    return "error: ".($!+0)." tie (GDBM) Failed";
 1022: 	}
 1023:     }
 1024: 
 1025: }
 1026: #--------------------- Request Handlers --------------------------------------------
 1027: #
 1028: #   By convention each request handler registers itself prior to the sub 
 1029: #   declaration:
 1030: #
 1031: 
 1032: #++
 1033: #
 1034: #  Handles ping requests.
 1035: #  Parameters:
 1036: #      $cmd    - the actual keyword that invoked us.
 1037: #      $tail   - the tail of the request that invoked us.
 1038: #      $replyfd- File descriptor connected to the client
 1039: #  Implicit Inputs:
 1040: #      $currenthostid - Global variable that carries the name of the host we are
 1041: #                       known as.
 1042: #  Returns:
 1043: #      1       - Ok to continue processing.
 1044: #      0       - Program should exit.
 1045: #  Side effects:
 1046: #      Reply information is sent to the client.
 1047: sub ping_handler {
 1048:     my ($cmd, $tail, $client) = @_;
 1049:     Debug("$cmd $tail $client .. $currenthostid:");
 1050:    
 1051:     Reply( $client,\$currenthostid,"$cmd:$tail");
 1052:    
 1053:     return 1;
 1054: }
 1055: &register_handler("ping", \&ping_handler, 0, 1, 1);       # Ping unencoded, client or manager.
 1056: 
 1057: #++
 1058: #
 1059: # Handles pong requests.  Pong replies with our current host id, and
 1060: #                         the results of a ping sent to us via our lonc.
 1061: #
 1062: # Parameters:
 1063: #      $cmd    - the actual keyword that invoked us.
 1064: #      $tail   - the tail of the request that invoked us.
 1065: #      $replyfd- File descriptor connected to the client
 1066: #  Implicit Inputs:
 1067: #      $currenthostid - Global variable that carries the name of the host we are
 1068: #                       connected to.
 1069: #  Returns:
 1070: #      1       - Ok to continue processing.
 1071: #      0       - Program should exit.
 1072: #  Side effects:
 1073: #      Reply information is sent to the client.
 1074: sub pong_handler {
 1075:     my ($cmd, $tail, $replyfd) = @_;
 1076: 
 1077:     my $reply=&Apache::lonnet::reply("ping",$clientname);
 1078:     &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail"); 
 1079:     return 1;
 1080: }
 1081: &register_handler("pong", \&pong_handler, 0, 1, 1);       # Pong unencoded, client or manager
 1082: 
 1083: #++
 1084: #      Called to establish an encrypted session key with the remote client.
 1085: #      Note that with secure lond, in most cases this function is never
 1086: #      invoked.  Instead, the secure session key is established either
 1087: #      via a local file that's locked down tight and only lives for a short
 1088: #      time, or via an ssl tunnel...and is generated from a bunch-o-random
 1089: #      bits from /dev/urandom, rather than the predictable pattern used by
 1090: #      by this sub.  This sub is only used in the old-style insecure
 1091: #      key negotiation.
 1092: # Parameters:
 1093: #      $cmd    - the actual keyword that invoked us.
 1094: #      $tail   - the tail of the request that invoked us.
 1095: #      $replyfd- File descriptor connected to the client
 1096: #  Implicit Inputs:
 1097: #      $currenthostid - Global variable that carries the name of the host
 1098: #                       known as.
 1099: #      $clientname    - Global variable that carries the name of the host we're connected to.
 1100: #  Returns:
 1101: #      1       - Ok to continue processing.
 1102: #      0       - Program should exit.
 1103: #  Implicit Outputs:
 1104: #      Reply information is sent to the client.
 1105: #      $cipher is set with a reference to a new IDEA encryption object.
 1106: #
 1107: sub establish_key_handler {
 1108:     my ($cmd, $tail, $replyfd) = @_;
 1109: 
 1110:     my $buildkey=time.$$.int(rand 100000);
 1111:     $buildkey=~tr/1-6/A-F/;
 1112:     $buildkey=int(rand 100000).$buildkey.int(rand 100000);
 1113:     my $key=$currenthostid.$clientname;
 1114:     $key=~tr/a-z/A-Z/;
 1115:     $key=~tr/G-P/0-9/;
 1116:     $key=~tr/Q-Z/0-9/;
 1117:     $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
 1118:     $key=substr($key,0,32);
 1119:     my $cipherkey=pack("H32",$key);
 1120:     $cipher=new IDEA $cipherkey;
 1121:     &Reply($replyfd, \$buildkey, "$cmd:$tail"); 
 1122:    
 1123:     return 1;
 1124: 
 1125: }
 1126: &register_handler("ekey", \&establish_key_handler, 0, 1,1);
 1127: 
 1128: #     Handler for the load command.  Returns the current system load average
 1129: #     to the requestor.
 1130: #
 1131: # Parameters:
 1132: #      $cmd    - the actual keyword that invoked us.
 1133: #      $tail   - the tail of the request that invoked us.
 1134: #      $replyfd- File descriptor connected to the client
 1135: #  Implicit Inputs:
 1136: #      $currenthostid - Global variable that carries the name of the host
 1137: #                       known as.
 1138: #      $clientname    - Global variable that carries the name of the host we're connected to.
 1139: #  Returns:
 1140: #      1       - Ok to continue processing.
 1141: #      0       - Program should exit.
 1142: #  Side effects:
 1143: #      Reply information is sent to the client.
 1144: sub load_handler {
 1145:     my ($cmd, $tail, $replyfd) = @_;
 1146: 
 1147: 
 1148: 
 1149:    # Get the load average from /proc/loadavg and calculate it as a percentage of
 1150:    # the allowed load limit as set by the perl global variable lonLoadLim
 1151: 
 1152:     my $loadavg;
 1153:     my $loadfile=IO::File->new('/proc/loadavg');
 1154:    
 1155:     $loadavg=<$loadfile>;
 1156:     $loadavg =~ s/\s.*//g;                      # Extract the first field only.
 1157:    
 1158:     my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
 1159: 
 1160:     &Reply( $replyfd, \$loadpercent, "$cmd:$tail");
 1161:    
 1162:     return 1;
 1163: }
 1164: &register_handler("load", \&load_handler, 0, 1, 0);
 1165: 
 1166: #
 1167: #   Process the userload request.  This sub returns to the client the current
 1168: #  user load average.  It can be invoked either by clients or managers.
 1169: #
 1170: # Parameters:
 1171: #      $cmd    - the actual keyword that invoked us.
 1172: #      $tail   - the tail of the request that invoked us.
 1173: #      $replyfd- File descriptor connected to the client
 1174: #  Implicit Inputs:
 1175: #      $currenthostid - Global variable that carries the name of the host
 1176: #                       known as.
 1177: #      $clientname    - Global variable that carries the name of the host we're connected to.
 1178: #  Returns:
 1179: #      1       - Ok to continue processing.
 1180: #      0       - Program should exit
 1181: # Implicit inputs:
 1182: #     whatever the userload() function requires.
 1183: #  Implicit outputs:
 1184: #     the reply is written to the client.
 1185: #
 1186: sub user_load_handler {
 1187:     my ($cmd, $tail, $replyfd) = @_;
 1188: 
 1189:     my $userloadpercent=&Apache::lonnet::userload();
 1190:     &Reply($replyfd, \$userloadpercent, "$cmd:$tail");
 1191:     
 1192:     return 1;
 1193: }
 1194: &register_handler("userload", \&user_load_handler, 0, 1, 0);
 1195: 
 1196: #   Process a request for the authorization type of a user:
 1197: #   (userauth).
 1198: #
 1199: # Parameters:
 1200: #      $cmd    - the actual keyword that invoked us.
 1201: #      $tail   - the tail of the request that invoked us.
 1202: #      $replyfd- File descriptor connected to the client
 1203: #  Returns:
 1204: #      1       - Ok to continue processing.
 1205: #      0       - Program should exit
 1206: # Implicit outputs:
 1207: #    The user authorization type is written to the client.
 1208: #
 1209: sub user_authorization_type {
 1210:     my ($cmd, $tail, $replyfd) = @_;
 1211:    
 1212:     my $userinput = "$cmd:$tail";
 1213:    
 1214:     #  Pull the domain and username out of the command tail.
 1215:     # and call get_auth_type to determine the authentication type.
 1216:    
 1217:     my ($udom,$uname)=split(/:/,$tail);
 1218:     my $result = &get_auth_type($udom, $uname);
 1219:     if($result eq "nouser") {
 1220: 	&Failure( $replyfd, "unknown_user\n", $userinput);
 1221:     } else {
 1222: 	#
 1223: 	# We only want to pass the second field from get_auth_type
 1224: 	# for ^krb.. otherwise we'll be handing out the encrypted
 1225: 	# password for internals e.g.
 1226: 	#
 1227: 	my ($type,$otherinfo) = split(/:/,$result);
 1228: 	if($type =~ /^krb/) {
 1229: 	    $type = $result;
 1230: 	} else {
 1231:             $type .= ':';
 1232:         }
 1233: 	&Reply( $replyfd, \$type, $userinput);
 1234:     }
 1235:   
 1236:     return 1;
 1237: }
 1238: &register_handler("currentauth", \&user_authorization_type, 1, 1, 0);
 1239: 
 1240: #   Process a request by a manager to push a hosts or domain table 
 1241: #   to us.  We pick apart the command and pass it on to the subs
 1242: #   that already exist to do this.
 1243: #
 1244: # Parameters:
 1245: #      $cmd    - the actual keyword that invoked us.
 1246: #      $tail   - the tail of the request that invoked us.
 1247: #      $client - File descriptor connected to the client
 1248: #  Returns:
 1249: #      1       - Ok to continue processing.
 1250: #      0       - Program should exit
 1251: # Implicit Output:
 1252: #    a reply is written to the client.
 1253: sub push_file_handler {
 1254:     my ($cmd, $tail, $client) = @_;
 1255:     &Debug("In push file handler");
 1256:     my $userinput = "$cmd:$tail";
 1257: 
 1258:     # At this time we only know that the IP of our partner is a valid manager
 1259:     # the code below is a hook to do further authentication (e.g. to resolve
 1260:     # spoofing).
 1261: 
 1262:     my $cert = &GetCertificate($userinput);
 1263:     if(&ValidManager($cert)) {
 1264: 	&Debug("Valid manager: $client");
 1265: 
 1266: 	# Now presumably we have the bona fides of both the peer host and the
 1267: 	# process making the request.
 1268:       
 1269: 	my $reply = &PushFile($userinput);
 1270: 	&Reply($client, \$reply, $userinput);
 1271: 
 1272:     } else {
 1273: 	&logthis("push_file_handler $client is not valid");
 1274: 	&Failure( $client, "refused\n", $userinput);
 1275:     } 
 1276:     return 1;
 1277: }
 1278: &register_handler("pushfile", \&push_file_handler, 1, 0, 1);
 1279: 
 1280: # The du_handler routine should be considered obsolete and is retained
 1281: # for communication with legacy servers.  Please see the du2_handler.
 1282: #
 1283: #   du  - list the disk usage of a directory recursively. 
 1284: #    
 1285: #   note: stolen code from the ls file handler
 1286: #   under construction by Rick Banghart 
 1287: #    .
 1288: # Parameters:
 1289: #    $cmd        - The command that dispatched us (du).
 1290: #    $ududir     - The directory path to list... I'm not sure what this
 1291: #                  is relative as things like ls:. return e.g.
 1292: #                  no_such_dir.
 1293: #    $client     - Socket open on the client.
 1294: # Returns:
 1295: #     1 - indicating that the daemon should not disconnect.
 1296: # Side Effects:
 1297: #   The reply is written to  $client.
 1298: #
 1299: sub du_handler {
 1300:     my ($cmd, $ududir, $client) = @_;
 1301:     ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
 1302:     my $userinput = "$cmd:$ududir";
 1303: 
 1304:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
 1305: 	&Failure($client,"refused\n","$cmd:$ududir");
 1306: 	return 1;
 1307:     }
 1308:     #  Since $ududir could have some nasties in it,
 1309:     #  we will require that ududir is a valid
 1310:     #  directory.  Just in case someone tries to
 1311:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
 1312:     #  etc.
 1313:     #
 1314:     if (-d $ududir) {
 1315: 	my $total_size=0;
 1316: 	my $code=sub { 
 1317: 	    if ($_=~/\.\d+\./) { return;} 
 1318: 	    if ($_=~/\.meta$/) { return;}
 1319: 	    if (-d $_)         { return;}
 1320: 	    $total_size+=(stat($_))[7];
 1321: 	};
 1322: 	chdir($ududir);
 1323: 	find($code,$ududir);
 1324: 	$total_size=int($total_size/1024);
 1325: 	&Reply($client,\$total_size,"$cmd:$ududir");
 1326:     } else {
 1327: 	&Failure($client, "bad_directory:$ududir\n","$cmd:$ududir"); 
 1328:     }
 1329:     return 1;
 1330: }
 1331: &register_handler("du", \&du_handler, 0, 1, 0);
 1332: 
 1333: # Please also see the du_handler, which is obsoleted by du2. 
 1334: # du2_handler differs from du_handler in that required path to directory
 1335: # provided by &propath() is prepended in the handler instead of on the 
 1336: # client side.
 1337: #
 1338: #   du2  - list the disk usage of a directory recursively.
 1339: #
 1340: # Parameters:
 1341: #    $cmd        - The command that dispatched us (du).
 1342: #    $tail       - The tail of the request that invoked us.
 1343: #                  $tail is a : separated list of the following:
 1344: #                   - $ududir - directory path to list (before prepending)
 1345: #                   - $getpropath = 1 if &propath() should prepend
 1346: #                   - $uname - username to use for &propath or user dir
 1347: #                   - $udom - domain to use for &propath or user dir
 1348: #                   All are escaped.
 1349: #    $client     - Socket open on the client.
 1350: # Returns:
 1351: #     1 - indicating that the daemon should not disconnect.
 1352: # Side Effects:
 1353: #   The reply is written to $client.
 1354: #
 1355: 
 1356: sub du2_handler {
 1357:     my ($cmd, $tail, $client) = @_;
 1358:     my ($ududir,$getpropath,$uname,$udom) = map { &unescape($_) } (split(/:/, $tail));
 1359:     my $userinput = "$cmd:$tail";
 1360:     if (($ududir=~/\.\./) || (($ududir!~m|^/home/httpd/|) && (!$getpropath))) {
 1361:         &Failure($client,"refused\n","$cmd:$tail");
 1362:         return 1;
 1363:     }
 1364:     if ($getpropath) {
 1365:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
 1366:             $ududir = &propath($udom,$uname).'/'.$ududir;
 1367:         } else {
 1368:             &Failure($client,"refused\n","$cmd:$tail");
 1369:             return 1;
 1370:         }
 1371:     }
 1372:     #  Since $ududir could have some nasties in it,
 1373:     #  we will require that ududir is a valid
 1374:     #  directory.  Just in case someone tries to
 1375:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
 1376:     #  etc.
 1377:     #
 1378:     if (-d $ududir) {
 1379:         my $total_size=0;
 1380:         my $code=sub {
 1381:             if ($_=~/\.\d+\./) { return;}
 1382:             if ($_=~/\.meta$/) { return;}
 1383:             if (-d $_)         { return;}
 1384:             $total_size+=(stat($_))[7];
 1385:         };
 1386:         chdir($ududir);
 1387:         find($code,$ududir);
 1388:         $total_size=int($total_size/1024);
 1389:         &Reply($client,\$total_size,"$cmd:$ududir");
 1390:     } else {
 1391:         &Failure($client, "bad_directory:$ududir\n","$cmd:$tail");
 1392:     }
 1393:     return 1;
 1394: }
 1395: &register_handler("du2", \&du2_handler, 0, 1, 0);
 1396: 
 1397: #
 1398: # The ls_handler routine should be considered obsolete and is retained
 1399: # for communication with legacy servers.  Please see the ls3_handler.
 1400: #
 1401: #   ls  - list the contents of a directory.  For each file in the
 1402: #    selected directory the filename followed by the full output of
 1403: #    the stat function is returned.  The returned info for each
 1404: #    file are separated by ':'.  The stat fields are separated by &'s.
 1405: # Parameters:
 1406: #    $cmd        - The command that dispatched us (ls).
 1407: #    $ulsdir     - The directory path to list... I'm not sure what this
 1408: #                  is relative as things like ls:. return e.g.
 1409: #                  no_such_dir.
 1410: #    $client     - Socket open on the client.
 1411: # Returns:
 1412: #     1 - indicating that the daemon should not disconnect.
 1413: # Side Effects:
 1414: #   The reply is written to  $client.
 1415: #
 1416: sub ls_handler {
 1417:     # obsoleted by ls2_handler
 1418:     my ($cmd, $ulsdir, $client) = @_;
 1419: 
 1420:     my $userinput = "$cmd:$ulsdir";
 1421: 
 1422:     my $obs;
 1423:     my $rights;
 1424:     my $ulsout='';
 1425:     my $ulsfn;
 1426:     if (-e $ulsdir) {
 1427: 	if(-d $ulsdir) {
 1428: 	    if (opendir(LSDIR,$ulsdir)) {
 1429: 		while ($ulsfn=readdir(LSDIR)) {
 1430: 		    undef($obs);
 1431: 		    undef($rights); 
 1432: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1433: 		    #We do some obsolete checking here
 1434: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
 1435: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
 1436: 			my @obsolete=<FILE>;
 1437: 			foreach my $obsolete (@obsolete) {
 1438: 			    if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
 1439: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
 1440: 			}
 1441: 		    }
 1442: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
 1443: 		    if($obs eq '1') { $ulsout.="&1"; }
 1444: 		    else { $ulsout.="&0"; }
 1445: 		    if($rights eq '1') { $ulsout.="&1:"; }
 1446: 		    else { $ulsout.="&0:"; }
 1447: 		}
 1448: 		closedir(LSDIR);
 1449: 	    }
 1450: 	} else {
 1451: 	    my @ulsstats=stat($ulsdir);
 1452: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1453: 	}
 1454:     } else {
 1455: 	$ulsout='no_such_dir';
 1456:     }
 1457:     if ($ulsout eq '') { $ulsout='empty'; }
 1458:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
 1459:     
 1460:     return 1;
 1461: 
 1462: }
 1463: &register_handler("ls", \&ls_handler, 0, 1, 0);
 1464: 
 1465: # The ls2_handler routine should be considered obsolete and is retained
 1466: # for communication with legacy servers.  Please see the ls3_handler.
 1467: # Please also see the ls_handler, which was itself obsoleted by ls2.
 1468: # ls2_handler differs from ls_handler in that it escapes its return 
 1469: # values before concatenating them together with ':'s.
 1470: #
 1471: #   ls2  - list the contents of a directory.  For each file in the
 1472: #    selected directory the filename followed by the full output of
 1473: #    the stat function is returned.  The returned info for each
 1474: #    file are separated by ':'.  The stat fields are separated by &'s.
 1475: # Parameters:
 1476: #    $cmd        - The command that dispatched us (ls).
 1477: #    $ulsdir     - The directory path to list... I'm not sure what this
 1478: #                  is relative as things like ls:. return e.g.
 1479: #                  no_such_dir.
 1480: #    $client     - Socket open on the client.
 1481: # Returns:
 1482: #     1 - indicating that the daemon should not disconnect.
 1483: # Side Effects:
 1484: #   The reply is written to  $client.
 1485: #
 1486: sub ls2_handler {
 1487:     my ($cmd, $ulsdir, $client) = @_;
 1488: 
 1489:     my $userinput = "$cmd:$ulsdir";
 1490: 
 1491:     my $obs;
 1492:     my $rights;
 1493:     my $ulsout='';
 1494:     my $ulsfn;
 1495:     if (-e $ulsdir) {
 1496:         if(-d $ulsdir) {
 1497:             if (opendir(LSDIR,$ulsdir)) {
 1498:                 while ($ulsfn=readdir(LSDIR)) {
 1499:                     undef($obs);
 1500: 		    undef($rights); 
 1501:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1502:                     #We do some obsolete checking here
 1503:                     if(-e $ulsdir.'/'.$ulsfn.".meta") { 
 1504:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
 1505:                         my @obsolete=<FILE>;
 1506:                         foreach my $obsolete (@obsolete) {
 1507:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
 1508:                             if($obsolete =~ m|(<copyright>)(default)|) {
 1509:                                 $rights = 1;
 1510:                             }
 1511:                         }
 1512:                     }
 1513:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
 1514:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1515:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1516:                     $ulsout.= &escape($tmp).':';
 1517:                 }
 1518:                 closedir(LSDIR);
 1519:             }
 1520:         } else {
 1521:             my @ulsstats=stat($ulsdir);
 1522:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1523:         }
 1524:     } else {
 1525:         $ulsout='no_such_dir';
 1526:    }
 1527:    if ($ulsout eq '') { $ulsout='empty'; }
 1528:    &Reply($client, \$ulsout, $userinput); # This supports debug logging.
 1529:    return 1;
 1530: }
 1531: &register_handler("ls2", \&ls2_handler, 0, 1, 0);
 1532: #
 1533: #   ls3  - list the contents of a directory.  For each file in the
 1534: #    selected directory the filename followed by the full output of
 1535: #    the stat function is returned.  The returned info for each
 1536: #    file are separated by ':'.  The stat fields are separated by &'s.
 1537: # Parameters:
 1538: #    $cmd        - The command that dispatched us (ls).
 1539: #    $tail       - The tail of the request that invoked us.
 1540: #                  $tail is a : separated list of the following:
 1541: #                   - $ulsdir - directory path to list (before prepending)
 1542: #                   - $getpropath = 1 if &propath() should prepend
 1543: #                   - $getuserdir = 1 if path to user dir in lonUsers should
 1544: #                                     prepend
 1545: #                   - $alternate_root - path to prepend
 1546: #                   - $uname - username to use for &propath or user dir
 1547: #                   - $udom - domain to use for &propath or user dir
 1548: #            All of these except $getpropath and &getuserdir are escaped.    
 1549: #                  no_such_dir.
 1550: #    $client     - Socket open on the client.
 1551: # Returns:
 1552: #     1 - indicating that the daemon should not disconnect.
 1553: # Side Effects:
 1554: #   The reply is written to $client.
 1555: #
 1556: 
 1557: sub ls3_handler {
 1558:     my ($cmd, $tail, $client) = @_;
 1559:     my $userinput = "$cmd:$tail";
 1560:     my ($ulsdir,$getpropath,$getuserdir,$alternate_root,$uname,$udom) =
 1561:         split(/:/,$tail);
 1562:     if (defined($ulsdir)) {
 1563:         $ulsdir = &unescape($ulsdir);
 1564:     }
 1565:     if (defined($alternate_root)) {
 1566:         $alternate_root = &unescape($alternate_root);
 1567:     }
 1568:     if (defined($uname)) {
 1569:         $uname = &unescape($uname);
 1570:     }
 1571:     if (defined($udom)) {
 1572:         $udom = &unescape($udom);
 1573:     }
 1574: 
 1575:     my $dir_root = $perlvar{'lonDocRoot'};
 1576:     if ($getpropath) {
 1577:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
 1578:             $dir_root = &propath($udom,$uname);
 1579:             $dir_root =~ s/\/$//;
 1580:         } else {
 1581:             &Failure($client,"refused\n","$cmd:$tail");
 1582:             return 1;
 1583:         }
 1584:     } elsif ($getuserdir) {
 1585:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
 1586:             my $subdir=$uname.'__';
 1587:             $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 1588:             $dir_root = $Apache::lonnet::perlvar{'lonUsersDir'}
 1589:                        ."/$udom/$subdir/$uname";
 1590:         } else {
 1591:             &Failure($client,"refused\n","$cmd:$tail");
 1592:             return 1;
 1593:         }
 1594:     } elsif ($alternate_root ne '') {
 1595:         $dir_root = $alternate_root;
 1596:     }
 1597:     if (($dir_root ne '') && ($dir_root ne '/')) {
 1598:         if ($ulsdir =~ /^\//) {
 1599:             $ulsdir = $dir_root.$ulsdir;
 1600:         } else {
 1601:             $ulsdir = $dir_root.'/'.$ulsdir;
 1602:         }
 1603:     }
 1604:     my $obs;
 1605:     my $rights;
 1606:     my $ulsout='';
 1607:     my $ulsfn;
 1608:     if (-e $ulsdir) {
 1609:         if(-d $ulsdir) {
 1610:             if (opendir(LSDIR,$ulsdir)) {
 1611:                 while ($ulsfn=readdir(LSDIR)) {
 1612:                     undef($obs);
 1613:                     undef($rights);
 1614:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1615:                     #We do some obsolete checking here
 1616:                     if(-e $ulsdir.'/'.$ulsfn.".meta") {
 1617:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
 1618:                         my @obsolete=<FILE>;
 1619:                         foreach my $obsolete (@obsolete) {
 1620:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
 1621:                             if($obsolete =~ m|(<copyright>)(default)|) {
 1622:                                 $rights = 1;
 1623:                             }
 1624:                         }
 1625:                     }
 1626:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
 1627:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1628:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1629:                     $ulsout.= &escape($tmp).':';
 1630:                 }
 1631:                 closedir(LSDIR);
 1632:             }
 1633:         } else {
 1634:             my @ulsstats=stat($ulsdir);
 1635:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1636:         }
 1637:     } else {
 1638:         $ulsout='no_such_dir';
 1639:     }
 1640:     if ($ulsout eq '') { $ulsout='empty'; }
 1641:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
 1642:     return 1;
 1643: }
 1644: &register_handler("ls3", \&ls3_handler, 0, 1, 0);
 1645: 
 1646: sub read_lonnet_global {
 1647:     my ($cmd,$tail,$client) = @_;
 1648:     my $userinput = "$cmd:$tail";
 1649:     my $requested = &Apache::lonnet::thaw_unescape($tail);
 1650:     my $result;
 1651:     my %packagevars = (
 1652:                         spareid => \%Apache::lonnet::spareid,
 1653:                         perlvar => \%Apache::lonnet::perlvar,
 1654:                       );
 1655:     my %limit_to = (
 1656:                     perlvar => {
 1657:                                  lonOtherAuthen => 1,
 1658:                                  lonBalancer    => 1,
 1659:                                  lonVersion     => 1,
 1660:                                  lonSysEMail    => 1,
 1661:                                  lonHostID      => 1,
 1662:                                  lonRole        => 1,
 1663:                                  lonDefDomain   => 1,
 1664:                                  lonLoadLim     => 1,
 1665:                                  lonUserLoadLim => 1,
 1666:                                }
 1667:                   );
 1668:     if (ref($requested) eq 'HASH') {
 1669:         foreach my $what (keys(%{$requested})) {
 1670:             my $response;
 1671:             my $items = {};
 1672:             if (exists($packagevars{$what})) {
 1673:                 if (ref($limit_to{$what}) eq 'HASH') {
 1674:                     foreach my $varname (keys(%{$packagevars{$what}})) {
 1675:                         if ($limit_to{$what}{$varname}) {
 1676:                             $items->{$varname} = $packagevars{$what}{$varname};
 1677:                         }
 1678:                     }
 1679:                 } else {
 1680:                     $items = $packagevars{$what};
 1681:                 }
 1682:                 if ($what eq 'perlvar') {
 1683:                     if (!exists($packagevars{$what}{'lonBalancer'})) {
 1684:                         if ($dist =~ /^(centos|rhes|fedora|scientific)/) {
 1685:                             my $othervarref=LONCAPA::Configuration::read_conf('httpd.conf');
 1686:                             if (ref($othervarref) eq 'HASH') {
 1687:                                 $items->{'lonBalancer'} = $othervarref->{'lonBalancer'};
 1688:                             }
 1689:                         }
 1690:                     }
 1691:                 }
 1692:                 $response = &Apache::lonnet::freeze_escape($items);
 1693:             }
 1694:             $result .= &escape($what).'='.$response.'&';
 1695:         }
 1696:     }
 1697:     $result =~ s/\&$//;
 1698:     &Reply($client,\$result,$userinput);
 1699:     return 1;
 1700: }
 1701: &register_handler("readlonnetglobal", \&read_lonnet_global, 0, 1, 0);
 1702: 
 1703: sub server_devalidatecache_handler {
 1704:     my ($cmd,$tail,$client) = @_;
 1705:     my $userinput = "$cmd:$tail";
 1706:     my ($name,$id) = map { &unescape($_); } split(/:/,$tail);
 1707:     &Apache::lonnet::devalidate_cache_new($name,$id);
 1708:     my $result = 'ok';
 1709:     &Reply($client,\$result,$userinput);
 1710:     return 1;
 1711: }
 1712: &register_handler("devalidatecache", \&server_devalidatecache_handler, 0, 1, 0);
 1713: 
 1714: sub server_timezone_handler {
 1715:     my ($cmd,$tail,$client) = @_;
 1716:     my $userinput = "$cmd:$tail";
 1717:     my $timezone;
 1718:     my $clockfile = '/etc/sysconfig/clock'; # Fedora/CentOS/SuSE
 1719:     my $tzfile = '/etc/timezone'; # Debian/Ubuntu
 1720:     if (-e $clockfile) {
 1721:         if (open(my $fh,"<$clockfile")) {
 1722:             while (<$fh>) {
 1723:                 next if (/^[\#\s]/);
 1724:                 if (/^(?:TIME)?ZONE\s*=\s*['"]?\s*([\w\/]+)/) {
 1725:                     $timezone = $1;
 1726:                     last;
 1727:                 }
 1728:             }
 1729:             close($fh);
 1730:         }
 1731:     } elsif (-e $tzfile) {
 1732:         if (open(my $fh,"<$tzfile")) {
 1733:             $timezone = <$fh>;
 1734:             close($fh);
 1735:             chomp($timezone);
 1736:             if ($timezone =~ m{^Etc/(\w+)$}) {
 1737:                 $timezone = $1;
 1738:             }
 1739:         }
 1740:     }
 1741:     &Reply($client,\$timezone,$userinput); # This supports debug logging.
 1742:     return 1;
 1743: }
 1744: &register_handler("servertimezone", \&server_timezone_handler, 0, 1, 0);
 1745: 
 1746: sub server_loncaparev_handler {
 1747:     my ($cmd,$tail,$client) = @_;
 1748:     my $userinput = "$cmd:$tail";
 1749:     &Reply($client,\$perlvar{'lonVersion'},$userinput);
 1750:     return 1;
 1751: }
 1752: &register_handler("serverloncaparev", \&server_loncaparev_handler, 0, 1, 0);
 1753: 
 1754: sub server_homeID_handler {
 1755:     my ($cmd,$tail,$client) = @_;
 1756:     my $userinput = "$cmd:$tail";
 1757:     &Reply($client,\$perlvar{'lonHostID'},$userinput);
 1758:     return 1;
 1759: }
 1760: &register_handler("serverhomeID", \&server_homeID_handler, 0, 1, 0);
 1761: 
 1762: sub server_distarch_handler {
 1763:     my ($cmd,$tail,$client) = @_;
 1764:     my $userinput = "$cmd:$tail";
 1765:     my $reply = &distro_and_arch();
 1766:     &Reply($client,\$reply,$userinput);
 1767:     return 1;
 1768: }
 1769: &register_handler("serverdistarch", \&server_distarch_handler, 0, 1, 0);
 1770: 
 1771: #   Process a reinit request.  Reinit requests that either
 1772: #   lonc or lond be reinitialized so that an updated 
 1773: #   host.tab or domain.tab can be processed.
 1774: #
 1775: # Parameters:
 1776: #      $cmd    - the actual keyword that invoked us.
 1777: #      $tail   - the tail of the request that invoked us.
 1778: #      $client - File descriptor connected to the client
 1779: #  Returns:
 1780: #      1       - Ok to continue processing.
 1781: #      0       - Program should exit
 1782: #  Implicit output:
 1783: #     a reply is sent to the client.
 1784: #
 1785: sub reinit_process_handler {
 1786:     my ($cmd, $tail, $client) = @_;
 1787:    
 1788:     my $userinput = "$cmd:$tail";
 1789:    
 1790:     my $cert = &GetCertificate($userinput);
 1791:     if(&ValidManager($cert)) {
 1792: 	chomp($userinput);
 1793: 	my $reply = &ReinitProcess($userinput);
 1794: 	&Reply( $client,  \$reply, $userinput);
 1795:     } else {
 1796: 	&Failure( $client, "refused\n", $userinput);
 1797:     }
 1798:     return 1;
 1799: }
 1800: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
 1801: 
 1802: #  Process the editing script for a table edit operation.
 1803: #  the editing operation must be encrypted and requested by
 1804: #  a manager host.
 1805: #
 1806: # Parameters:
 1807: #      $cmd    - the actual keyword that invoked us.
 1808: #      $tail   - the tail of the request that invoked us.
 1809: #      $client - File descriptor connected to the client
 1810: #  Returns:
 1811: #      1       - Ok to continue processing.
 1812: #      0       - Program should exit
 1813: #  Implicit output:
 1814: #     a reply is sent to the client.
 1815: #
 1816: sub edit_table_handler {
 1817:     my ($command, $tail, $client) = @_;
 1818:    
 1819:     my $userinput = "$command:$tail";
 1820: 
 1821:     my $cert = &GetCertificate($userinput);
 1822:     if(&ValidManager($cert)) {
 1823: 	my($filetype, $script) = split(/:/, $tail);
 1824: 	if (($filetype eq "hosts") || 
 1825: 	    ($filetype eq "domain")) {
 1826: 	    if($script ne "") {
 1827: 		&Reply($client,              # BUGBUG - EditFile
 1828: 		      &EditFile($userinput), #   could fail.
 1829: 		      $userinput);
 1830: 	    } else {
 1831: 		&Failure($client,"refused\n",$userinput);
 1832: 	    }
 1833: 	} else {
 1834: 	    &Failure($client,"refused\n",$userinput);
 1835: 	}
 1836:     } else {
 1837: 	&Failure($client,"refused\n",$userinput);
 1838:     }
 1839:     return 1;
 1840: }
 1841: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
 1842: 
 1843: #
 1844: #   Authenticate a user against the LonCAPA authentication
 1845: #   database.  Note that there are several authentication
 1846: #   possibilities:
 1847: #   - unix     - The user can be authenticated against the unix
 1848: #                password file.
 1849: #   - internal - The user can be authenticated against a purely 
 1850: #                internal per user password file.
 1851: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
 1852: #                ticket granting authority.
 1853: #   - user     - The person tailoring LonCAPA can supply a user authentication
 1854: #                mechanism that is per system.
 1855: #
 1856: # Parameters:
 1857: #    $cmd      - The command that got us here.
 1858: #    $tail     - Tail of the command (remaining parameters).
 1859: #    $client   - File descriptor connected to client.
 1860: # Returns
 1861: #     0        - Requested to exit, caller should shut down.
 1862: #     1        - Continue processing.
 1863: # Implicit inputs:
 1864: #    The authentication systems describe above have their own forms of implicit
 1865: #    input into the authentication process that are described above.
 1866: #
 1867: sub authenticate_handler {
 1868:     my ($cmd, $tail, $client) = @_;
 1869: 
 1870:     
 1871:     #  Regenerate the full input line 
 1872:     
 1873:     my $userinput  = $cmd.":".$tail;
 1874:     
 1875:     #  udom    - User's domain.
 1876:     #  uname   - Username.
 1877:     #  upass   - User's password.
 1878:     #  checkdefauth - Pass to validate_user() to try authentication
 1879:     #                 with default auth type(s) if no user account.
 1880:     #  clientcancheckhost - Passed by clients with functionality in lonauth.pm
 1881:     #                       to check if session can be hosted.
 1882:     
 1883:     my ($udom, $uname, $upass, $checkdefauth, $clientcancheckhost)=split(/:/,$tail);
 1884:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass,  checkdefauth = $checkdefauth");
 1885:     chomp($upass);
 1886:     $upass=&unescape($upass);
 1887: 
 1888:     my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
 1889:     if($pwdcorrect) {
 1890:         my $canhost = 1;
 1891:         unless ($clientcancheckhost) {
 1892:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1893:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1894:             my @intdoms;
 1895:             my $internet_names = &Apache::lonnet::get_internet_names($clientname);
 1896:             if (ref($internet_names) eq 'ARRAY') {
 1897:                 @intdoms = @{$internet_names};
 1898:             }
 1899:             unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1900:                 my ($remote,$hosted);
 1901:                 my $remotesession = &get_usersession_config($udom,'remotesession');
 1902:                 if (ref($remotesession) eq 'HASH') {
 1903:                     $remote = $remotesession->{'remote'}
 1904:                 }
 1905:                 my $hostedsession = &get_usersession_config($clienthomedom,'hostedsession');
 1906:                 if (ref($hostedsession) eq 'HASH') {
 1907:                     $hosted = $hostedsession->{'hosted'};
 1908:                 }
 1909:                 my $loncaparev = $clientversion;
 1910:                 if ($loncaparev eq '') {
 1911:                     $loncaparev = $Apache::lonnet::loncaparevs{$clientname};
 1912:                 }
 1913:                 $canhost = &Apache::lonnet::can_host_session($udom,$clientname,
 1914:                                                              $loncaparev,
 1915:                                                              $remote,$hosted);
 1916:             }
 1917:         }
 1918:         if ($canhost) {               
 1919:             &Reply( $client, "authorized\n", $userinput);
 1920:         } else {
 1921:             &Reply( $client, "not_allowed_to_host\n", $userinput);
 1922:         }
 1923: 	#
 1924: 	#  Bad credentials: Failed to authorize
 1925: 	#
 1926:     } else {
 1927: 	&Failure( $client, "non_authorized\n", $userinput);
 1928:     }
 1929: 
 1930:     return 1;
 1931: }
 1932: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
 1933: 
 1934: #
 1935: #   Change a user's password.  Note that this function is complicated by
 1936: #   the fact that a user may be authenticated in more than one way:
 1937: #   At present, we are not able to change the password for all types of
 1938: #   authentication methods.  Only for:
 1939: #      unix    - unix password or shadow passoword style authentication.
 1940: #      local   - Locally written authentication mechanism.
 1941: #   For now, kerb4 and kerb5 password changes are not supported and result
 1942: #   in an error.
 1943: # FUTURE WORK:
 1944: #    Support kerberos passwd changes?
 1945: # Parameters:
 1946: #    $cmd      - The command that got us here.
 1947: #    $tail     - Tail of the command (remaining parameters).
 1948: #    $client   - File descriptor connected to client.
 1949: # Returns
 1950: #     0        - Requested to exit, caller should shut down.
 1951: #     1        - Continue processing.
 1952: # Implicit inputs:
 1953: #    The authentication systems describe above have their own forms of implicit
 1954: #    input into the authentication process that are described above.
 1955: sub change_password_handler {
 1956:     my ($cmd, $tail, $client) = @_;
 1957: 
 1958:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
 1959: 
 1960:     #
 1961:     #  udom  - user's domain.
 1962:     #  uname - Username.
 1963:     #  upass - Current password.
 1964:     #  npass - New password.
 1965:     #  context - Context in which this was called 
 1966:     #            (preferences or reset_by_email).
 1967:     #  lonhost - HostID of server where request originated 
 1968:    
 1969:     my ($udom,$uname,$upass,$npass,$context,$lonhost)=split(/:/,$tail);
 1970: 
 1971:     $upass=&unescape($upass);
 1972:     $npass=&unescape($npass);
 1973:     &Debug("Trying to change password for $uname");
 1974: 
 1975:     # First require that the user can be authenticated with their
 1976:     # old password unless context was 'reset_by_email':
 1977:     
 1978:     my ($validated,$failure);
 1979:     if ($context eq 'reset_by_email') {
 1980:         if ($lonhost eq '') {
 1981:             $failure = 'invalid_client';
 1982:         } else {
 1983:             $validated = 1;
 1984:         }
 1985:     } else {
 1986:         $validated = &validate_user($udom, $uname, $upass);
 1987:     }
 1988:     if($validated) {
 1989: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
 1990: 	
 1991: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
 1992: 	if ($howpwd eq 'internal') {
 1993: 	    &Debug("internal auth");
 1994: 	    my $salt=time;
 1995: 	    $salt=substr($salt,6,2);
 1996: 	    my $ncpass=crypt($npass,$salt);
 1997: 	    if(&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
 1998: 		my $msg="Result of password change for $uname: pwchange_success";
 1999:                 if ($lonhost) {
 2000:                     $msg .= " - request originated from: $lonhost";
 2001:                 }
 2002:                 &logthis($msg);
 2003: 		&Reply($client, "ok\n", $userinput);
 2004: 	    } else {
 2005: 		&logthis("Unable to open $uname passwd "               
 2006: 			 ."to change password");
 2007: 		&Failure( $client, "non_authorized\n",$userinput);
 2008: 	    }
 2009: 	} elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
 2010: 	    my $result = &change_unix_password($uname, $npass);
 2011: 	    &logthis("Result of password change for $uname: ".
 2012: 		     $result);
 2013: 	    &Reply($client, \$result, $userinput);
 2014: 	} else {
 2015: 	    # this just means that the current password mode is not
 2016: 	    # one we know how to change (e.g the kerberos auth modes or
 2017: 	    # locally written auth handler).
 2018: 	    #
 2019: 	    &Failure( $client, "auth_mode_error\n", $userinput);
 2020: 	}  
 2021: 	
 2022:     } else {
 2023: 	if ($failure eq '') {
 2024: 	    $failure = 'non_authorized';
 2025: 	}
 2026: 	&Failure( $client, "$failure\n", $userinput);
 2027:     }
 2028: 
 2029:     return 1;
 2030: }
 2031: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
 2032: 
 2033: #
 2034: #   Create a new user.  User in this case means a lon-capa user.
 2035: #   The user must either already exist in some authentication realm
 2036: #   like kerberos or the /etc/passwd.  If not, a user completely local to
 2037: #   this loncapa system is created.
 2038: #
 2039: # Parameters:
 2040: #    $cmd      - The command that got us here.
 2041: #    $tail     - Tail of the command (remaining parameters).
 2042: #    $client   - File descriptor connected to client.
 2043: # Returns
 2044: #     0        - Requested to exit, caller should shut down.
 2045: #     1        - Continue processing.
 2046: # Implicit inputs:
 2047: #    The authentication systems describe above have their own forms of implicit
 2048: #    input into the authentication process that are described above.
 2049: sub add_user_handler {
 2050: 
 2051:     my ($cmd, $tail, $client) = @_;
 2052: 
 2053: 
 2054:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
 2055:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
 2056: 
 2057:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
 2058: 
 2059: 
 2060:     if($udom eq $currentdomainid) { # Reject new users for other domains...
 2061: 	
 2062: 	my $oldumask=umask(0077);
 2063: 	chomp($npass);
 2064: 	$npass=&unescape($npass);
 2065: 	my $passfilename  = &password_path($udom, $uname);
 2066: 	&Debug("Password file created will be:".$passfilename);
 2067: 	if (-e $passfilename) {
 2068: 	    &Failure( $client, "already_exists\n", $userinput);
 2069: 	} else {
 2070: 	    my $fperror='';
 2071: 	    if (!&mkpath($passfilename)) {
 2072: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
 2073: 		    ."makeuser";
 2074: 	    }
 2075: 	    unless ($fperror) {
 2076: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass, $passfilename);
 2077: 		&Reply($client,\$result, $userinput);     #BUGBUG - could be fail
 2078: 	    } else {
 2079: 		&Failure($client, \$fperror, $userinput);
 2080: 	    }
 2081: 	}
 2082: 	umask($oldumask);
 2083:     }  else {
 2084: 	&Failure($client, "not_right_domain\n",
 2085: 		$userinput);	# Even if we are multihomed.
 2086:     
 2087:     }
 2088:     return 1;
 2089: 
 2090: }
 2091: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
 2092: 
 2093: #
 2094: #   Change the authentication method of a user.  Note that this may
 2095: #   also implicitly change the user's password if, for example, the user is
 2096: #   joining an existing authentication realm.  Known authentication realms at
 2097: #   this time are:
 2098: #    internal   - Purely internal password file (only loncapa knows this user)
 2099: #    local      - Institutionally written authentication module.
 2100: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
 2101: #    kerb4      - kerberos version 4
 2102: #    kerb5      - kerberos version 5
 2103: #
 2104: # Parameters:
 2105: #    $cmd      - The command that got us here.
 2106: #    $tail     - Tail of the command (remaining parameters).
 2107: #    $client   - File descriptor connected to client.
 2108: # Returns
 2109: #     0        - Requested to exit, caller should shut down.
 2110: #     1        - Continue processing.
 2111: # Implicit inputs:
 2112: #    The authentication systems describe above have their own forms of implicit
 2113: #    input into the authentication process that are described above.
 2114: # NOTE:
 2115: #   This is also used to change the authentication credential values (e.g. passwd).
 2116: #   
 2117: #
 2118: sub change_authentication_handler {
 2119: 
 2120:     my ($cmd, $tail, $client) = @_;
 2121:    
 2122:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
 2123: 
 2124:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
 2125:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
 2126:     if ($udom ne $currentdomainid) {
 2127: 	&Failure( $client, "not_right_domain\n", $client);
 2128:     } else {
 2129: 	
 2130: 	chomp($npass);
 2131: 	
 2132: 	$npass=&unescape($npass);
 2133: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
 2134: 	my $passfilename = &password_path($udom, $uname);
 2135: 	if ($passfilename) {	# Not allowed to create a new user!!
 2136: 	    # If just changing the unix passwd. need to arrange to run
 2137: 	    # passwd since otherwise make_passwd_file will run
 2138: 	    # lcuseradd which fails if an account already exists
 2139: 	    # (to prevent an unscrupulous LONCAPA admin from stealing
 2140: 	    # an existing account by overwriting it as a LonCAPA account).
 2141: 
 2142: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
 2143: 		my $result = &change_unix_password($uname, $npass);
 2144: 		&logthis("Result of password change for $uname: ".$result);
 2145: 		if ($result eq "ok") {
 2146: 		    &Reply($client, \$result);
 2147: 		} else {
 2148: 		    &Failure($client, \$result);
 2149: 		}
 2150: 	    } else {
 2151: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,$passfilename);
 2152: 		#
 2153: 		#  If the current auth mode is internal, and the old auth mode was
 2154: 		#  unix, or krb*,  and the user is an author for this domain,
 2155: 		#  re-run manage_permissions for that role in order to be able
 2156: 		#  to take ownership of the construction space back to www:www
 2157: 		#
 2158: 		
 2159: 		
 2160: 		if( (($oldauth =~ /^unix/) && ($umode eq "internal")) ||
 2161: 		    (($oldauth =~ /^internal/) && ($umode eq "unix")) ) { 
 2162: 		    if(&is_author($udom, $uname)) {
 2163: 			&Debug(" Need to manage author permissions...");
 2164: 			&manage_permissions("/$udom/_au", $udom, $uname, "$umode:");
 2165: 		    }
 2166: 		}
 2167: 		&Reply($client, \$result, $userinput);
 2168: 	    }
 2169: 	       
 2170: 
 2171: 	} else {	       
 2172: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
 2173: 	}
 2174:     }
 2175:     return 1;
 2176: }
 2177: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
 2178: 
 2179: #
 2180: #   Determines if this is the home server for a user.  The home server
 2181: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
 2182: #   to do is determine if this file exists.
 2183: #
 2184: # Parameters:
 2185: #    $cmd      - The command that got us here.
 2186: #    $tail     - Tail of the command (remaining parameters).
 2187: #    $client   - File descriptor connected to client.
 2188: # Returns
 2189: #     0        - Requested to exit, caller should shut down.
 2190: #     1        - Continue processing.
 2191: # Implicit inputs:
 2192: #    The authentication systems describe above have their own forms of implicit
 2193: #    input into the authentication process that are described above.
 2194: #
 2195: sub is_home_handler {
 2196:     my ($cmd, $tail, $client) = @_;
 2197:    
 2198:     my $userinput  = "$cmd:$tail";
 2199:    
 2200:     my ($udom,$uname)=split(/:/,$tail);
 2201:     chomp($uname);
 2202:     my $passfile = &password_filename($udom, $uname);
 2203:     if($passfile) {
 2204: 	&Reply( $client, "found\n", $userinput);
 2205:     } else {
 2206: 	&Failure($client, "not_found\n", $userinput);
 2207:     }
 2208:     return 1;
 2209: }
 2210: &register_handler("home", \&is_home_handler, 0,1,0);
 2211: 
 2212: #
 2213: #   Process an update request for a resource.
 2214: #   A resource has been modified that we hold a subscription to.
 2215: #   If the resource is not local, then we must update, or at least invalidate our
 2216: #   cached copy of the resource. 
 2217: # Parameters:
 2218: #    $cmd      - The command that got us here.
 2219: #    $tail     - Tail of the command (remaining parameters).
 2220: #    $client   - File descriptor connected to client.
 2221: # Returns
 2222: #     0        - Requested to exit, caller should shut down.
 2223: #     1        - Continue processing.
 2224: # Implicit inputs:
 2225: #    The authentication systems describe above have their own forms of implicit
 2226: #    input into the authentication process that are described above.
 2227: #
 2228: sub update_resource_handler {
 2229: 
 2230:     my ($cmd, $tail, $client) = @_;
 2231:    
 2232:     my $userinput = "$cmd:$tail";
 2233:    
 2234:     my $fname= $tail;		# This allows interactive testing
 2235: 
 2236: 
 2237:     my $ownership=ishome($fname);
 2238:     if ($ownership eq 'not_owner') {
 2239: 	if (-e $fname) {
 2240:             # Delete preview file, if exists
 2241:             unlink("$fname.tmp");
 2242:             # Get usage stats
 2243: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
 2244: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
 2245: 	    my $now=time;
 2246: 	    my $since=$now-$atime;
 2247:             # If the file has not been used within lonExpire seconds,
 2248:             # unsubscribe from it and delete local copy
 2249: 	    if ($since>$perlvar{'lonExpire'}) {
 2250: 		my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
 2251: 		&devalidate_meta_cache($fname);
 2252: 		unlink("$fname");
 2253: 		unlink("$fname.meta");
 2254: 	    } else {
 2255:             # Yes, this is in active use. Get a fresh copy. Since it might be in
 2256:             # very active use and huge (like a movie), copy it to "in.transfer" filename first.
 2257: 		my $transname="$fname.in.transfer";
 2258: 		my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
 2259: 		my $response;
 2260: # FIXME: cannot replicate files that take more than two minutes to transfer?
 2261: #		alarm(120);
 2262: # FIXME: this should use the LWP mechanism, not internal alarms.
 2263:                 alarm(1200);
 2264: 		{
 2265: 		    my $ua=new LWP::UserAgent;
 2266: 		    my $request=new HTTP::Request('GET',"$remoteurl");
 2267: 		    $response=$ua->request($request,$transname);
 2268: 		}
 2269: 		alarm(0);
 2270: 		if ($response->is_error()) {
 2271: # FIXME: we should probably clean up here instead of just whine
 2272: 		    unlink($transname);
 2273: 		    my $message=$response->status_line;
 2274: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
 2275: 		} else {
 2276: 		    if ($remoteurl!~/\.meta$/) {
 2277: # FIXME: isn't there an internal LWP mechanism for this?
 2278: 			alarm(120);
 2279: 			{
 2280: 			    my $ua=new LWP::UserAgent;
 2281: 			    my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2282: 			    my $mresponse=$ua->request($mrequest,$fname.'.meta');
 2283: 			    if ($mresponse->is_error()) {
 2284: 				unlink($fname.'.meta');
 2285: 			    }
 2286: 			}
 2287: 			alarm(0);
 2288: 		    }
 2289:                     # we successfully transfered, copy file over to real name
 2290: 		    rename($transname,$fname);
 2291: 		    &devalidate_meta_cache($fname);
 2292: 		}
 2293: 	    }
 2294: 	    &Reply( $client, "ok\n", $userinput);
 2295: 	} else {
 2296: 	    &Failure($client, "not_found\n", $userinput);
 2297: 	}
 2298:     } else {
 2299: 	&Failure($client, "rejected\n", $userinput);
 2300:     }
 2301:     return 1;
 2302: }
 2303: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
 2304: 
 2305: sub devalidate_meta_cache {
 2306:     my ($url) = @_;
 2307:     use Cache::Memcached;
 2308:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
 2309:     $url = &Apache::lonnet::declutter($url);
 2310:     $url =~ s-\.meta$--;
 2311:     my $id = &escape('meta:'.$url);
 2312:     $memcache->delete($id);
 2313: }
 2314: 
 2315: #
 2316: #   Fetch a user file from a remote server to the user's home directory
 2317: #   userfiles subdir.
 2318: # Parameters:
 2319: #    $cmd      - The command that got us here.
 2320: #    $tail     - Tail of the command (remaining parameters).
 2321: #    $client   - File descriptor connected to client.
 2322: # Returns
 2323: #     0        - Requested to exit, caller should shut down.
 2324: #     1        - Continue processing.
 2325: #
 2326: sub fetch_user_file_handler {
 2327: 
 2328:     my ($cmd, $tail, $client) = @_;
 2329: 
 2330:     my $userinput = "$cmd:$tail";
 2331:     my $fname           = $tail;
 2332:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
 2333:     my $udir=&propath($udom,$uname).'/userfiles';
 2334:     unless (-e $udir) {
 2335: 	mkdir($udir,0770); 
 2336:     }
 2337:     Debug("fetch user file for $fname");
 2338:     if (-e $udir) {
 2339: 	$ufile=~s/^[\.\~]+//;
 2340: 
 2341: 	# IF necessary, create the path right down to the file.
 2342: 	# Note that any regular files in the way of this path are
 2343: 	# wiped out to deal with some earlier folly of mine.
 2344: 
 2345: 	if (!&mkpath($udir.'/'.$ufile)) {
 2346: 	    &Failure($client, "unable_to_create\n", $userinput);	    
 2347: 	}
 2348: 
 2349: 	my $destname=$udir.'/'.$ufile;
 2350: 	my $transname=$udir.'/'.$ufile.'.in.transit';
 2351:         my $clientprotocol=$Apache::lonnet::protocol{$clientname};
 2352:         $clientprotocol = 'http' if ($clientprotocol ne 'https');
 2353: 	my $clienthost = &Apache::lonnet::hostname($clientname);
 2354: 	my $remoteurl=$clientprotocol.'://'.$clienthost.'/userfiles/'.$fname;
 2355: 	my $response;
 2356: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
 2357: 	alarm(120);
 2358: 	{
 2359: 	    my $ua=new LWP::UserAgent;
 2360: 	    my $request=new HTTP::Request('GET',"$remoteurl");
 2361: 	    $response=$ua->request($request,$transname);
 2362: 	}
 2363: 	alarm(0);
 2364: 	if ($response->is_error()) {
 2365: 	    unlink($transname);
 2366: 	    my $message=$response->status_line;
 2367: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
 2368: 	    &Failure($client, "failed\n", $userinput);
 2369: 	} else {
 2370: 	    Debug("Renaming $transname to $destname");
 2371: 	    if (!rename($transname,$destname)) {
 2372: 		&logthis("Unable to move $transname to $destname");
 2373: 		unlink($transname);
 2374: 		&Failure($client, "failed\n", $userinput);
 2375: 	    } else {
 2376: 		&Reply($client, "ok\n", $userinput);
 2377: 	    }
 2378: 	}   
 2379:     } else {
 2380: 	&Failure($client, "not_home\n", $userinput);
 2381:     }
 2382:     return 1;
 2383: }
 2384: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
 2385: 
 2386: #
 2387: #   Remove a file from a user's home directory userfiles subdirectory.
 2388: # Parameters:
 2389: #    cmd   - the Lond request keyword that got us here.
 2390: #    tail  - the part of the command past the keyword.
 2391: #    client- File descriptor connected with the client.
 2392: #
 2393: # Returns:
 2394: #    1    - Continue processing.
 2395: sub remove_user_file_handler {
 2396:     my ($cmd, $tail, $client) = @_;
 2397: 
 2398:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
 2399: 
 2400:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
 2401:     if ($ufile =~m|/\.\./|) {
 2402: 	# any files paths with /../ in them refuse 
 2403: 	# to deal with
 2404: 	&Failure($client, "refused\n", "$cmd:$tail");
 2405:     } else {
 2406: 	my $udir = &propath($udom,$uname);
 2407: 	if (-e $udir) {
 2408: 	    my $file=$udir.'/userfiles/'.$ufile;
 2409: 	    if (-e $file) {
 2410: 		#
 2411: 		#   If the file is a regular file unlink is fine...
 2412: 		#   However it's possible the client wants a dir.
 2413: 		#   removed, in which case rmdir is more approprate:
 2414: 		#
 2415: 	        if (-f $file){
 2416: 		    unlink($file);
 2417: 		} elsif(-d $file) {
 2418: 		    rmdir($file);
 2419: 		}
 2420: 		if (-e $file) {
 2421: 		    #  File is still there after we deleted it ?!?
 2422: 
 2423: 		    &Failure($client, "failed\n", "$cmd:$tail");
 2424: 		} else {
 2425: 		    &Reply($client, "ok\n", "$cmd:$tail");
 2426: 		}
 2427: 	    } else {
 2428: 		&Failure($client, "not_found\n", "$cmd:$tail");
 2429: 	    }
 2430: 	} else {
 2431: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 2432: 	}
 2433:     }
 2434:     return 1;
 2435: }
 2436: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
 2437: 
 2438: #
 2439: #   make a directory in a user's home directory userfiles subdirectory.
 2440: # Parameters:
 2441: #    cmd   - the Lond request keyword that got us here.
 2442: #    tail  - the part of the command past the keyword.
 2443: #    client- File descriptor connected with the client.
 2444: #
 2445: # Returns:
 2446: #    1    - Continue processing.
 2447: sub mkdir_user_file_handler {
 2448:     my ($cmd, $tail, $client) = @_;
 2449: 
 2450:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
 2451:     $dir=&unescape($dir);
 2452:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
 2453:     if ($ufile =~m|/\.\./|) {
 2454: 	# any files paths with /../ in them refuse 
 2455: 	# to deal with
 2456: 	&Failure($client, "refused\n", "$cmd:$tail");
 2457:     } else {
 2458: 	my $udir = &propath($udom,$uname);
 2459: 	if (-e $udir) {
 2460: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
 2461: 	    if (!&mkpath($newdir)) {
 2462: 		&Failure($client, "failed\n", "$cmd:$tail");
 2463: 	    }
 2464: 	    &Reply($client, "ok\n", "$cmd:$tail");
 2465: 	} else {
 2466: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 2467: 	}
 2468:     }
 2469:     return 1;
 2470: }
 2471: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
 2472: 
 2473: #
 2474: #   rename a file in a user's home directory userfiles subdirectory.
 2475: # Parameters:
 2476: #    cmd   - the Lond request keyword that got us here.
 2477: #    tail  - the part of the command past the keyword.
 2478: #    client- File descriptor connected with the client.
 2479: #
 2480: # Returns:
 2481: #    1    - Continue processing.
 2482: sub rename_user_file_handler {
 2483:     my ($cmd, $tail, $client) = @_;
 2484: 
 2485:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
 2486:     $old=&unescape($old);
 2487:     $new=&unescape($new);
 2488:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
 2489: 	# any files paths with /../ in them refuse to deal with
 2490: 	&Failure($client, "refused\n", "$cmd:$tail");
 2491:     } else {
 2492: 	my $udir = &propath($udom,$uname);
 2493: 	if (-e $udir) {
 2494: 	    my $oldfile=$udir.'/userfiles/'.$old;
 2495: 	    my $newfile=$udir.'/userfiles/'.$new;
 2496: 	    if (-e $newfile) {
 2497: 		&Failure($client, "exists\n", "$cmd:$tail");
 2498: 	    } elsif (! -e $oldfile) {
 2499: 		&Failure($client, "not_found\n", "$cmd:$tail");
 2500: 	    } else {
 2501: 		if (!rename($oldfile,$newfile)) {
 2502: 		    &Failure($client, "failed\n", "$cmd:$tail");
 2503: 		} else {
 2504: 		    &Reply($client, "ok\n", "$cmd:$tail");
 2505: 		}
 2506: 	    }
 2507: 	} else {
 2508: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 2509: 	}
 2510:     }
 2511:     return 1;
 2512: }
 2513: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
 2514: 
 2515: #
 2516: #  Checks if the specified user has an active session on the server
 2517: #  return ok if so, not_found if not
 2518: #
 2519: # Parameters:
 2520: #   cmd      - The request keyword that dispatched to tus.
 2521: #   tail     - The tail of the request (colon separated parameters).
 2522: #   client   - Filehandle open on the client.
 2523: # Return:
 2524: #    1.
 2525: sub user_has_session_handler {
 2526:     my ($cmd, $tail, $client) = @_;
 2527: 
 2528:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
 2529:     
 2530:     opendir(DIR,$perlvar{'lonIDsDir'});
 2531:     my $filename;
 2532:     while ($filename=readdir(DIR)) {
 2533: 	last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
 2534:     }
 2535:     if ($filename) {
 2536: 	&Reply($client, "ok\n", "$cmd:$tail");
 2537:     } else {
 2538: 	&Failure($client, "not_found\n", "$cmd:$tail");
 2539:     }
 2540:     return 1;
 2541: 
 2542: }
 2543: &register_handler("userhassession", \&user_has_session_handler, 0,1,0);
 2544: 
 2545: #
 2546: #  Authenticate access to a user file by checking that the token the user's 
 2547: #  passed also exists in their session file
 2548: #
 2549: # Parameters:
 2550: #   cmd      - The request keyword that dispatched to tus.
 2551: #   tail     - The tail of the request (colon separated parameters).
 2552: #   client   - Filehandle open on the client.
 2553: # Return:
 2554: #    1.
 2555: sub token_auth_user_file_handler {
 2556:     my ($cmd, $tail, $client) = @_;
 2557: 
 2558:     my ($fname, $session) = split(/:/, $tail);
 2559:     
 2560:     chomp($session);
 2561:     my $reply="non_auth";
 2562:     my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
 2563:     if (open(ENVIN,"$file")) {
 2564: 	flock(ENVIN,LOCK_SH);
 2565: 	tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
 2566: 	if (exists($disk_env{"userfile.$fname"})) {
 2567: 	    $reply="ok";
 2568: 	} else {
 2569: 	    foreach my $envname (keys(%disk_env)) {
 2570: 		if ($envname=~ m|^userfile\.\Q$fname\E|) {
 2571: 		    $reply="ok";
 2572: 		    last;
 2573: 		}
 2574: 	    }
 2575: 	}
 2576: 	untie(%disk_env);
 2577: 	close(ENVIN);
 2578: 	&Reply($client, \$reply, "$cmd:$tail");
 2579:     } else {
 2580: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
 2581:     }
 2582:     return 1;
 2583: 
 2584: }
 2585: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
 2586: 
 2587: #
 2588: #   Unsubscribe from a resource.
 2589: #
 2590: # Parameters:
 2591: #    $cmd      - The command that got us here.
 2592: #    $tail     - Tail of the command (remaining parameters).
 2593: #    $client   - File descriptor connected to client.
 2594: # Returns
 2595: #     0        - Requested to exit, caller should shut down.
 2596: #     1        - Continue processing.
 2597: #
 2598: sub unsubscribe_handler {
 2599:     my ($cmd, $tail, $client) = @_;
 2600: 
 2601:     my $userinput= "$cmd:$tail";
 2602:     
 2603:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
 2604: 
 2605:     &Debug("Unsubscribing $fname");
 2606:     if (-e $fname) {
 2607: 	&Debug("Exists");
 2608: 	&Reply($client, &unsub($fname,$clientip), $userinput);
 2609:     } else {
 2610: 	&Failure($client, "not_found\n", $userinput);
 2611:     }
 2612:     return 1;
 2613: }
 2614: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
 2615: 
 2616: #   Subscribe to a resource
 2617: #
 2618: # Parameters:
 2619: #    $cmd      - The command that got us here.
 2620: #    $tail     - Tail of the command (remaining parameters).
 2621: #    $client   - File descriptor connected to client.
 2622: # Returns
 2623: #     0        - Requested to exit, caller should shut down.
 2624: #     1        - Continue processing.
 2625: #
 2626: sub subscribe_handler {
 2627:     my ($cmd, $tail, $client)= @_;
 2628: 
 2629:     my $userinput  = "$cmd:$tail";
 2630: 
 2631:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
 2632: 
 2633:     return 1;
 2634: }
 2635: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
 2636: 
 2637: #
 2638: #   Determine the latest version of a resource (it looks for the highest
 2639: #   past version and then returns that +1)
 2640: #
 2641: # Parameters:
 2642: #    $cmd      - The command that got us here.
 2643: #    $tail     - Tail of the command (remaining parameters).
 2644: #                 (Should consist of an absolute path to a file)
 2645: #    $client   - File descriptor connected to client.
 2646: # Returns
 2647: #     0        - Requested to exit, caller should shut down.
 2648: #     1        - Continue processing.
 2649: #
 2650: sub current_version_handler {
 2651:     my ($cmd, $tail, $client) = @_;
 2652: 
 2653:     my $userinput= "$cmd:$tail";
 2654:    
 2655:     my $fname   = $tail;
 2656:     &Reply( $client, &currentversion($fname)."\n", $userinput);
 2657:     return 1;
 2658: 
 2659: }
 2660: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
 2661: 
 2662: #  Make an entry in a user's activity log.
 2663: #
 2664: # Parameters:
 2665: #    $cmd      - The command that got us here.
 2666: #    $tail     - Tail of the command (remaining parameters).
 2667: #    $client   - File descriptor connected to client.
 2668: # Returns
 2669: #     0        - Requested to exit, caller should shut down.
 2670: #     1        - Continue processing.
 2671: #
 2672: sub activity_log_handler {
 2673:     my ($cmd, $tail, $client) = @_;
 2674: 
 2675: 
 2676:     my $userinput= "$cmd:$tail";
 2677: 
 2678:     my ($udom,$uname,$what)=split(/:/,$tail);
 2679:     chomp($what);
 2680:     my $proname=&propath($udom,$uname);
 2681:     my $now=time;
 2682:     my $hfh;
 2683:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
 2684: 	print $hfh "$now:$clientname:$what\n";
 2685: 	&Reply( $client, "ok\n", $userinput); 
 2686:     } else {
 2687: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
 2688: 		 ."while attempting log\n", 
 2689: 		 $userinput);
 2690:     }
 2691: 
 2692:     return 1;
 2693: }
 2694: &register_handler("log", \&activity_log_handler, 0, 1, 0);
 2695: 
 2696: #
 2697: #   Put a namespace entry in a user profile hash.
 2698: #   My druthers would be for this to be an encrypted interaction too.
 2699: #   anything that might be an inadvertent covert channel about either
 2700: #   user authentication or user personal information....
 2701: #
 2702: # Parameters:
 2703: #    $cmd      - The command that got us here.
 2704: #    $tail     - Tail of the command (remaining parameters).
 2705: #    $client   - File descriptor connected to client.
 2706: # Returns
 2707: #     0        - Requested to exit, caller should shut down.
 2708: #     1        - Continue processing.
 2709: #
 2710: sub put_user_profile_entry {
 2711:     my ($cmd, $tail, $client)  = @_;
 2712: 
 2713:     my $userinput = "$cmd:$tail";
 2714:     
 2715:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
 2716:     if ($namespace ne 'roles') {
 2717: 	chomp($what);
 2718: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2719: 				  &GDBM_WRCREAT(),"P",$what);
 2720: 	if($hashref) {
 2721: 	    my @pairs=split(/\&/,$what);
 2722: 	    foreach my $pair (@pairs) {
 2723: 		my ($key,$value)=split(/=/,$pair);
 2724: 		$hashref->{$key}=$value;
 2725: 	    }
 2726: 	    if (&untie_user_hash($hashref)) {
 2727: 		&Reply( $client, "ok\n", $userinput);
 2728: 	    } else {
 2729: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 2730: 			"while attempting put\n", 
 2731: 			$userinput);
 2732: 	    }
 2733: 	} else {
 2734: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 2735: 		     "while attempting put\n", $userinput);
 2736: 	}
 2737:     } else {
 2738:         &Failure( $client, "refused\n", $userinput);
 2739:     }
 2740:     
 2741:     return 1;
 2742: }
 2743: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
 2744: 
 2745: #   Put a piece of new data in hash, returns error if entry already exists
 2746: # Parameters:
 2747: #    $cmd      - The command that got us here.
 2748: #    $tail     - Tail of the command (remaining parameters).
 2749: #    $client   - File descriptor connected to client.
 2750: # Returns
 2751: #     0        - Requested to exit, caller should shut down.
 2752: #     1        - Continue processing.
 2753: #
 2754: sub newput_user_profile_entry {
 2755:     my ($cmd, $tail, $client)  = @_;
 2756: 
 2757:     my $userinput = "$cmd:$tail";
 2758: 
 2759:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
 2760:     if ($namespace eq 'roles') {
 2761:         &Failure( $client, "refused\n", $userinput);
 2762: 	return 1;
 2763:     }
 2764: 
 2765:     chomp($what);
 2766: 
 2767:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2768: 				 &GDBM_WRCREAT(),"N",$what);
 2769:     if(!$hashref) {
 2770: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 2771: 		  "while attempting put\n", $userinput);
 2772: 	return 1;
 2773:     }
 2774: 
 2775:     my @pairs=split(/\&/,$what);
 2776:     foreach my $pair (@pairs) {
 2777: 	my ($key,$value)=split(/=/,$pair);
 2778: 	if (exists($hashref->{$key})) {
 2779: 	    &Failure($client, "key_exists: ".$key."\n",$userinput);
 2780: 	    return 1;
 2781: 	}
 2782:     }
 2783: 
 2784:     foreach my $pair (@pairs) {
 2785: 	my ($key,$value)=split(/=/,$pair);
 2786: 	$hashref->{$key}=$value;
 2787:     }
 2788: 
 2789:     if (&untie_user_hash($hashref)) {
 2790: 	&Reply( $client, "ok\n", $userinput);
 2791:     } else {
 2792: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 2793: 		 "while attempting put\n", 
 2794: 		 $userinput);
 2795:     }
 2796:     return 1;
 2797: }
 2798: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
 2799: 
 2800: # 
 2801: #   Increment a profile entry in the user history file.
 2802: #   The history contains keyword value pairs.  In this case,
 2803: #   The value itself is a pair of numbers.  The first, the current value
 2804: #   the second an increment that this function applies to the current
 2805: #   value.
 2806: #
 2807: # Parameters:
 2808: #    $cmd      - The command that got us here.
 2809: #    $tail     - Tail of the command (remaining parameters).
 2810: #    $client   - File descriptor connected to client.
 2811: # Returns
 2812: #     0        - Requested to exit, caller should shut down.
 2813: #     1        - Continue processing.
 2814: #
 2815: sub increment_user_value_handler {
 2816:     my ($cmd, $tail, $client) = @_;
 2817:     
 2818:     my $userinput   = "$cmd:$tail";
 2819:     
 2820:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
 2821:     if ($namespace ne 'roles') {
 2822:         chomp($what);
 2823: 	my $hashref = &tie_user_hash($udom, $uname,
 2824: 				     $namespace, &GDBM_WRCREAT(),
 2825: 				     "P",$what);
 2826: 	if ($hashref) {
 2827: 	    my @pairs=split(/\&/,$what);
 2828: 	    foreach my $pair (@pairs) {
 2829: 		my ($key,$value)=split(/=/,$pair);
 2830:                 $value = &unescape($value);
 2831: 		# We could check that we have a number...
 2832: 		if (! defined($value) || $value eq '') {
 2833: 		    $value = 1;
 2834: 		}
 2835: 		$hashref->{$key}+=$value;
 2836:                 if ($namespace eq 'nohist_resourcetracker') {
 2837:                     if ($hashref->{$key} < 0) {
 2838:                         $hashref->{$key} = 0;
 2839:                     }
 2840:                 }
 2841: 	    }
 2842: 	    if (&untie_user_hash($hashref)) {
 2843: 		&Reply( $client, "ok\n", $userinput);
 2844: 	    } else {
 2845: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 2846: 			 "while attempting inc\n", $userinput);
 2847: 	    }
 2848: 	} else {
 2849: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 2850: 		     "while attempting inc\n", $userinput);
 2851: 	}
 2852:     } else {
 2853: 	&Failure($client, "refused\n", $userinput);
 2854:     }
 2855:     
 2856:     return 1;
 2857: }
 2858: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
 2859: 
 2860: #
 2861: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
 2862: #   Each 'role' a user has implies a set of permissions.  Adding a new role
 2863: #   for a person grants the permissions packaged with that role
 2864: #   to that user when the role is selected.
 2865: #
 2866: # Parameters:
 2867: #    $cmd       - The command string (rolesput).
 2868: #    $tail      - The remainder of the request line.  For rolesput this
 2869: #                 consists of a colon separated list that contains:
 2870: #                 The domain and user that is granting the role (logged).
 2871: #                 The domain and user that is getting the role.
 2872: #                 The roles being granted as a set of & separated pairs.
 2873: #                 each pair a key value pair.
 2874: #    $client    - File descriptor connected to the client.
 2875: # Returns:
 2876: #     0         - If the daemon should exit
 2877: #     1         - To continue processing.
 2878: #
 2879: #
 2880: sub roles_put_handler {
 2881:     my ($cmd, $tail, $client) = @_;
 2882: 
 2883:     my $userinput  = "$cmd:$tail";
 2884: 
 2885:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
 2886:     
 2887: 
 2888:     my $namespace='roles';
 2889:     chomp($what);
 2890:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2891: 				 &GDBM_WRCREAT(), "P",
 2892: 				 "$exedom:$exeuser:$what");
 2893:     #
 2894:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
 2895:     #  handle is open for the minimal amount of time.  Since the flush
 2896:     #  is done on close this improves the chances the log will be an un-
 2897:     #  corrupted ordered thing.
 2898:     if ($hashref) {
 2899: 	my $pass_entry = &get_auth_type($udom, $uname);
 2900: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
 2901: 	$auth_type = $auth_type.":";
 2902: 	my @pairs=split(/\&/,$what);
 2903: 	foreach my $pair (@pairs) {
 2904: 	    my ($key,$value)=split(/=/,$pair);
 2905: 	    &manage_permissions($key, $udom, $uname,
 2906: 			       $auth_type);
 2907: 	    $hashref->{$key}=$value;
 2908: 	}
 2909: 	if (&untie_user_hash($hashref)) {
 2910: 	    &Reply($client, "ok\n", $userinput);
 2911: 	} else {
 2912: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 2913: 		     "while attempting rolesput\n", $userinput);
 2914: 	}
 2915:     } else {
 2916: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 2917: 		 "while attempting rolesput\n", $userinput);
 2918:     }
 2919:     return 1;
 2920: }
 2921: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
 2922: 
 2923: #
 2924: #   Deletes (removes) a role for a user.   This is equivalent to removing
 2925: #  a permissions package associated with the role from the user's profile.
 2926: #
 2927: # Parameters:
 2928: #     $cmd                 - The command (rolesdel)
 2929: #     $tail                - The remainder of the request line. This consists
 2930: #                             of:
 2931: #                             The domain and user requesting the change (logged)
 2932: #                             The domain and user being changed.
 2933: #                             The roles being revoked.  These are shipped to us
 2934: #                             as a bunch of & separated role name keywords.
 2935: #     $client              - The file handle open on the client.
 2936: # Returns:
 2937: #     1                    - Continue processing
 2938: #     0                    - Exit.
 2939: #
 2940: sub roles_delete_handler {
 2941:     my ($cmd, $tail, $client)  = @_;
 2942: 
 2943:     my $userinput    = "$cmd:$tail";
 2944:    
 2945:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
 2946:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
 2947: 	   "what = ".$what);
 2948:     my $namespace='roles';
 2949:     chomp($what);
 2950:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2951: 				 &GDBM_WRCREAT(), "D",
 2952: 				 "$exedom:$exeuser:$what");
 2953:     
 2954:     if ($hashref) {
 2955: 	my @rolekeys=split(/\&/,$what);
 2956: 	
 2957: 	foreach my $key (@rolekeys) {
 2958: 	    delete $hashref->{$key};
 2959: 	}
 2960: 	if (&untie_user_hash($hashref)) {
 2961: 	    &Reply($client, "ok\n", $userinput);
 2962: 	} else {
 2963: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 2964: 		     "while attempting rolesdel\n", $userinput);
 2965: 	}
 2966:     } else {
 2967:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 2968: 		 "while attempting rolesdel\n", $userinput);
 2969:     }
 2970:     
 2971:     return 1;
 2972: }
 2973: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
 2974: 
 2975: # Unencrypted get from a user's profile database.  See 
 2976: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
 2977: # This function retrieves a keyed item from a specific named database in the
 2978: # user's directory.
 2979: #
 2980: # Parameters:
 2981: #   $cmd             - Command request keyword (get).
 2982: #   $tail            - Tail of the command.  This is a colon separated list
 2983: #                      consisting of the domain and username that uniquely
 2984: #                      identifies the profile,
 2985: #                      The 'namespace' which selects the gdbm file to 
 2986: #                      do the lookup in, 
 2987: #                      & separated list of keys to lookup.  Note that
 2988: #                      the values are returned as an & separated list too.
 2989: #   $client          - File descriptor open on the client.
 2990: # Returns:
 2991: #   1       - Continue processing.
 2992: #   0       - Exit.
 2993: #
 2994: sub get_profile_entry {
 2995:     my ($cmd, $tail, $client) = @_;
 2996: 
 2997:     my $userinput= "$cmd:$tail";
 2998:    
 2999:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 3000:     chomp($what);
 3001: 
 3002: 
 3003:     my $replystring = read_profile($udom, $uname, $namespace, $what);
 3004:     my ($first) = split(/:/,$replystring);
 3005:     if($first ne "error") {
 3006: 	&Reply($client, \$replystring, $userinput);
 3007:     } else {
 3008: 	&Failure($client, $replystring." while attempting get\n", $userinput);
 3009:     }
 3010:     return 1;
 3011: 
 3012: 
 3013: }
 3014: &register_handler("get", \&get_profile_entry, 0,1,0);
 3015: 
 3016: #
 3017: #  Process the encrypted get request.  Note that the request is sent
 3018: #  in clear, but the reply is encrypted.  This is a small covert channel:
 3019: #  information about the sensitive keys is given to the snooper.  Just not
 3020: #  information about the values of the sensitive key.  Hmm if I wanted to
 3021: #  know these I'd snoop for the egets. Get the profile item names from them
 3022: #  and then issue a get for them since there's no enforcement of the
 3023: #  requirement of an encrypted get for particular profile items.  If I
 3024: #  were re-doing this, I'd force the request to be encrypted as well as the
 3025: #  reply.  I'd also just enforce encrypted transactions for all gets since
 3026: #  that would prevent any covert channel snooping.
 3027: #
 3028: #  Parameters:
 3029: #     $cmd               - Command keyword of request (eget).
 3030: #     $tail              - Tail of the command.  See GetProfileEntry
#                          for more information about this.
 3031: #     $client            - File open on the client.
 3032: #  Returns:
 3033: #     1      - Continue processing
 3034: #     0      - server should exit.
 3035: sub get_profile_entry_encrypted {
 3036:     my ($cmd, $tail, $client) = @_;
 3037: 
 3038:     my $userinput = "$cmd:$tail";
 3039:    
 3040:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 3041:     chomp($what);
 3042:     my $qresult = read_profile($udom, $uname, $namespace, $what);
 3043:     my ($first) = split(/:/, $qresult);
 3044:     if($first ne "error") {
 3045: 	
 3046: 	if ($cipher) {
 3047: 	    my $cmdlength=length($qresult);
 3048: 	    $qresult.="         ";
 3049: 	    my $encqresult='';
 3050: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 3051: 		$encqresult.= unpack("H16", 
 3052: 				     $cipher->encrypt(substr($qresult,
 3053: 							     $encidx,
 3054: 							     8)));
 3055: 	    }
 3056: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
 3057: 	} else {
 3058: 		&Failure( $client, "error:no_key\n", $userinput);
 3059: 	    }
 3060:     } else {
 3061: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
 3062: 
 3063:     }
 3064:     
 3065:     return 1;
 3066: }
 3067: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
 3068: 
 3069: #
 3070: #   Deletes a key in a user profile database.
 3071: #   
 3072: #   Parameters:
 3073: #       $cmd                  - Command keyword (del).
 3074: #       $tail                 - Command tail.  IN this case a colon
 3075: #                               separated list containing:
 3076: #                               The domain and user that identifies uniquely
 3077: #                               the identity of the user.
 3078: #                               The profile namespace (name of the profile
 3079: #                               database file).
 3080: #                               & separated list of keywords to delete.
 3081: #       $client              - File open on client socket.
 3082: # Returns:
 3083: #     1   - Continue processing
 3084: #     0   - Exit server.
 3085: #
 3086: #
 3087: sub delete_profile_entry {
 3088:     my ($cmd, $tail, $client) = @_;
 3089: 
 3090:     my $userinput = "cmd:$tail";
 3091: 
 3092:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 3093:     chomp($what);
 3094:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3095: 				 &GDBM_WRCREAT(),
 3096: 				 "D",$what);
 3097:     if ($hashref) {
 3098:         my @keys=split(/\&/,$what);
 3099: 	foreach my $key (@keys) {
 3100: 	    delete($hashref->{$key});
 3101: 	}
 3102: 	if (&untie_user_hash($hashref)) {
 3103: 	    &Reply($client, "ok\n", $userinput);
 3104: 	} else {
 3105: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3106: 		    "while attempting del\n", $userinput);
 3107: 	}
 3108:     } else {
 3109: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3110: 		 "while attempting del\n", $userinput);
 3111:     }
 3112:     return 1;
 3113: }
 3114: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
 3115: 
 3116: #
 3117: #  List the set of keys that are defined in a profile database file.
 3118: #  A successful reply from this will contain an & separated list of
 3119: #  the keys. 
 3120: # Parameters:
 3121: #     $cmd              - Command request (keys).
 3122: #     $tail             - Remainder of the request, a colon separated
 3123: #                         list containing domain/user that identifies the
 3124: #                         user being queried, and the database namespace
 3125: #                         (database filename essentially).
 3126: #     $client           - File open on the client.
 3127: #  Returns:
 3128: #    1    - Continue processing.
 3129: #    0    - Exit the server.
 3130: #
 3131: sub get_profile_keys {
 3132:     my ($cmd, $tail, $client) = @_;
 3133: 
 3134:     my $userinput = "$cmd:$tail";
 3135: 
 3136:     my ($udom,$uname,$namespace)=split(/:/,$tail);
 3137:     my $qresult='';
 3138:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3139: 				  &GDBM_READER());
 3140:     if ($hashref) {
 3141: 	foreach my $key (keys %$hashref) {
 3142: 	    $qresult.="$key&";
 3143: 	}
 3144: 	if (&untie_user_hash($hashref)) {
 3145: 	    $qresult=~s/\&$//;
 3146: 	    &Reply($client, \$qresult, $userinput);
 3147: 	} else {
 3148: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3149: 		    "while attempting keys\n", $userinput);
 3150: 	}
 3151:     } else {
 3152: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3153: 		 "while attempting keys\n", $userinput);
 3154:     }
 3155:    
 3156:     return 1;
 3157: }
 3158: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
 3159: 
 3160: #
 3161: #   Dump the contents of a user profile database.
 3162: #   Note that this constitutes a very large covert channel too since
 3163: #   the dump will return sensitive information that is not encrypted.
 3164: #   The naive security assumption is that the session negotiation ensures
 3165: #   our client is trusted and I don't believe that's assured at present.
 3166: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
 3167: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
 3168: # 
 3169: #  Parameters:
 3170: #     $cmd           - The command request keyword (currentdump).
 3171: #     $tail          - Remainder of the request, consisting of a colon
 3172: #                      separated list that has the domain/username and
 3173: #                      the namespace to dump (database file).
 3174: #     $client        - file open on the remote client.
 3175: # Returns:
 3176: #     1    - Continue processing.
 3177: #     0    - Exit the server.
 3178: #
 3179: sub dump_profile_database {
 3180:     my ($cmd, $tail, $client) = @_;
 3181: 
 3182:     my $userinput = "$cmd:$tail";
 3183:    
 3184:     my ($udom,$uname,$namespace) = split(/:/,$tail);
 3185:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3186: 				 &GDBM_READER());
 3187:     if ($hashref) {
 3188: 	# Structure of %data:
 3189: 	# $data{$symb}->{$parameter}=$value;
 3190: 	# $data{$symb}->{'v.'.$parameter}=$version;
 3191: 	# since $parameter will be unescaped, we do not
 3192:  	# have to worry about silly parameter names...
 3193: 	
 3194:         my $qresult='';
 3195: 	my %data = ();                     # A hash of anonymous hashes..
 3196: 	while (my ($key,$value) = each(%$hashref)) {
 3197: 	    my ($v,$symb,$param) = split(/:/,$key);
 3198: 	    next if ($v eq 'version' || $symb eq 'keys');
 3199: 	    next if (exists($data{$symb}) && 
 3200: 		     exists($data{$symb}->{$param}) &&
 3201: 		     $data{$symb}->{'v.'.$param} > $v);
 3202: 	    $data{$symb}->{$param}=$value;
 3203: 	    $data{$symb}->{'v.'.$param}=$v;
 3204: 	}
 3205: 	if (&untie_user_hash($hashref)) {
 3206: 	    while (my ($symb,$param_hash) = each(%data)) {
 3207: 		while(my ($param,$value) = each (%$param_hash)){
 3208: 		    next if ($param =~ /^v\./);       # Ignore versions...
 3209: 		    #
 3210: 		    #   Just dump the symb=value pairs separated by &
 3211: 		    #
 3212: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
 3213: 		}
 3214: 	    }
 3215: 	    chop($qresult);
 3216: 	    &Reply($client , \$qresult, $userinput);
 3217: 	} else {
 3218: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 3219: 		     "while attempting currentdump\n", $userinput);
 3220: 	}
 3221:     } else {
 3222: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3223: 		"while attempting currentdump\n", $userinput);
 3224:     }
 3225: 
 3226:     return 1;
 3227: }
 3228: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
 3229: 
 3230: #
 3231: #   Dump a profile database with an optional regular expression
 3232: #   to match against the keys.  In this dump, no effort is made
 3233: #   to separate symb from version information. Presumably the
 3234: #   databases that are dumped by this command are of a different
 3235: #   structure.  Need to look at this and improve the documentation of
 3236: #   both this and the currentdump handler.
 3237: # Parameters:
 3238: #    $cmd                     - The command keyword.
 3239: #    $tail                    - All of the characters after the $cmd:
 3240: #                               These are expected to be a colon
 3241: #                               separated list containing:
 3242: #                               domain/user - identifying the user.
 3243: #                               namespace   - identifying the database.
 3244: #                               regexp      - optional regular expression
 3245: #                                             that is matched against
 3246: #                                             database keywords to do
 3247: #                                             selective dumps.
 3248: #   $client                   - Channel open on the client.
 3249: # Returns:
 3250: #    1    - Continue processing.
 3251: # Side effects:
 3252: #    response is written to $client.
 3253: #
 3254: sub dump_with_regexp {
 3255:     my ($cmd, $tail, $client) = @_;
 3256: 
 3257: 
 3258:     my $userinput = "$cmd:$tail";
 3259: 
 3260:     my ($udom,$uname,$namespace,$regexp,$range,$extra)=split(/:/,$tail);
 3261:     if (defined($regexp)) {
 3262: 	$regexp=&unescape($regexp);
 3263:     } else {
 3264: 	$regexp='.';
 3265:     }
 3266:     my ($start,$end);
 3267:     if (defined($range)) {
 3268: 	if ($range =~/^(\d+)\-(\d+)$/) {
 3269: 	    ($start,$end) = ($1,$2);
 3270: 	} elsif ($range =~/^(\d+)$/) {
 3271: 	    ($start,$end) = (0,$1);
 3272: 	} else {
 3273: 	    undef($range);
 3274: 	}
 3275:     }
 3276:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3277: 				 &GDBM_READER());
 3278:     my $skipcheck;
 3279:     if ($hashref) {
 3280:         my $qresult='';
 3281: 	my $count=0;
 3282:         if ($extra ne '') {
 3283:             $extra = &Apache::lonnet::thaw_unescape($extra);
 3284:             $skipcheck = $extra->{'skipcheck'};
 3285:         }
 3286:         my @ids = &Apache::lonnet::current_machine_ids();
 3287:         my (%homecourses,$major,$minor,$now);
 3288:         if (($namespace eq 'roles') && (!$skipcheck)) {
 3289:             my $loncaparev = $clientversion;
 3290:             if ($loncaparev eq '') {
 3291:                 $loncaparev = $Apache::lonnet::loncaparevs{$clientname};
 3292:             }
 3293:             if ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?/) {
 3294:                 $major = $1;
 3295:                 $minor = $2;
 3296:             }
 3297:             $now = time;
 3298:         }
 3299: 	while (my ($key,$value) = each(%$hashref)) {
 3300:             if ($namespace eq 'roles') {
 3301:                 if ($key =~ m{^/($LONCAPA::match_domain)/($LONCAPA::match_courseid)(/?[^_]*)_(cc|co|in|ta|ep|ad|st|cr)$}) {
 3302:                     my $cdom = $1;
 3303:                     my $cnum = $2;
 3304:                     unless ($skipcheck) {
 3305:                         my ($role,$end,$start) = split(/\_/,$value);
 3306:                         if (!$end || $end > $now) {
 3307:                             next unless (&releasereqd_check($cnum,$cdom,$key,$value,$major,
 3308:                                                             $minor,\%homecourses,\@ids));
 3309:                         }
 3310:                     }
 3311:                 }
 3312:             }
 3313: 	    if ($regexp eq '.') {
 3314: 		$count++;
 3315: 		if (defined($range) && $count >= $end)   { last; }
 3316: 		if (defined($range) && $count <  $start) { next; }
 3317: 		$qresult.=$key.'='.$value.'&';
 3318: 	    } else {
 3319: 		my $unescapeKey = &unescape($key);
 3320: 		if (eval('$unescapeKey=~/$regexp/')) {
 3321: 		    $count++;
 3322: 		    if (defined($range) && $count >= $end)   { last; }
 3323: 		    if (defined($range) && $count <  $start) { next; }
 3324: 		    $qresult.="$key=$value&";
 3325: 		}
 3326: 	    }
 3327: 	}
 3328: 	if (&untie_user_hash($hashref)) {
 3329:             if (($namespace eq 'roles') && (!$skipcheck)) {
 3330:                 if (keys(%homecourses) > 0) {
 3331:                     $qresult .= &check_homecourses(\%homecourses,$udom,$regexp,$count,
 3332:                                                    $range,$start,$end,$major,$minor);
 3333:                 }
 3334:             }
 3335: 	    chop($qresult);
 3336: 	    &Reply($client, \$qresult, $userinput);
 3337: 	} else {
 3338: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 3339: 		     "while attempting dump\n", $userinput);
 3340: 	}
 3341:     } else {
 3342: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3343: 		"while attempting dump\n", $userinput);
 3344:     }
 3345: 
 3346:     return 1;
 3347: }
 3348: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
 3349: 
 3350: #  Store a set of key=value pairs associated with a versioned name.
 3351: #
 3352: #  Parameters:
 3353: #    $cmd                - Request command keyword.
 3354: #    $tail               - Tail of the request.  This is a colon
 3355: #                          separated list containing:
 3356: #                          domain/user - User and authentication domain.
 3357: #                          namespace   - Name of the database being modified
 3358: #                          rid         - Resource keyword to modify.
 3359: #                          what        - new value associated with rid.
 3360: #
 3361: #    $client             - Socket open on the client.
 3362: #
 3363: #
 3364: #  Returns:
 3365: #      1 (keep on processing).
 3366: #  Side-Effects:
 3367: #    Writes to the client
 3368: sub store_handler {
 3369:     my ($cmd, $tail, $client) = @_;
 3370:  
 3371:     my $userinput = "$cmd:$tail";
 3372: 
 3373:     my ($udom,$uname,$namespace,$rid,$what) =split(/:/,$tail);
 3374:     if ($namespace ne 'roles') {
 3375: 
 3376: 	chomp($what);
 3377: 	my @pairs=split(/\&/,$what);
 3378: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
 3379: 				       &GDBM_WRCREAT(), "S",
 3380: 				       "$rid:$what");
 3381: 	if ($hashref) {
 3382: 	    my $now = time;
 3383: 	    my @previouskeys=split(/&/,$hashref->{"keys:$rid"});
 3384: 	    my $key;
 3385: 	    $hashref->{"version:$rid"}++;
 3386: 	    my $version=$hashref->{"version:$rid"};
 3387: 	    my $allkeys=''; 
 3388: 	    foreach my $pair (@pairs) {
 3389: 		my ($key,$value)=split(/=/,$pair);
 3390: 		$allkeys.=$key.':';
 3391: 		$hashref->{"$version:$rid:$key"}=$value;
 3392: 	    }
 3393: 	    $hashref->{"$version:$rid:timestamp"}=$now;
 3394: 	    $allkeys.='timestamp';
 3395: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
 3396: 	    if (&untie_user_hash($hashref)) {
 3397: 		&Reply($client, "ok\n", $userinput);
 3398: 	    } else {
 3399: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3400: 			"while attempting store\n", $userinput);
 3401: 	    }
 3402: 	} else {
 3403: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3404: 		     "while attempting store\n", $userinput);
 3405: 	}
 3406:     } else {
 3407: 	&Failure($client, "refused\n", $userinput);
 3408:     }
 3409: 
 3410:     return 1;
 3411: }
 3412: &register_handler("store", \&store_handler, 0, 1, 0);
 3413: 
 3414: #  Modify a set of key=value pairs associated with a versioned name.
 3415: #
 3416: #  Parameters:
 3417: #    $cmd                - Request command keyword.
 3418: #    $tail               - Tail of the request.  This is a colon
 3419: #                          separated list containing:
 3420: #                          domain/user - User and authentication domain.
 3421: #                          namespace   - Name of the database being modified
 3422: #                          rid         - Resource keyword to modify.
 3423: #                          v           - Version item to modify
 3424: #                          what        - new value associated with rid.
 3425: #
 3426: #    $client             - Socket open on the client.
 3427: #
 3428: #
 3429: #  Returns:
 3430: #      1 (keep on processing).
 3431: #  Side-Effects:
 3432: #    Writes to the client
 3433: sub putstore_handler {
 3434:     my ($cmd, $tail, $client) = @_;
 3435:  
 3436:     my $userinput = "$cmd:$tail";
 3437: 
 3438:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
 3439:     if ($namespace ne 'roles') {
 3440: 
 3441: 	chomp($what);
 3442: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
 3443: 				       &GDBM_WRCREAT(), "M",
 3444: 				       "$rid:$v:$what");
 3445: 	if ($hashref) {
 3446: 	    my $now = time;
 3447: 	    my %data = &hash_extract($what);
 3448: 	    my @allkeys;
 3449: 	    while (my($key,$value) = each(%data)) {
 3450: 		push(@allkeys,$key);
 3451: 		$hashref->{"$v:$rid:$key"} = $value;
 3452: 	    }
 3453: 	    my $allkeys = join(':',@allkeys);
 3454: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
 3455: 
 3456: 	    if (&untie_user_hash($hashref)) {
 3457: 		&Reply($client, "ok\n", $userinput);
 3458: 	    } else {
 3459: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3460: 			"while attempting store\n", $userinput);
 3461: 	    }
 3462: 	} else {
 3463: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3464: 		     "while attempting store\n", $userinput);
 3465: 	}
 3466:     } else {
 3467: 	&Failure($client, "refused\n", $userinput);
 3468:     }
 3469: 
 3470:     return 1;
 3471: }
 3472: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
 3473: 
 3474: sub hash_extract {
 3475:     my ($str)=@_;
 3476:     my %hash;
 3477:     foreach my $pair (split(/\&/,$str)) {
 3478: 	my ($key,$value)=split(/=/,$pair);
 3479: 	$hash{$key}=$value;
 3480:     }
 3481:     return (%hash);
 3482: }
 3483: sub hash_to_str {
 3484:     my ($hash_ref)=@_;
 3485:     my $str;
 3486:     foreach my $key (keys(%$hash_ref)) {
 3487: 	$str.=$key.'='.$hash_ref->{$key}.'&';
 3488:     }
 3489:     $str=~s/\&$//;
 3490:     return $str;
 3491: }
 3492: 
 3493: #
 3494: #  Dump out all versions of a resource that has key=value pairs associated
 3495: # with it for each version.  These resources are built up via the store
 3496: # command.
 3497: #
 3498: #  Parameters:
 3499: #     $cmd               - Command keyword.
 3500: #     $tail              - Remainder of the request which consists of:
 3501: #                          domain/user   - User and auth. domain.
 3502: #                          namespace     - name of resource database.
 3503: #                          rid           - Resource id.
 3504: #    $client             - socket open on the client.
 3505: #
 3506: # Returns:
 3507: #      1  indicating the caller should not yet exit.
 3508: # Side-effects:
 3509: #   Writes a reply to the client.
 3510: #   The reply is a string of the following shape:
 3511: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
 3512: #    Where the 1 above represents version 1.
 3513: #    this continues for all pairs of keys in all versions.
 3514: #
 3515: #
 3516: #    
 3517: #
 3518: sub restore_handler {
 3519:     my ($cmd, $tail, $client) = @_;
 3520: 
 3521:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
 3522:     my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
 3523:     $namespace=~s/\//\_/g;
 3524:     $namespace = &LONCAPA::clean_username($namespace);
 3525: 
 3526:     chomp($rid);
 3527:     my $qresult='';
 3528:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
 3529:     if ($hashref) {
 3530: 	my $version=$hashref->{"version:$rid"};
 3531: 	$qresult.="version=$version&";
 3532: 	my $scope;
 3533: 	for ($scope=1;$scope<=$version;$scope++) {
 3534: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
 3535: 	    my @keys=split(/:/,$vkeys);
 3536: 	    my $key;
 3537: 	    $qresult.="$scope:keys=$vkeys&";
 3538: 	    foreach $key (@keys) {
 3539: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
 3540: 	    }                                  
 3541: 	}
 3542: 	if (&untie_user_hash($hashref)) {
 3543: 	    $qresult=~s/\&$//;
 3544: 	    &Reply( $client, \$qresult, $userinput);
 3545: 	} else {
 3546: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3547: 		    "while attempting restore\n", $userinput);
 3548: 	}
 3549:     } else {
 3550: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3551: 		"while attempting restore\n", $userinput);
 3552:     }
 3553:   
 3554:     return 1;
 3555: 
 3556: 
 3557: }
 3558: &register_handler("restore", \&restore_handler, 0,1,0);
 3559: 
 3560: #
 3561: #   Add a chat message to a synchronous discussion board.
 3562: #
 3563: # Parameters:
 3564: #    $cmd                - Request keyword.
 3565: #    $tail               - Tail of the command. A colon separated list
 3566: #                          containing:
 3567: #                          cdom    - Domain on which the chat board lives
 3568: #                          cnum    - Course containing the chat board.
 3569: #                          newpost - Body of the posting.
 3570: #                          group   - Optional group, if chat board is only 
 3571: #                                    accessible in a group within the course 
 3572: #   $client              - Socket open on the client.
 3573: # Returns:
 3574: #   1    - Indicating caller should keep on processing.
 3575: #
 3576: # Side-effects:
 3577: #   writes a reply to the client.
 3578: #
 3579: #
 3580: sub send_chat_handler {
 3581:     my ($cmd, $tail, $client) = @_;
 3582: 
 3583:     
 3584:     my $userinput = "$cmd:$tail";
 3585: 
 3586:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
 3587:     &chat_add($cdom,$cnum,$newpost,$group);
 3588:     &Reply($client, "ok\n", $userinput);
 3589: 
 3590:     return 1;
 3591: }
 3592: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
 3593: 
 3594: #
 3595: #   Retrieve the set of chat messages from a discussion board.
 3596: #
 3597: #  Parameters:
 3598: #    $cmd             - Command keyword that initiated the request.
 3599: #    $tail            - Remainder of the request after the command
 3600: #                       keyword.  In this case a colon separated list of
 3601: #                       chat domain    - Which discussion board.
 3602: #                       chat id        - Discussion thread(?)
 3603: #                       domain/user    - Authentication domain and username
 3604: #                                        of the requesting person.
 3605: #                       group          - Optional course group containing
 3606: #                                        the board.      
 3607: #   $client           - Socket open on the client program.
 3608: # Returns:
 3609: #    1     - continue processing
 3610: # Side effects:
 3611: #    Response is written to the client.
 3612: #
 3613: sub retrieve_chat_handler {
 3614:     my ($cmd, $tail, $client) = @_;
 3615: 
 3616: 
 3617:     my $userinput = "$cmd:$tail";
 3618: 
 3619:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
 3620:     my $reply='';
 3621:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
 3622: 	$reply.=&escape($_).':';
 3623:     }
 3624:     $reply=~s/\:$//;
 3625:     &Reply($client, \$reply, $userinput);
 3626: 
 3627: 
 3628:     return 1;
 3629: }
 3630: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
 3631: 
 3632: #
 3633: #  Initiate a query of an sql database.  SQL query repsonses get put in
 3634: #  a file for later retrieval.  This prevents sql query results from
 3635: #  bottlenecking the system.  Note that with loncnew, perhaps this is
 3636: #  less of an issue since multiple outstanding requests can be concurrently
 3637: #  serviced.
 3638: #
 3639: #  Parameters:
 3640: #     $cmd       - COmmand keyword that initiated the request.
 3641: #     $tail      - Remainder of the command after the keyword.
 3642: #                  For this function, this consists of a query and
 3643: #                  3 arguments that are self-documentingly labelled
 3644: #                  in the original arg1, arg2, arg3.
 3645: #     $client    - Socket open on the client.
 3646: # Return:
 3647: #    1   - Indicating processing should continue.
 3648: # Side-effects:
 3649: #    a reply is written to $client.
 3650: #
 3651: sub send_query_handler {
 3652:     my ($cmd, $tail, $client) = @_;
 3653: 
 3654: 
 3655:     my $userinput = "$cmd:$tail";
 3656: 
 3657:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
 3658:     $query=~s/\n*$//g;
 3659:     &Reply($client, "". &sql_reply("$clientname\&$query".
 3660: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
 3661: 	  $userinput);
 3662:     
 3663:     return 1;
 3664: }
 3665: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
 3666: 
 3667: #
 3668: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
 3669: #   The query is submitted via a "querysend" transaction.
 3670: #   There it is passed on to the lonsql daemon, queued and issued to
 3671: #   mysql.
 3672: #     This transaction is invoked when the sql transaction is complete
 3673: #   it stores the query results in flie and indicates query completion.
 3674: #   presumably local software then fetches this response... I'm guessing
 3675: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
 3676: #   lonsql on completion of the query interacts with the lond of our
 3677: #   client to do a query reply storing two files:
 3678: #    - id     - The results of the query.
 3679: #    - id.end - Indicating the transaction completed. 
 3680: #    NOTE: id is a unique id assigned to the query and querysend time.
 3681: # Parameters:
 3682: #    $cmd        - Command keyword that initiated this request.
 3683: #    $tail       - Remainder of the tail.  In this case that's a colon
 3684: #                  separated list containing the query Id and the 
 3685: #                  results of the query.
 3686: #    $client     - Socket open on the client.
 3687: # Return:
 3688: #    1           - Indicating that we should continue processing.
 3689: # Side effects:
 3690: #    ok written to the client.
 3691: #
 3692: sub reply_query_handler {
 3693:     my ($cmd, $tail, $client) = @_;
 3694: 
 3695: 
 3696:     my $userinput = "$cmd:$tail";
 3697: 
 3698:     my ($id,$reply)=split(/:/,$tail); 
 3699:     my $store;
 3700:     my $execdir=$perlvar{'lonDaemons'};
 3701:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
 3702: 	$reply=~s/\&/\n/g;
 3703: 	print $store $reply;
 3704: 	close $store;
 3705: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
 3706: 	print $store2 "done\n";
 3707: 	close $store2;
 3708: 	&Reply($client, "ok\n", $userinput);
 3709:     } else {
 3710: 	&Failure($client, "error: ".($!+0)
 3711: 		." IO::File->new Failed ".
 3712: 		"while attempting queryreply\n", $userinput);
 3713:     }
 3714:  
 3715: 
 3716:     return 1;
 3717: }
 3718: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
 3719: 
 3720: #
 3721: #  Process the courseidput request.  Not quite sure what this means
 3722: #  at the system level sense.  It appears a gdbm file in the 
 3723: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
 3724: #  a set of entries made in that database.
 3725: #
 3726: # Parameters:
 3727: #   $cmd      - The command keyword that initiated this request.
 3728: #   $tail     - Tail of the command.  In this case consists of a colon
 3729: #               separated list contaning the domain to apply this to and
 3730: #               an ampersand separated list of keyword=value pairs.
 3731: #               Each value is a colon separated list that includes:  
 3732: #               description, institutional code and course owner.
 3733: #               For backward compatibility with versions included
 3734: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
 3735: #               code and/or course owner are preserved from the existing 
 3736: #               record when writing a new record in response to 1.1 or 
 3737: #               1.2 implementations of lonnet::flushcourselogs().   
 3738: #                      
 3739: #   $client   - Socket open on the client.
 3740: # Returns:
 3741: #   1    - indicating that processing should continue
 3742: #
 3743: # Side effects:
 3744: #   reply is written to the client.
 3745: #
 3746: sub put_course_id_handler {
 3747:     my ($cmd, $tail, $client) = @_;
 3748: 
 3749: 
 3750:     my $userinput = "$cmd:$tail";
 3751: 
 3752:     my ($udom, $what) = split(/:/, $tail,2);
 3753:     chomp($what);
 3754:     my $now=time;
 3755:     my @pairs=split(/\&/,$what);
 3756: 
 3757:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 3758:     if ($hashref) {
 3759: 	foreach my $pair (@pairs) {
 3760:             my ($key,$courseinfo) = split(/=/,$pair,2);
 3761:             $courseinfo =~ s/=/:/g;
 3762:             if (defined($hashref->{$key})) {
 3763:                 my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
 3764:                 if (ref($value) eq 'HASH') {
 3765:                     my @items = ('description','inst_code','owner','type');
 3766:                     my @new_items = split(/:/,$courseinfo,-1);
 3767:                     my %storehash; 
 3768:                     for (my $i=0; $i<@new_items; $i++) {
 3769:                         $storehash{$items[$i]} = &unescape($new_items[$i]);
 3770:                     }
 3771:                     $hashref->{$key} = 
 3772:                         &Apache::lonnet::freeze_escape(\%storehash);
 3773:                     my $unesc_key = &unescape($key);
 3774:                     $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
 3775:                     next;
 3776:                 }
 3777:             }
 3778:             my @current_items = split(/:/,$hashref->{$key},-1);
 3779:             shift(@current_items); # remove description
 3780:             pop(@current_items);   # remove last access
 3781:             my $numcurrent = scalar(@current_items);
 3782:             if ($numcurrent > 3) {
 3783:                 $numcurrent = 3;
 3784:             }
 3785:             my @new_items = split(/:/,$courseinfo,-1);
 3786:             my $numnew = scalar(@new_items);
 3787:             if ($numcurrent > 0) {
 3788:                 if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2 
 3789:                     for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
 3790:                         $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
 3791:                     }
 3792:                 }
 3793:             }
 3794:             $hashref->{$key}=$courseinfo.':'.$now;
 3795: 	}
 3796: 	if (&untie_domain_hash($hashref)) {
 3797: 	    &Reply( $client, "ok\n", $userinput);
 3798: 	} else {
 3799: 	    &Failure($client, "error: ".($!+0)
 3800: 		     ." untie(GDBM) Failed ".
 3801: 		     "while attempting courseidput\n", $userinput);
 3802: 	}
 3803:     } else {
 3804: 	&Failure($client, "error: ".($!+0)
 3805: 		 ." tie(GDBM) Failed ".
 3806: 		 "while attempting courseidput\n", $userinput);
 3807:     }
 3808: 
 3809:     return 1;
 3810: }
 3811: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
 3812: 
 3813: sub put_course_id_hash_handler {
 3814:     my ($cmd, $tail, $client) = @_;
 3815:     my $userinput = "$cmd:$tail";
 3816:     my ($udom,$mode,$what) = split(/:/, $tail,3);
 3817:     chomp($what);
 3818:     my $now=time;
 3819:     my @pairs=split(/\&/,$what);
 3820:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 3821:     if ($hashref) {
 3822:         foreach my $pair (@pairs) {
 3823:             my ($key,$value)=split(/=/,$pair);
 3824:             my $unesc_key = &unescape($key);
 3825:             if ($mode ne 'timeonly') {
 3826:                 if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
 3827:                     my $curritems = &Apache::lonnet::thaw_unescape($key); 
 3828:                     if (ref($curritems) ne 'HASH') {
 3829:                         my @current_items = split(/:/,$hashref->{$key},-1);
 3830:                         my $lasttime = pop(@current_items);
 3831:                         $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
 3832:                     } else {
 3833:                         $hashref->{&escape('lasttime:'.$unesc_key)} = '';
 3834:                     }
 3835:                 } 
 3836:                 $hashref->{$key} = $value;
 3837:             }
 3838:             if ($mode ne 'notime') {
 3839:                 $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
 3840:             }
 3841:         }
 3842:         if (&untie_domain_hash($hashref)) {
 3843:             &Reply($client, "ok\n", $userinput);
 3844:         } else {
 3845:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3846:                      "while attempting courseidputhash\n", $userinput);
 3847:         }
 3848:     } else {
 3849:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3850:                   "while attempting courseidputhash\n", $userinput);
 3851:     }
 3852:     return 1;
 3853: }
 3854: &register_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
 3855: 
 3856: #  Retrieves the value of a course id resource keyword pattern
 3857: #  defined since a starting date.  Both the starting date and the
 3858: #  keyword pattern are optional.  If the starting date is not supplied it
 3859: #  is treated as the beginning of time.  If the pattern is not found,
 3860: #  it is treatred as "." matching everything.
 3861: #
 3862: #  Parameters:
 3863: #     $cmd     - Command keyword that resulted in us being dispatched.
 3864: #     $tail    - The remainder of the command that, in this case, consists
 3865: #                of a colon separated list of:
 3866: #                 domain   - The domain in which the course database is 
 3867: #                            defined.
 3868: #                 since    - Optional parameter describing the minimum
 3869: #                            time of definition(?) of the resources that
 3870: #                            will match the dump.
 3871: #                 description - regular expression that is used to filter
 3872: #                            the dump.  Only keywords matching this regexp
 3873: #                            will be used.
 3874: #                 institutional code - optional supplied code to filter 
 3875: #                            the dump. Only courses with an institutional code 
 3876: #                            that match the supplied code will be returned.
 3877: #                 owner    - optional supplied username and domain of owner to
 3878: #                            filter the dump.  Only courses for which the course
 3879: #                            owner matches the supplied username and/or domain
 3880: #                            will be returned. Pre-2.2.0 legacy entries from 
 3881: #                            nohist_courseiddump will only contain usernames.
 3882: #                 type     - optional parameter for selection 
 3883: #                 regexp_ok - if 1 or -1 allow the supplied institutional code
 3884: #                            filter to behave as a regular expression:
 3885: #	                      1 will not exclude the course if the instcode matches the RE 
 3886: #                            -1 will exclude the course if the instcode matches the RE
 3887: #                 rtn_as_hash - whether to return the information available for
 3888: #                            each matched item as a frozen hash of all 
 3889: #                            key, value pairs in the item's hash, or as a 
 3890: #                            colon-separated list of (in order) description,
 3891: #                            institutional code, and course owner.
 3892: #                 selfenrollonly - filter by courses allowing self-enrollment  
 3893: #                                  now or in the future (selfenrollonly = 1).
 3894: #                 catfilter - filter by course category, assigned to a course 
 3895: #                             using manually defined categories (i.e., not
 3896: #                             self-cataloging based on on institutional code).   
 3897: #                 showhidden - include course in results even if course  
 3898: #                              was set to be excluded from course catalog (DC only).
 3899: #                 caller -  if set to 'coursecatalog', courses set to be hidden
 3900: #                           from course catalog will be excluded from results (unless
 3901: #                           overridden by "showhidden".
 3902: #                 cloner - escaped username:domain of course cloner (if picking course to
 3903: #                          clone).
 3904: #                 cc_clone_list - escaped comma separated list of courses for which 
 3905: #                                 course cloner has active CC role (and so can clone
 3906: #                                 automatically).
 3907: #                 cloneonly - filter by courses for which cloner has rights to clone.
 3908: #                 createdbefore - include courses for which creation date preceeded this date.
 3909: #                 createdafter - include courses for which creation date followed this date.
 3910: #                 creationcontext - include courses created in specified context 
 3911: #
 3912: #                 domcloner - flag to indicate if user can create CCs in course's domain.
 3913: #                             If so, ability to clone course is automatic. 
 3914: #
 3915: #     $client  - The socket open on the client.
 3916: # Returns:
 3917: #    1     - Continue processing.
 3918: # Side Effects:
 3919: #   a reply is written to $client.
 3920: sub dump_course_id_handler {
 3921:     my ($cmd, $tail, $client) = @_;
 3922:     my $userinput = "$cmd:$tail";
 3923: 
 3924:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
 3925:         $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
 3926:         $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
 3927:         $creationcontext,$domcloner) =split(/:/,$tail);
 3928:     my $now = time;
 3929:     my ($cloneruname,$clonerudom,%cc_clone);
 3930:     if (defined($description)) {
 3931: 	$description=&unescape($description);
 3932:     } else {
 3933: 	$description='.';
 3934:     }
 3935:     if (defined($instcodefilter)) {
 3936:         $instcodefilter=&unescape($instcodefilter);
 3937:     } else {
 3938:         $instcodefilter='.';
 3939:     }
 3940:     my ($ownerunamefilter,$ownerdomfilter);
 3941:     if (defined($ownerfilter)) {
 3942:         $ownerfilter=&unescape($ownerfilter);
 3943:         if ($ownerfilter ne '.' && defined($ownerfilter)) {
 3944:             if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
 3945:                  $ownerunamefilter = $1;
 3946:                  $ownerdomfilter = $2;
 3947:             } else {
 3948:                 $ownerunamefilter = $ownerfilter;
 3949:                 $ownerdomfilter = '';
 3950:             }
 3951:         }
 3952:     } else {
 3953:         $ownerfilter='.';
 3954:     }
 3955: 
 3956:     if (defined($coursefilter)) {
 3957:         $coursefilter=&unescape($coursefilter);
 3958:     } else {
 3959:         $coursefilter='.';
 3960:     }
 3961:     if (defined($typefilter)) {
 3962:         $typefilter=&unescape($typefilter);
 3963:     } else {
 3964:         $typefilter='.';
 3965:     }
 3966:     if (defined($regexp_ok)) {
 3967:         $regexp_ok=&unescape($regexp_ok);
 3968:     }
 3969:     if (defined($catfilter)) {
 3970:         $catfilter=&unescape($catfilter);
 3971:     }
 3972:     if (defined($cloner)) {
 3973:         $cloner = &unescape($cloner);
 3974:         ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/); 
 3975:     }
 3976:     if (defined($cc_clone_list)) {
 3977:         $cc_clone_list = &unescape($cc_clone_list);
 3978:         my @cc_cloners = split('&',$cc_clone_list);
 3979:         foreach my $cid (@cc_cloners) {
 3980:             my ($clonedom,$clonenum) = split(':',$cid);
 3981:             next if ($clonedom ne $udom); 
 3982:             $cc_clone{$clonedom.'_'.$clonenum} = 1;
 3983:         } 
 3984:     }
 3985:     if ($createdbefore ne '') {
 3986:         $createdbefore = &unescape($createdbefore);
 3987:     } else {
 3988:        $createdbefore = 0;
 3989:     }
 3990:     if ($createdafter ne '') {
 3991:         $createdafter = &unescape($createdafter);
 3992:     } else {
 3993:         $createdafter = 0;
 3994:     }
 3995:     if ($creationcontext ne '') {
 3996:         $creationcontext = &unescape($creationcontext);
 3997:     } else {
 3998:         $creationcontext = '.';
 3999:     }
 4000:     my $unpack = 1;
 4001:     if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' && 
 4002:         $typefilter eq '.') {
 4003:         $unpack = 0;
 4004:     }
 4005:     if (!defined($since)) { $since=0; }
 4006:     my $qresult='';
 4007:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 4008:     if ($hashref) {
 4009: 	while (my ($key,$value) = each(%$hashref)) {
 4010:             my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
 4011:                 %unesc_val,$selfenroll_end,$selfenroll_types,$created,
 4012:                 $context);
 4013:             $unesc_key = &unescape($key);
 4014:             if ($unesc_key =~ /^lasttime:/) {
 4015:                 next;
 4016:             } else {
 4017:                 $lasttime_key = &escape('lasttime:'.$unesc_key);
 4018:             }
 4019:             if ($hashref->{$lasttime_key} ne '') {
 4020:                 $lasttime = $hashref->{$lasttime_key};
 4021:                 next if ($lasttime<$since);
 4022:             }
 4023:             my ($canclone,$valchange);
 4024:             my $items = &Apache::lonnet::thaw_unescape($value);
 4025:             if (ref($items) eq 'HASH') {
 4026:                 if ($hashref->{$lasttime_key} eq '') {
 4027:                     next if ($since > 1);
 4028:                 }
 4029:                 $is_hash =  1;
 4030:                 if ($domcloner) {
 4031:                     $canclone = 1;
 4032:                 } elsif (defined($clonerudom)) {
 4033:                     if ($items->{'cloners'}) {
 4034:                         my @cloneable = split(',',$items->{'cloners'});
 4035:                         if (@cloneable) {
 4036:                             if (grep(/^\*$/,@cloneable))  {
 4037:                                 $canclone = 1;
 4038:                             } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
 4039:                                 $canclone = 1;
 4040:                             } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
 4041:                                 $canclone = 1;
 4042:                             }
 4043:                         }
 4044:                         unless ($canclone) {
 4045:                             if ($cloneruname ne '' && $clonerudom ne '') {
 4046:                                 if ($cc_clone{$unesc_key}) {
 4047:                                     $canclone = 1;
 4048:                                     $items->{'cloners'} .= ','.$cloneruname.':'.
 4049:                                                            $clonerudom;
 4050:                                     $valchange = 1;
 4051:                                 }
 4052:                             }
 4053:                         }
 4054:                     } elsif (defined($cloneruname)) {
 4055:                         if ($cc_clone{$unesc_key}) {
 4056:                             $canclone = 1;
 4057:                             $items->{'cloners'} = $cloneruname.':'.$clonerudom;
 4058:                             $valchange = 1;
 4059:                         }
 4060:                         unless ($canclone) {
 4061:                             if ($items->{'owner'} =~ /:/) {
 4062:                                 if ($items->{'owner'} eq $cloner) {
 4063:                                     $canclone = 1;
 4064:                                 }
 4065:                             } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
 4066:                                 $canclone = 1;
 4067:                             }
 4068:                             if ($canclone) {
 4069:                                 $items->{'cloners'} = $cloneruname.':'.$clonerudom;
 4070:                                 $valchange = 1;
 4071:                             }
 4072:                         }
 4073:                     }
 4074:                 }
 4075:                 if ($unpack || !$rtn_as_hash) {
 4076:                     $unesc_val{'descr'} = $items->{'description'};
 4077:                     $unesc_val{'inst_code'} = $items->{'inst_code'};
 4078:                     $unesc_val{'owner'} = $items->{'owner'};
 4079:                     $unesc_val{'type'} = $items->{'type'};
 4080:                     $unesc_val{'cloners'} = $items->{'cloners'};
 4081:                     $unesc_val{'created'} = $items->{'created'};
 4082:                     $unesc_val{'context'} = $items->{'context'};
 4083:                 }
 4084:                 $selfenroll_types = $items->{'selfenroll_types'};
 4085:                 $selfenroll_end = $items->{'selfenroll_end_date'};
 4086:                 $created = $items->{'created'};
 4087:                 $context = $items->{'context'};
 4088:                 if ($selfenrollonly) {
 4089:                     next if (!$selfenroll_types);
 4090:                     if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
 4091:                         next;
 4092:                     }
 4093:                 }
 4094:                 if ($creationcontext ne '.') {
 4095:                     next if (($context ne '') && ($context ne $creationcontext));  
 4096:                 }
 4097:                 if ($createdbefore > 0) {
 4098:                     next if (($created eq '') || ($created > $createdbefore));   
 4099:                 }
 4100:                 if ($createdafter > 0) {
 4101:                     next if (($created eq '') || ($created <= $createdafter)); 
 4102:                 }
 4103:                 if ($catfilter ne '') {
 4104:                     next if ($items->{'categories'} eq '');
 4105:                     my @categories = split('&',$items->{'categories'}); 
 4106:                     next if (@categories == 0);
 4107:                     my @subcats = split('&',$catfilter);
 4108:                     my $matchcat = 0;
 4109:                     foreach my $cat (@categories) {
 4110:                         if (grep(/^\Q$cat\E$/,@subcats)) {
 4111:                             $matchcat = 1;
 4112:                             last;
 4113:                         }
 4114:                     }
 4115:                     next if (!$matchcat);
 4116:                 }
 4117:                 if ($caller eq 'coursecatalog') {
 4118:                     if ($items->{'hidefromcat'} eq 'yes') {
 4119:                         next if !$showhidden;
 4120:                     }
 4121:                 }
 4122:             } else {
 4123:                 next if ($catfilter ne '');
 4124:                 next if ($selfenrollonly);
 4125:                 next if ($createdbefore || $createdafter);
 4126:                 next if ($creationcontext ne '.');
 4127:                 if ((defined($clonerudom)) && (defined($cloneruname)))  {
 4128:                     if ($cc_clone{$unesc_key}) {
 4129:                         $canclone = 1;
 4130:                         $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
 4131:                     }
 4132:                 }
 4133:                 $is_hash =  0;
 4134:                 my @courseitems = split(/:/,$value);
 4135:                 $lasttime = pop(@courseitems);
 4136:                 if ($hashref->{$lasttime_key} eq '') {
 4137:                     next if ($lasttime<$since);
 4138:                 }
 4139: 	        ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
 4140:             }
 4141:             if ($cloneonly) {
 4142:                next unless ($canclone);
 4143:             }
 4144:             my $match = 1;
 4145: 	    if ($description ne '.') {
 4146:                 if (!$is_hash) {
 4147:                     $unesc_val{'descr'} = &unescape($val{'descr'});
 4148:                 }
 4149:                 if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
 4150:                     $match = 0;
 4151:                 }
 4152:             }
 4153:             if ($instcodefilter ne '.') {
 4154:                 if (!$is_hash) {
 4155:                     $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
 4156:                 }
 4157:                 if ($regexp_ok == 1) {
 4158:                     if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
 4159:                         $match = 0;
 4160:                     }
 4161:                 } elsif ($regexp_ok == -1) {
 4162:                     if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
 4163:                         $match = 0;
 4164:                     }
 4165:                 } else {
 4166:                     if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
 4167:                         $match = 0;
 4168:                     }
 4169:                 }
 4170: 	    }
 4171:             if ($ownerfilter ne '.') {
 4172:                 if (!$is_hash) {
 4173:                     $unesc_val{'owner'} = &unescape($val{'owner'});
 4174:                 }
 4175:                 if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
 4176:                     if ($unesc_val{'owner'} =~ /:/) {
 4177:                         if (eval{$unesc_val{'owner'} !~ 
 4178:                              /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
 4179:                             $match = 0;
 4180:                         } 
 4181:                     } else {
 4182:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
 4183:                             $match = 0;
 4184:                         }
 4185:                     }
 4186:                 } elsif ($ownerunamefilter ne '') {
 4187:                     if ($unesc_val{'owner'} =~ /:/) {
 4188:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
 4189:                              $match = 0;
 4190:                         }
 4191:                     } else {
 4192:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
 4193:                             $match = 0;
 4194:                         }
 4195:                     }
 4196:                 } elsif ($ownerdomfilter ne '') {
 4197:                     if ($unesc_val{'owner'} =~ /:/) {
 4198:                         if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
 4199:                              $match = 0;
 4200:                         }
 4201:                     } else {
 4202:                         if ($ownerdomfilter ne $udom) {
 4203:                             $match = 0;
 4204:                         }
 4205:                     }
 4206:                 }
 4207:             }
 4208:             if ($coursefilter ne '.') {
 4209:                 if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
 4210:                     $match = 0;
 4211:                 }
 4212:             }
 4213:             if ($typefilter ne '.') {
 4214:                 if (!$is_hash) {
 4215:                     $unesc_val{'type'} = &unescape($val{'type'});
 4216:                 }
 4217:                 if ($unesc_val{'type'} eq '') {
 4218:                     if ($typefilter ne 'Course') {
 4219:                         $match = 0;
 4220:                     }
 4221:                 } else {
 4222:                     if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
 4223:                         $match = 0;
 4224:                     }
 4225:                 }
 4226:             }
 4227:             if ($match == 1) {
 4228:                 if ($rtn_as_hash) {
 4229:                     if ($is_hash) {
 4230:                         if ($valchange) {
 4231:                             my $newvalue = &Apache::lonnet::freeze_escape($items);
 4232:                             $qresult.=$key.'='.$newvalue.'&';
 4233:                         } else {
 4234:                             $qresult.=$key.'='.$value.'&';
 4235:                         }
 4236:                     } else {
 4237:                         my %rtnhash = ( 'description' => &unescape($val{'descr'}),
 4238:                                         'inst_code' => &unescape($val{'inst_code'}),
 4239:                                         'owner'     => &unescape($val{'owner'}),
 4240:                                         'type'      => &unescape($val{'type'}),
 4241:                                         'cloners'   => &unescape($val{'cloners'}),
 4242:                                       );
 4243:                         my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
 4244:                         $qresult.=$key.'='.$items.'&';
 4245:                     }
 4246:                 } else {
 4247:                     if ($is_hash) {
 4248:                         $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
 4249:                                     &escape($unesc_val{'inst_code'}).':'.
 4250:                                     &escape($unesc_val{'owner'}).'&';
 4251:                     } else {
 4252:                         $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
 4253:                                     ':'.$val{'owner'}.'&';
 4254:                     }
 4255:                 }
 4256:             }
 4257: 	}
 4258: 	if (&untie_domain_hash($hashref)) {
 4259: 	    chop($qresult);
 4260: 	    &Reply($client, \$qresult, $userinput);
 4261: 	} else {
 4262: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4263: 		    "while attempting courseiddump\n", $userinput);
 4264: 	}
 4265:     } else {
 4266: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 4267: 		"while attempting courseiddump\n", $userinput);
 4268:     }
 4269:     return 1;
 4270: }
 4271: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
 4272: 
 4273: sub course_lastaccess_handler {
 4274:     my ($cmd, $tail, $client) = @_;
 4275:     my $userinput = "$cmd:$tail";
 4276:     my ($cdom,$cnum) = split(':',$tail); 
 4277:     my (%lastaccess,$qresult);
 4278:     my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
 4279:     if ($hashref) {
 4280:         while (my ($key,$value) = each(%$hashref)) {
 4281:             my ($unesc_key,$lasttime);
 4282:             $unesc_key = &unescape($key);
 4283:             if ($cnum) {
 4284:                 next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
 4285:             }
 4286:             if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
 4287:                 $lastaccess{$1} = $value;
 4288:             } else {
 4289:                 my $items = &Apache::lonnet::thaw_unescape($value);
 4290:                 if (ref($items) eq 'HASH') {
 4291:                     unless ($lastaccess{$unesc_key}) {
 4292:                         $lastaccess{$unesc_key} = '';
 4293:                     }
 4294:                 } else {
 4295:                     my @courseitems = split(':',$value);
 4296:                     $lastaccess{$unesc_key} = pop(@courseitems);
 4297:                 }
 4298:             }
 4299:         }
 4300:         foreach my $cid (sort(keys(%lastaccess))) {
 4301:             $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&'; 
 4302:         }
 4303:         if (&untie_domain_hash($hashref)) {
 4304:             if ($qresult) {
 4305:                 chop($qresult);
 4306:             }
 4307:             &Reply($client, \$qresult, $userinput);
 4308:         } else {
 4309:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4310:                     "while attempting lastacourseaccess\n", $userinput);
 4311:         }
 4312:     } else {
 4313:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 4314:                 "while attempting lastcourseaccess\n", $userinput);
 4315:     }
 4316:     return 1;
 4317: }
 4318: &register_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
 4319: 
 4320: #
 4321: # Puts an unencrypted entry in a namespace db file at the domain level 
 4322: #
 4323: # Parameters:
 4324: #    $cmd      - The command that got us here.
 4325: #    $tail     - Tail of the command (remaining parameters).
 4326: #    $client   - File descriptor connected to client.
 4327: # Returns
 4328: #     0        - Requested to exit, caller should shut down.
 4329: #     1        - Continue processing.
 4330: #  Side effects:
 4331: #     reply is written to $client.
 4332: #
 4333: sub put_domain_handler {
 4334:     my ($cmd,$tail,$client) = @_;
 4335: 
 4336:     my $userinput = "$cmd:$tail";
 4337: 
 4338:     my ($udom,$namespace,$what) =split(/:/,$tail,3);
 4339:     chomp($what);
 4340:     my @pairs=split(/\&/,$what);
 4341:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
 4342:                                    "P", $what);
 4343:     if ($hashref) {
 4344:         foreach my $pair (@pairs) {
 4345:             my ($key,$value)=split(/=/,$pair);
 4346:             $hashref->{$key}=$value;
 4347:         }
 4348:         if (&untie_domain_hash($hashref)) {
 4349:             &Reply($client, "ok\n", $userinput);
 4350:         } else {
 4351:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4352:                      "while attempting putdom\n", $userinput);
 4353:         }
 4354:     } else {
 4355:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 4356:                   "while attempting putdom\n", $userinput);
 4357:     }
 4358: 
 4359:     return 1;
 4360: }
 4361: &register_handler("putdom", \&put_domain_handler, 0, 1, 0);
 4362: 
 4363: # Unencrypted get from the namespace database file at the domain level.
 4364: # This function retrieves a keyed item from a specific named database in the
 4365: # domain directory.
 4366: #
 4367: # Parameters:
 4368: #   $cmd             - Command request keyword (get).
 4369: #   $tail            - Tail of the command.  This is a colon separated list
 4370: #                      consisting of the domain and the 'namespace' 
 4371: #                      which selects the gdbm file to do the lookup in,
 4372: #                      & separated list of keys to lookup.  Note that
 4373: #                      the values are returned as an & separated list too.
 4374: #   $client          - File descriptor open on the client.
 4375: # Returns:
 4376: #   1       - Continue processing.
 4377: #   0       - Exit.
 4378: #  Side effects:
 4379: #     reply is written to $client.
 4380: #
 4381: 
 4382: sub get_domain_handler {
 4383:     my ($cmd, $tail, $client) = @_;
 4384: 
 4385: 
 4386:     my $userinput = "$client:$tail";
 4387: 
 4388:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
 4389:     chomp($what);
 4390:     my @queries=split(/\&/,$what);
 4391:     my $qresult='';
 4392:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
 4393:     if ($hashref) {
 4394:         for (my $i=0;$i<=$#queries;$i++) {
 4395:             $qresult.="$hashref->{$queries[$i]}&";
 4396:         }
 4397:         if (&untie_domain_hash($hashref)) {
 4398:             $qresult=~s/\&$//;
 4399:             &Reply($client, \$qresult, $userinput);
 4400:         } else {
 4401:             &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 4402:                       "while attempting getdom\n",$userinput);
 4403:         }
 4404:     } else {
 4405:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 4406:                  "while attempting getdom\n",$userinput);
 4407:     }
 4408: 
 4409:     return 1;
 4410: }
 4411: &register_handler("getdom", \&get_domain_handler, 0, 1, 0);
 4412: 
 4413: #
 4414: #  Puts an id to a domains id database. 
 4415: #
 4416: #  Parameters:
 4417: #   $cmd     - The command that triggered us.
 4418: #   $tail    - Remainder of the request other than the command. This is a 
 4419: #              colon separated list containing:
 4420: #              $domain  - The domain for which we are writing the id.
 4421: #              $pairs  - The id info to write... this is and & separated list
 4422: #                        of keyword=value.
 4423: #   $client  - Socket open on the client.
 4424: #  Returns:
 4425: #    1   - Continue processing.
 4426: #  Side effects:
 4427: #     reply is written to $client.
 4428: #
 4429: sub put_id_handler {
 4430:     my ($cmd,$tail,$client) = @_;
 4431: 
 4432: 
 4433:     my $userinput = "$cmd:$tail";
 4434: 
 4435:     my ($udom,$what)=split(/:/,$tail);
 4436:     chomp($what);
 4437:     my @pairs=split(/\&/,$what);
 4438:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
 4439: 				   "P", $what);
 4440:     if ($hashref) {
 4441: 	foreach my $pair (@pairs) {
 4442: 	    my ($key,$value)=split(/=/,$pair);
 4443: 	    $hashref->{$key}=$value;
 4444: 	}
 4445: 	if (&untie_domain_hash($hashref)) {
 4446: 	    &Reply($client, "ok\n", $userinput);
 4447: 	} else {
 4448: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4449: 		     "while attempting idput\n", $userinput);
 4450: 	}
 4451:     } else {
 4452: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 4453: 		  "while attempting idput\n", $userinput);
 4454:     }
 4455: 
 4456:     return 1;
 4457: }
 4458: &register_handler("idput", \&put_id_handler, 0, 1, 0);
 4459: 
 4460: #
 4461: #  Retrieves a set of id values from the id database.
 4462: #  Returns an & separated list of results, one for each requested id to the
 4463: #  client.
 4464: #
 4465: # Parameters:
 4466: #   $cmd       - Command keyword that caused us to be dispatched.
 4467: #   $tail      - Tail of the command.  Consists of a colon separated:
 4468: #               domain - the domain whose id table we dump
 4469: #               ids      Consists of an & separated list of
 4470: #                        id keywords whose values will be fetched.
 4471: #                        nonexisting keywords will have an empty value.
 4472: #   $client    - Socket open on the client.
 4473: #
 4474: # Returns:
 4475: #    1 - indicating processing should continue.
 4476: # Side effects:
 4477: #   An & separated list of results is written to $client.
 4478: #
 4479: sub get_id_handler {
 4480:     my ($cmd, $tail, $client) = @_;
 4481: 
 4482:     
 4483:     my $userinput = "$client:$tail";
 4484:     
 4485:     my ($udom,$what)=split(/:/,$tail);
 4486:     chomp($what);
 4487:     my @queries=split(/\&/,$what);
 4488:     my $qresult='';
 4489:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
 4490:     if ($hashref) {
 4491: 	for (my $i=0;$i<=$#queries;$i++) {
 4492: 	    $qresult.="$hashref->{$queries[$i]}&";
 4493: 	}
 4494: 	if (&untie_domain_hash($hashref)) {
 4495: 	    $qresult=~s/\&$//;
 4496: 	    &Reply($client, \$qresult, $userinput);
 4497: 	} else {
 4498: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 4499: 		      "while attempting idget\n",$userinput);
 4500: 	}
 4501:     } else {
 4502: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 4503: 		 "while attempting idget\n",$userinput);
 4504:     }
 4505:     
 4506:     return 1;
 4507: }
 4508: &register_handler("idget", \&get_id_handler, 0, 1, 0);
 4509: 
 4510: #
 4511: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
 4512: #
 4513: # Parameters
 4514: #   $cmd       - Command keyword that caused us to be dispatched.
 4515: #   $tail      - Tail of the command.  Consists of a colon separated:
 4516: #               domain - the domain whose dcmail we are recording
 4517: #               email    Consists of key=value pair 
 4518: #                        where key is unique msgid
 4519: #                        and value is message (in XML)
 4520: #   $client    - Socket open on the client.
 4521: #
 4522: # Returns:
 4523: #    1 - indicating processing should continue.
 4524: # Side effects
 4525: #     reply is written to $client.
 4526: #
 4527: sub put_dcmail_handler {
 4528:     my ($cmd,$tail,$client) = @_;
 4529:     my $userinput = "$cmd:$tail";
 4530: 
 4531: 
 4532:     my ($udom,$what)=split(/:/,$tail);
 4533:     chomp($what);
 4534:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
 4535:     if ($hashref) {
 4536:         my ($key,$value)=split(/=/,$what);
 4537:         $hashref->{$key}=$value;
 4538:     }
 4539:     if (&untie_domain_hash($hashref)) {
 4540:         &Reply($client, "ok\n", $userinput);
 4541:     } else {
 4542:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4543:                  "while attempting dcmailput\n", $userinput);
 4544:     }
 4545:     return 1;
 4546: }
 4547: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
 4548: 
 4549: #
 4550: # Retrieves broadcast e-mail from nohist_dcmail database
 4551: # Returns to client an & separated list of key=value pairs,
 4552: # where key is msgid and value is message information.
 4553: #
 4554: # Parameters
 4555: #   $cmd       - Command keyword that caused us to be dispatched.
 4556: #   $tail      - Tail of the command.  Consists of a colon separated:
 4557: #               domain - the domain whose dcmail table we dump
 4558: #               startfilter - beginning of time window 
 4559: #               endfilter - end of time window
 4560: #               sendersfilter - & separated list of username:domain 
 4561: #                 for senders to search for.
 4562: #   $client    - Socket open on the client.
 4563: #
 4564: # Returns:
 4565: #    1 - indicating processing should continue.
 4566: # Side effects
 4567: #     reply (& separated list of msgid=messageinfo pairs) is 
 4568: #     written to $client.
 4569: #
 4570: sub dump_dcmail_handler {
 4571:     my ($cmd, $tail, $client) = @_;
 4572:                                                                                 
 4573:     my $userinput = "$cmd:$tail";
 4574:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
 4575:     chomp($sendersfilter);
 4576:     my @senders = ();
 4577:     if (defined($startfilter)) {
 4578:         $startfilter=&unescape($startfilter);
 4579:     } else {
 4580:         $startfilter='.';
 4581:     }
 4582:     if (defined($endfilter)) {
 4583:         $endfilter=&unescape($endfilter);
 4584:     } else {
 4585:         $endfilter='.';
 4586:     }
 4587:     if (defined($sendersfilter)) {
 4588:         $sendersfilter=&unescape($sendersfilter);
 4589: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
 4590:     }
 4591: 
 4592:     my $qresult='';
 4593:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
 4594:     if ($hashref) {
 4595:         while (my ($key,$value) = each(%$hashref)) {
 4596:             my $match = 1;
 4597:             my ($timestamp,$subj,$uname,$udom) = 
 4598: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
 4599:             $subj = &unescape($subj);
 4600:             unless ($startfilter eq '.' || !defined($startfilter)) {
 4601:                 if ($timestamp < $startfilter) {
 4602:                     $match = 0;
 4603:                 }
 4604:             }
 4605:             unless ($endfilter eq '.' || !defined($endfilter)) {
 4606:                 if ($timestamp > $endfilter) {
 4607:                     $match = 0;
 4608:                 }
 4609:             }
 4610:             unless (@senders < 1) {
 4611:                 unless (grep/^$uname:$udom$/,@senders) {
 4612:                     $match = 0;
 4613:                 }
 4614:             }
 4615:             if ($match == 1) {
 4616:                 $qresult.=$key.'='.$value.'&';
 4617:             }
 4618:         }
 4619:         if (&untie_domain_hash($hashref)) {
 4620:             chop($qresult);
 4621:             &Reply($client, \$qresult, $userinput);
 4622:         } else {
 4623:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4624:                     "while attempting dcmaildump\n", $userinput);
 4625:         }
 4626:     } else {
 4627:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 4628:                 "while attempting dcmaildump\n", $userinput);
 4629:     }
 4630:     return 1;
 4631: }
 4632: 
 4633: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
 4634: 
 4635: #
 4636: # Puts domain roles in nohist_domainroles database
 4637: #
 4638: # Parameters
 4639: #   $cmd       - Command keyword that caused us to be dispatched.
 4640: #   $tail      - Tail of the command.  Consists of a colon separated:
 4641: #               domain - the domain whose roles we are recording  
 4642: #               role -   Consists of key=value pair
 4643: #                        where key is unique role
 4644: #                        and value is start/end date information
 4645: #   $client    - Socket open on the client.
 4646: #
 4647: # Returns:
 4648: #    1 - indicating processing should continue.
 4649: # Side effects
 4650: #     reply is written to $client.
 4651: #
 4652: 
 4653: sub put_domainroles_handler {
 4654:     my ($cmd,$tail,$client) = @_;
 4655: 
 4656:     my $userinput = "$cmd:$tail";
 4657:     my ($udom,$what)=split(/:/,$tail);
 4658:     chomp($what);
 4659:     my @pairs=split(/\&/,$what);
 4660:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
 4661:     if ($hashref) {
 4662:         foreach my $pair (@pairs) {
 4663:             my ($key,$value)=split(/=/,$pair);
 4664:             $hashref->{$key}=$value;
 4665:         }
 4666:         if (&untie_domain_hash($hashref)) {
 4667:             &Reply($client, "ok\n", $userinput);
 4668:         } else {
 4669:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4670:                      "while attempting domroleput\n", $userinput);
 4671:         }
 4672:     } else {
 4673:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 4674:                   "while attempting domroleput\n", $userinput);
 4675:     }
 4676:                                                                                   
 4677:     return 1;
 4678: }
 4679: 
 4680: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
 4681: 
 4682: #
 4683: # Retrieves domain roles from nohist_domainroles database
 4684: # Returns to client an & separated list of key=value pairs,
 4685: # where key is role and value is start and end date information.
 4686: #
 4687: # Parameters
 4688: #   $cmd       - Command keyword that caused us to be dispatched.
 4689: #   $tail      - Tail of the command.  Consists of a colon separated:
 4690: #               domain - the domain whose domain roles table we dump
 4691: #   $client    - Socket open on the client.
 4692: #
 4693: # Returns:
 4694: #    1 - indicating processing should continue.
 4695: # Side effects
 4696: #     reply (& separated list of role=start/end info pairs) is
 4697: #     written to $client.
 4698: #
 4699: sub dump_domainroles_handler {
 4700:     my ($cmd, $tail, $client) = @_;
 4701:                                                                                            
 4702:     my $userinput = "$cmd:$tail";
 4703:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
 4704:     chomp($rolesfilter);
 4705:     my @roles = ();
 4706:     if (defined($startfilter)) {
 4707:         $startfilter=&unescape($startfilter);
 4708:     } else {
 4709:         $startfilter='.';
 4710:     }
 4711:     if (defined($endfilter)) {
 4712:         $endfilter=&unescape($endfilter);
 4713:     } else {
 4714:         $endfilter='.';
 4715:     }
 4716:     if (defined($rolesfilter)) {
 4717:         $rolesfilter=&unescape($rolesfilter);
 4718: 	@roles = split(/\&/,$rolesfilter);
 4719:     }
 4720: 
 4721:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
 4722:     if ($hashref) {
 4723:         my $qresult = '';
 4724:         while (my ($key,$value) = each(%$hashref)) {
 4725:             my $match = 1;
 4726:             my ($end,$start) = split(/:/,&unescape($value));
 4727:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
 4728:             unless (@roles < 1) {
 4729:                 unless (grep/^\Q$trole\E$/,@roles) {
 4730:                     $match = 0;
 4731:                     next;
 4732:                 }
 4733:             }
 4734:             unless ($startfilter eq '.' || !defined($startfilter)) {
 4735:                 if ((defined($start)) && ($start >= $startfilter)) {
 4736:                     $match = 0;
 4737:                     next;
 4738:                 }
 4739:             }
 4740:             unless ($endfilter eq '.' || !defined($endfilter)) {
 4741:                 if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
 4742:                     $match = 0;
 4743:                     next;
 4744:                 }
 4745:             }
 4746:             if ($match == 1) {
 4747:                 $qresult.=$key.'='.$value.'&';
 4748:             }
 4749:         }
 4750:         if (&untie_domain_hash($hashref)) {
 4751:             chop($qresult);
 4752:             &Reply($client, \$qresult, $userinput);
 4753:         } else {
 4754:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4755:                     "while attempting domrolesdump\n", $userinput);
 4756:         }
 4757:     } else {
 4758:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 4759:                 "while attempting domrolesdump\n", $userinput);
 4760:     }
 4761:     return 1;
 4762: }
 4763: 
 4764: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
 4765: 
 4766: 
 4767: #  Process the tmpput command I'm not sure what this does.. Seems to
 4768: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
 4769: # where Id is the client's ip concatenated with a sequence number.
 4770: # The file will contain some value that is passed in.  Is this e.g.
 4771: # a login token?
 4772: #
 4773: # Parameters:
 4774: #    $cmd     - The command that got us dispatched.
 4775: #    $tail    - The remainder of the request following $cmd:
 4776: #               In this case this will be the contents of the file.
 4777: #    $client  - Socket connected to the client.
 4778: # Returns:
 4779: #    1 indicating processing can continue.
 4780: # Side effects:
 4781: #   A file is created in the local filesystem.
 4782: #   A reply is sent to the client.
 4783: sub tmp_put_handler {
 4784:     my ($cmd, $what, $client) = @_;
 4785: 
 4786:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
 4787: 
 4788:     my ($record,$context) = split(/:/,$what);
 4789:     if ($context ne '') {
 4790:         chomp($context);
 4791:         $context = &unescape($context);
 4792:     }
 4793:     my ($id,$store);
 4794:     $tmpsnum++;
 4795:     if (($context eq 'resetpw') || ($context eq 'createaccount')) {
 4796:         $id = &md5_hex(&md5_hex(time.{}.rand().$$));
 4797:     } else {
 4798:         $id = $$.'_'.$clientip.'_'.$tmpsnum;
 4799:     }
 4800:     $id=~s/\W/\_/g;
 4801:     $record=~s/\n//g;
 4802:     my $execdir=$perlvar{'lonDaemons'};
 4803:     if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
 4804: 	print $store $record;
 4805: 	close $store;
 4806: 	&Reply($client, \$id, $userinput);
 4807:     } else {
 4808: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
 4809: 		  "while attempting tmpput\n", $userinput);
 4810:     }
 4811:     return 1;
 4812:   
 4813: }
 4814: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
 4815: 
 4816: #   Processes the tmpget command.  This command returns the contents
 4817: #  of a temporary resource file(?) created via tmpput.
 4818: #
 4819: # Paramters:
 4820: #    $cmd      - Command that got us dispatched.
 4821: #    $id       - Tail of the command, contain the id of the resource
 4822: #                we want to fetch.
 4823: #    $client   - socket open on the client.
 4824: # Return:
 4825: #    1         - Inidcating processing can continue.
 4826: # Side effects:
 4827: #   A reply is sent to the client.
 4828: #
 4829: sub tmp_get_handler {
 4830:     my ($cmd, $id, $client) = @_;
 4831: 
 4832:     my $userinput = "$cmd:$id"; 
 4833:     
 4834: 
 4835:     $id=~s/\W/\_/g;
 4836:     my $store;
 4837:     my $execdir=$perlvar{'lonDaemons'};
 4838:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
 4839: 	my $reply=<$store>;
 4840: 	&Reply( $client, \$reply, $userinput);
 4841: 	close $store;
 4842:     } else {
 4843: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
 4844: 		  "while attempting tmpget\n", $userinput);
 4845:     }
 4846: 
 4847:     return 1;
 4848: }
 4849: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
 4850: 
 4851: #
 4852: #  Process the tmpdel command.  This command deletes a temp resource
 4853: #  created by the tmpput command.
 4854: #
 4855: # Parameters:
 4856: #   $cmd      - Command that got us here.
 4857: #   $id       - Id of the temporary resource created.
 4858: #   $client   - socket open on the client process.
 4859: #
 4860: # Returns:
 4861: #   1     - Indicating processing should continue.
 4862: # Side Effects:
 4863: #   A file is deleted
 4864: #   A reply is sent to the client.
 4865: sub tmp_del_handler {
 4866:     my ($cmd, $id, $client) = @_;
 4867:     
 4868:     my $userinput= "$cmd:$id";
 4869:     
 4870:     chomp($id);
 4871:     $id=~s/\W/\_/g;
 4872:     my $execdir=$perlvar{'lonDaemons'};
 4873:     if (unlink("$execdir/tmp/$id.tmp")) {
 4874: 	&Reply($client, "ok\n", $userinput);
 4875:     } else {
 4876: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
 4877: 		  "while attempting tmpdel\n", $userinput);
 4878:     }
 4879:     
 4880:     return 1;
 4881: 
 4882: }
 4883: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
 4884: 
 4885: #
 4886: #   Processes the setannounce command.  This command
 4887: #   creates a file named announce.txt in the top directory of
 4888: #   the documentn root and sets its contents.  The announce.txt file is
 4889: #   printed in its entirety at the LonCAPA login page.  Note:
 4890: #   once the announcement.txt fileis created it cannot be deleted.
 4891: #   However, setting the contents of the file to empty removes the
 4892: #   announcement from the login page of loncapa so who cares.
 4893: #
 4894: # Parameters:
 4895: #    $cmd          - The command that got us dispatched.
 4896: #    $announcement - The text of the announcement.
 4897: #    $client       - Socket open on the client process.
 4898: # Retunrns:
 4899: #   1             - Indicating request processing should continue
 4900: # Side Effects:
 4901: #   The file {DocRoot}/announcement.txt is created.
 4902: #   A reply is sent to $client.
 4903: #
 4904: sub set_announce_handler {
 4905:     my ($cmd, $announcement, $client) = @_;
 4906:   
 4907:     my $userinput    = "$cmd:$announcement";
 4908: 
 4909:     chomp($announcement);
 4910:     $announcement=&unescape($announcement);
 4911:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
 4912: 				'/announcement.txt')) {
 4913: 	print $store $announcement;
 4914: 	close $store;
 4915: 	&Reply($client, "ok\n", $userinput);
 4916:     } else {
 4917: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
 4918:     }
 4919: 
 4920:     return 1;
 4921: }
 4922: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
 4923: 
 4924: #
 4925: #  Return the version of the daemon.  This can be used to determine
 4926: #  the compatibility of cross version installations or, alternatively to
 4927: #  simply know who's out of date and who isn't.  Note that the version
 4928: #  is returned concatenated with the tail.
 4929: # Parameters:
 4930: #   $cmd        - the request that dispatched to us.
 4931: #   $tail       - Tail of the request (client's version?).
 4932: #   $client     - Socket open on the client.
 4933: #Returns:
 4934: #   1 - continue processing requests.
 4935: # Side Effects:
 4936: #   Replies with version to $client.
 4937: sub get_version_handler {
 4938:     my ($cmd, $tail, $client) = @_;
 4939: 
 4940:     my $userinput  = $cmd.$tail;
 4941:     
 4942:     &Reply($client, &version($userinput)."\n", $userinput);
 4943: 
 4944: 
 4945:     return 1;
 4946: }
 4947: &register_handler("version", \&get_version_handler, 0, 1, 0);
 4948: 
 4949: #  Set the current host and domain.  This is used to support
 4950: #  multihomed systems.  Each IP of the system, or even separate daemons
 4951: #  on the same IP can be treated as handling a separate lonCAPA virtual
 4952: #  machine.  This command selects the virtual lonCAPA.  The client always
 4953: #  knows the right one since it is lonc and it is selecting the domain/system
 4954: #  from the hosts.tab file.
 4955: # Parameters:
 4956: #    $cmd      - Command that dispatched us.
 4957: #    $tail     - Tail of the command (domain/host requested).
 4958: #    $socket   - Socket open on the client.
 4959: #
 4960: # Returns:
 4961: #     1   - Indicates the program should continue to process requests.
 4962: # Side-effects:
 4963: #     The default domain/system context is modified for this daemon.
 4964: #     a reply is sent to the client.
 4965: #
 4966: sub set_virtual_host_handler {
 4967:     my ($cmd, $tail, $socket) = @_;
 4968:   
 4969:     my $userinput  ="$cmd:$tail";
 4970: 
 4971:     &Reply($client, &sethost($userinput)."\n", $userinput);
 4972: 
 4973: 
 4974:     return 1;
 4975: }
 4976: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
 4977: 
 4978: #  Process a request to exit:
 4979: #   - "bye" is sent to the client.
 4980: #   - The client socket is shutdown and closed.
 4981: #   - We indicate to the caller that we should exit.
 4982: # Formal Parameters:
 4983: #   $cmd                - The command that got us here.
 4984: #   $tail               - Tail of the command (empty).
 4985: #   $client             - Socket open on the tail.
 4986: # Returns:
 4987: #   0      - Indicating the program should exit!!
 4988: #
 4989: sub exit_handler {
 4990:     my ($cmd, $tail, $client) = @_;
 4991: 
 4992:     my $userinput = "$cmd:$tail";
 4993: 
 4994:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
 4995:     &Reply($client, "bye\n", $userinput);
 4996:     $client->shutdown(2);        # shutdown the socket forcibly.
 4997:     $client->close();
 4998: 
 4999:     return 0;
 5000: }
 5001: &register_handler("exit", \&exit_handler, 0,1,1);
 5002: &register_handler("init", \&exit_handler, 0,1,1);
 5003: &register_handler("quit", \&exit_handler, 0,1,1);
 5004: 
 5005: #  Determine if auto-enrollment is enabled.
 5006: #  Note that the original had what I believe to be a defect.
 5007: #  The original returned 0 if the requestor was not a registerd client.
 5008: #  It should return "refused".
 5009: # Formal Parameters:
 5010: #   $cmd       - The command that invoked us.
 5011: #   $tail      - The tail of the command (Extra command parameters.
 5012: #   $client    - The socket open on the client that issued the request.
 5013: # Returns:
 5014: #    1         - Indicating processing should continue.
 5015: #
 5016: sub enrollment_enabled_handler {
 5017:     my ($cmd, $tail, $client) = @_;
 5018:     my $userinput = $cmd.":".$tail; # For logging purposes.
 5019: 
 5020:     
 5021:     my ($cdom) = split(/:/, $tail, 2);   # Domain we're asking about.
 5022: 
 5023:     my $outcome  = &localenroll::run($cdom);
 5024:     &Reply($client, \$outcome, $userinput);
 5025: 
 5026:     return 1;
 5027: }
 5028: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
 5029: 
 5030: #
 5031: #   Validate an institutional code used for a LON-CAPA course.          
 5032: #
 5033: # Formal Parameters:
 5034: #   $cmd          - The command request that got us dispatched.
 5035: #   $tail         - The tail of the command.  In this case,
 5036: #                   this is a colon separated set of words that will be split
 5037: #                   into:
 5038: #                        $dom      - The domain for which the check of 
 5039: #                                    institutional course code will occur.
 5040: #
 5041: #                        $instcode - The institutional code for the course
 5042: #                                    being requested, or validated for rights
 5043: #                                    to request.
 5044: #
 5045: #                        $owner    - The course requestor (who will be the
 5046: #                                    course owner, in the form username:domain
 5047: #
 5048: #   $client       - Socket open on the client.
 5049: # Returns:
 5050: #    1           - Indicating processing should continue.
 5051: #
 5052: sub validate_instcode_handler {
 5053:     my ($cmd, $tail, $client) = @_;
 5054:     my $userinput = "$cmd:$tail";
 5055:     my ($dom,$instcode,$owner) = split(/:/, $tail);
 5056:     $instcode = &unescape($instcode);
 5057:     $owner = &unescape($owner);
 5058:     my ($outcome,$description) = 
 5059:         &localenroll::validate_instcode($dom,$instcode,$owner);
 5060:     my $result = &escape($outcome).'&'.&escape($description);
 5061:     &Reply($client, \$result, $userinput);
 5062: 
 5063:     return 1;
 5064: }
 5065: &register_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
 5066: 
 5067: #   Get the official sections for which auto-enrollment is possible.
 5068: #   Since the admin people won't know about 'unofficial sections' 
 5069: #   we cannot auto-enroll on them.
 5070: # Formal Parameters:
 5071: #    $cmd     - The command request that got us dispatched here.
 5072: #    $tail    - The remainder of the request.  In our case this
 5073: #               will be split into:
 5074: #               $coursecode   - The course name from the admin point of view.
 5075: #               $cdom         - The course's domain(?).
 5076: #    $client  - Socket open on the client.
 5077: # Returns:
 5078: #    1    - Indiciting processing should continue.
 5079: #
 5080: sub get_sections_handler {
 5081:     my ($cmd, $tail, $client) = @_;
 5082:     my $userinput = "$cmd:$tail";
 5083: 
 5084:     my ($coursecode, $cdom) = split(/:/, $tail);
 5085:     my @secs = &localenroll::get_sections($coursecode,$cdom);
 5086:     my $seclist = &escape(join(':',@secs));
 5087: 
 5088:     &Reply($client, \$seclist, $userinput);
 5089:     
 5090: 
 5091:     return 1;
 5092: }
 5093: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
 5094: 
 5095: #   Validate the owner of a new course section.  
 5096: #
 5097: # Formal Parameters:
 5098: #   $cmd      - Command that got us dispatched.
 5099: #   $tail     - the remainder of the command.  For us this consists of a
 5100: #               colon separated string containing:
 5101: #                  $inst    - Course Id from the institutions point of view.
 5102: #                  $owner   - Proposed owner of the course.
 5103: #                  $cdom    - Domain of the course (from the institutions
 5104: #                             point of view?)..
 5105: #   $client   - Socket open on the client.
 5106: #
 5107: # Returns:
 5108: #   1        - Processing should continue.
 5109: #
 5110: sub validate_course_owner_handler {
 5111:     my ($cmd, $tail, $client)  = @_;
 5112:     my $userinput = "$cmd:$tail";
 5113:     my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
 5114:     
 5115:     $owner = &unescape($owner);
 5116:     $coowners = &unescape($coowners);
 5117:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
 5118:     &Reply($client, \$outcome, $userinput);
 5119: 
 5120: 
 5121: 
 5122:     return 1;
 5123: }
 5124: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
 5125: 
 5126: #
 5127: #   Validate a course section in the official schedule of classes
 5128: #   from the institutions point of view (part of autoenrollment).
 5129: #
 5130: # Formal Parameters:
 5131: #   $cmd          - The command request that got us dispatched.
 5132: #   $tail         - The tail of the command.  In this case,
 5133: #                   this is a colon separated set of words that will be split
 5134: #                   into:
 5135: #                        $inst_course_id - The course/section id from the
 5136: #                                          institutions point of view.
 5137: #                        $cdom           - The domain from the institutions
 5138: #                                          point of view.
 5139: #   $client       - Socket open on the client.
 5140: # Returns:
 5141: #    1           - Indicating processing should continue.
 5142: #
 5143: sub validate_course_section_handler {
 5144:     my ($cmd, $tail, $client) = @_;
 5145:     my $userinput = "$cmd:$tail";
 5146:     my ($inst_course_id, $cdom) = split(/:/, $tail);
 5147: 
 5148:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
 5149:     &Reply($client, \$outcome, $userinput);
 5150: 
 5151: 
 5152:     return 1;
 5153: }
 5154: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
 5155: 
 5156: #
 5157: #   Validate course owner's access to enrollment data for specific class section. 
 5158: #   
 5159: #
 5160: # Formal Parameters:
 5161: #    $cmd     - The command request that got us dispatched.
 5162: #    $tail    - The tail of the command.   In this case this is a colon separated
 5163: #               set of words that will be split into:
 5164: #               $inst_class  - Institutional code for the specific class section   
 5165: #               $courseowner - The escaped username:domain of the course owner 
 5166: #               $cdom        - The domain of the course from the institution's
 5167: #                              point of view.
 5168: #    $client  - The socket open on the client.
 5169: # Returns:
 5170: #    1 - continue processing.
 5171: #
 5172: 
 5173: sub validate_class_access_handler {
 5174:     my ($cmd, $tail, $client) = @_;
 5175:     my $userinput = "$cmd:$tail";
 5176:     my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
 5177:     my $owners = &unescape($ownerlist);
 5178:     my $outcome;
 5179:     eval {
 5180: 	local($SIG{__DIE__})='DEFAULT';
 5181: 	$outcome=&localenroll::check_section($inst_class,$owners,$cdom);
 5182:     };
 5183:     &Reply($client,\$outcome, $userinput);
 5184: 
 5185:     return 1;
 5186: }
 5187: &register_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
 5188: 
 5189: #
 5190: #   Create a password for a new LON-CAPA user added by auto-enrollment.
 5191: #   Only used for case where authentication method for new user is localauth
 5192: #
 5193: # Formal Parameters:
 5194: #    $cmd     - The command request that got us dispatched.
 5195: #    $tail    - The tail of the command.   In this case this is a colon separated
 5196: #               set of words that will be split into:
 5197: #               $authparam - An authentication parameter (localauth parameter).
 5198: #               $cdom      - The domain of the course from the institution's
 5199: #                            point of view.
 5200: #    $client  - The socket open on the client.
 5201: # Returns:
 5202: #    1 - continue processing.
 5203: #
 5204: sub create_auto_enroll_password_handler {
 5205:     my ($cmd, $tail, $client) = @_;
 5206:     my $userinput = "$cmd:$tail";
 5207: 
 5208:     my ($authparam, $cdom) = split(/:/, $userinput);
 5209: 
 5210:     my ($create_passwd,$authchk);
 5211:     ($authparam,
 5212:      $create_passwd,
 5213:      $authchk) = &localenroll::create_password($authparam,$cdom);
 5214: 
 5215:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
 5216: 	   $userinput);
 5217: 
 5218: 
 5219:     return 1;
 5220: }
 5221: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
 5222: 		  0, 1, 0);
 5223: 
 5224: #   Retrieve and remove temporary files created by/during autoenrollment.
 5225: #
 5226: # Formal Parameters:
 5227: #    $cmd      - The command that got us dispatched.
 5228: #    $tail     - The tail of the command.  In our case this is a colon 
 5229: #                separated list that will be split into:
 5230: #                $filename - The name of the file to remove.
 5231: #                            The filename is given as a path relative to
 5232: #                            the LonCAPA temp file directory.
 5233: #    $client   - Socket open on the client.
 5234: #
 5235: # Returns:
 5236: #   1     - Continue processing.
 5237: sub retrieve_auto_file_handler {
 5238:     my ($cmd, $tail, $client)    = @_;
 5239:     my $userinput                = "cmd:$tail";
 5240: 
 5241:     my ($filename)   = split(/:/, $tail);
 5242: 
 5243:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
 5244:     if ( (-e $source) && ($filename ne '') ) {
 5245: 	my $reply = '';
 5246: 	if (open(my $fh,$source)) {
 5247: 	    while (<$fh>) {
 5248: 		chomp($_);
 5249: 		$_ =~ s/^\s+//g;
 5250: 		$_ =~ s/\s+$//g;
 5251: 		$reply .= $_;
 5252: 	    }
 5253: 	    close($fh);
 5254: 	    &Reply($client, &escape($reply)."\n", $userinput);
 5255: 
 5256: #   Does this have to be uncommented??!?  (RF).
 5257: #
 5258: #                                unlink($source);
 5259: 	} else {
 5260: 	    &Failure($client, "error\n", $userinput);
 5261: 	}
 5262:     } else {
 5263: 	&Failure($client, "error\n", $userinput);
 5264:     }
 5265:     
 5266: 
 5267:     return 1;
 5268: }
 5269: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
 5270: 
 5271: sub crsreq_checks_handler {
 5272:     my ($cmd, $tail, $client) = @_;
 5273:     my $userinput = "$cmd:$tail";
 5274:     my $dom = $tail;
 5275:     my $result;
 5276:     my @reqtypes = ('official','unofficial','community');
 5277:     eval {
 5278:         local($SIG{__DIE__})='DEFAULT';
 5279:         my %validations;
 5280:         my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
 5281:                                                    \%validations);
 5282:         if ($response eq 'ok') { 
 5283:             foreach my $key (keys(%validations)) {
 5284:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
 5285:             }
 5286:             $result =~ s/\&$//;
 5287:         } else {
 5288:             $result = 'error';
 5289:         }
 5290:     };
 5291:     if (!$@) {
 5292:         &Reply($client, \$result, $userinput);
 5293:     } else {
 5294:         &Failure($client,"unknown_cmd\n",$userinput);
 5295:     }
 5296:     return 1;
 5297: }
 5298: &register_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
 5299: 
 5300: sub validate_crsreq_handler {
 5301:     my ($cmd, $tail, $client) = @_;
 5302:     my $userinput = "$cmd:$tail";
 5303:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = split(/:/, $tail);
 5304:     $instcode = &unescape($instcode);
 5305:     $owner = &unescape($owner);
 5306:     $crstype = &unescape($crstype);
 5307:     $inststatuslist = &unescape($inststatuslist);
 5308:     $instcode = &unescape($instcode);
 5309:     $instseclist = &unescape($instseclist);
 5310:     my $outcome;
 5311:     eval {
 5312:         local($SIG{__DIE__})='DEFAULT';
 5313:         $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
 5314:                                                  $inststatuslist,$instcode,
 5315:                                                  $instseclist);
 5316:     };
 5317:     if (!$@) {
 5318:         &Reply($client, \$outcome, $userinput);
 5319:     } else {
 5320:         &Failure($client,"unknown_cmd\n",$userinput);
 5321:     }
 5322:     return 1;
 5323: }
 5324: &register_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
 5325: 
 5326: #
 5327: #   Read and retrieve institutional code format (for support form).
 5328: # Formal Parameters:
 5329: #    $cmd        - Command that dispatched us.
 5330: #    $tail       - Tail of the command.  In this case it conatins 
 5331: #                  the course domain and the coursename.
 5332: #    $client     - Socket open on the client.
 5333: # Returns:
 5334: #    1     - Continue processing.
 5335: #
 5336: sub get_institutional_code_format_handler {
 5337:     my ($cmd, $tail, $client)   = @_;
 5338:     my $userinput               = "$cmd:$tail";
 5339: 
 5340:     my $reply;
 5341:     my($cdom,$course) = split(/:/,$tail);
 5342:     my @pairs = split/\&/,$course;
 5343:     my %instcodes = ();
 5344:     my %codes = ();
 5345:     my @codetitles = ();
 5346:     my %cat_titles = ();
 5347:     my %cat_order = ();
 5348:     foreach (@pairs) {
 5349: 	my ($key,$value) = split/=/,$_;
 5350: 	$instcodes{&unescape($key)} = &unescape($value);
 5351:     }
 5352:     my $formatreply = &localenroll::instcode_format($cdom,
 5353: 						    \%instcodes,
 5354: 						    \%codes,
 5355: 						    \@codetitles,
 5356: 						    \%cat_titles,
 5357: 						    \%cat_order);
 5358:     if ($formatreply eq 'ok') {
 5359: 	my $codes_str = &Apache::lonnet::hash2str(%codes);
 5360: 	my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
 5361: 	my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
 5362: 	my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
 5363: 	&Reply($client,
 5364: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
 5365: 	       .$cat_order_str."\n",
 5366: 	       $userinput);
 5367:     } else {
 5368: 	# this else branch added by RF since if not ok, lonc will
 5369: 	# hang waiting on reply until timeout.
 5370: 	#
 5371: 	&Reply($client, "format_error\n", $userinput);
 5372:     }
 5373:     
 5374:     return 1;
 5375: }
 5376: &register_handler("autoinstcodeformat",
 5377: 		  \&get_institutional_code_format_handler,0,1,0);
 5378: 
 5379: sub get_institutional_defaults_handler {
 5380:     my ($cmd, $tail, $client)   = @_;
 5381:     my $userinput               = "$cmd:$tail";
 5382: 
 5383:     my $dom = $tail;
 5384:     my %defaults_hash;
 5385:     my @code_order;
 5386:     my $outcome;
 5387:     eval {
 5388:         local($SIG{__DIE__})='DEFAULT';
 5389:         $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
 5390:                                                    \@code_order);
 5391:     };
 5392:     if (!$@) {
 5393:         if ($outcome eq 'ok') {
 5394:             my $result='';
 5395:             while (my ($key,$value) = each(%defaults_hash)) {
 5396:                 $result.=&escape($key).'='.&escape($value).'&';
 5397:             }
 5398:             $result .= 'code_order='.&escape(join('&',@code_order));
 5399:             &Reply($client,\$result,$userinput);
 5400:         } else {
 5401:             &Reply($client,"error\n", $userinput);
 5402:         }
 5403:     } else {
 5404:         &Failure($client,"unknown_cmd\n",$userinput);
 5405:     }
 5406: }
 5407: &register_handler("autoinstcodedefaults",
 5408:                   \&get_institutional_defaults_handler,0,1,0);
 5409: 
 5410: sub get_possible_instcodes_handler {
 5411:     my ($cmd, $tail, $client)   = @_;
 5412:     my $userinput               = "$cmd:$tail";
 5413: 
 5414:     my $reply;
 5415:     my $cdom = $tail;
 5416:     my (@codetitles,%cat_titles,%cat_order,@code_order);
 5417:     my $formatreply = &localenroll::possible_instcodes($cdom,
 5418:                                                        \@codetitles,
 5419:                                                        \%cat_titles,
 5420:                                                        \%cat_order,
 5421:                                                        \@code_order);
 5422:     if ($formatreply eq 'ok') {
 5423:         my $result = join('&',map {&escape($_);} (@codetitles)).':';
 5424:         $result .= join('&',map {&escape($_);} (@code_order)).':';
 5425:         foreach my $key (keys(%cat_titles)) {
 5426:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
 5427:         }
 5428:         $result =~ s/\&$//;
 5429:         $result .= ':';
 5430:         foreach my $key (keys(%cat_order)) {
 5431:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
 5432:         }
 5433:         $result =~ s/\&$//;
 5434:         &Reply($client,\$result,$userinput);
 5435:     } else {
 5436:         &Reply($client, "format_error\n", $userinput);
 5437:     }
 5438:     return 1;
 5439: }
 5440: &register_handler("autopossibleinstcodes",
 5441:                   \&get_possible_instcodes_handler,0,1,0);
 5442: 
 5443: sub get_institutional_user_rules {
 5444:     my ($cmd, $tail, $client)   = @_;
 5445:     my $userinput               = "$cmd:$tail";
 5446:     my $dom = &unescape($tail);
 5447:     my (%rules_hash,@rules_order);
 5448:     my $outcome;
 5449:     eval {
 5450:         local($SIG{__DIE__})='DEFAULT';
 5451:         $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
 5452:     };
 5453:     if (!$@) {
 5454:         if ($outcome eq 'ok') {
 5455:             my $result;
 5456:             foreach my $key (keys(%rules_hash)) {
 5457:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
 5458:             }
 5459:             $result =~ s/\&$//;
 5460:             $result .= ':';
 5461:             if (@rules_order > 0) {
 5462:                 foreach my $item (@rules_order) {
 5463:                     $result .= &escape($item).'&';
 5464:                 }
 5465:             }
 5466:             $result =~ s/\&$//;
 5467:             &Reply($client,\$result,$userinput);
 5468:         } else {
 5469:             &Reply($client,"error\n", $userinput);
 5470:         }
 5471:     } else {
 5472:         &Failure($client,"unknown_cmd\n",$userinput);
 5473:     }
 5474: }
 5475: &register_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
 5476: 
 5477: sub get_institutional_id_rules {
 5478:     my ($cmd, $tail, $client)   = @_;
 5479:     my $userinput               = "$cmd:$tail";
 5480:     my $dom = &unescape($tail);
 5481:     my (%rules_hash,@rules_order);
 5482:     my $outcome;
 5483:     eval {
 5484:         local($SIG{__DIE__})='DEFAULT';
 5485:         $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
 5486:     };
 5487:     if (!$@) {
 5488:         if ($outcome eq 'ok') {
 5489:             my $result;
 5490:             foreach my $key (keys(%rules_hash)) {
 5491:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
 5492:             }
 5493:             $result =~ s/\&$//;
 5494:             $result .= ':';
 5495:             if (@rules_order > 0) {
 5496:                 foreach my $item (@rules_order) {
 5497:                     $result .= &escape($item).'&';
 5498:                 }
 5499:             }
 5500:             $result =~ s/\&$//;
 5501:             &Reply($client,\$result,$userinput);
 5502:         } else {
 5503:             &Reply($client,"error\n", $userinput);
 5504:         }
 5505:     } else {
 5506:         &Failure($client,"unknown_cmd\n",$userinput);
 5507:     }
 5508: }
 5509: &register_handler("instidrules",\&get_institutional_id_rules,0,1,0);
 5510: 
 5511: sub get_institutional_selfcreate_rules {
 5512:     my ($cmd, $tail, $client)   = @_;
 5513:     my $userinput               = "$cmd:$tail";
 5514:     my $dom = &unescape($tail);
 5515:     my (%rules_hash,@rules_order);
 5516:     my $outcome;
 5517:     eval {
 5518:         local($SIG{__DIE__})='DEFAULT';
 5519:         $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
 5520:     };
 5521:     if (!$@) {
 5522:         if ($outcome eq 'ok') {
 5523:             my $result;
 5524:             foreach my $key (keys(%rules_hash)) {
 5525:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
 5526:             }
 5527:             $result =~ s/\&$//;
 5528:             $result .= ':';
 5529:             if (@rules_order > 0) {
 5530:                 foreach my $item (@rules_order) {
 5531:                     $result .= &escape($item).'&';
 5532:                 }
 5533:             }
 5534:             $result =~ s/\&$//;
 5535:             &Reply($client,\$result,$userinput);
 5536:         } else {
 5537:             &Reply($client,"error\n", $userinput);
 5538:         }
 5539:     } else {
 5540:         &Failure($client,"unknown_cmd\n",$userinput);
 5541:     }
 5542: }
 5543: &register_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
 5544: 
 5545: 
 5546: sub institutional_username_check {
 5547:     my ($cmd, $tail, $client)   = @_;
 5548:     my $userinput               = "$cmd:$tail";
 5549:     my %rulecheck;
 5550:     my $outcome;
 5551:     my ($udom,$uname,@rules) = split(/:/,$tail);
 5552:     $udom = &unescape($udom);
 5553:     $uname = &unescape($uname);
 5554:     @rules = map {&unescape($_);} (@rules);
 5555:     eval {
 5556:         local($SIG{__DIE__})='DEFAULT';
 5557:         $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
 5558:     };
 5559:     if (!$@) {
 5560:         if ($outcome eq 'ok') {
 5561:             my $result='';
 5562:             foreach my $key (keys(%rulecheck)) {
 5563:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
 5564:             }
 5565:             &Reply($client,\$result,$userinput);
 5566:         } else {
 5567:             &Reply($client,"error\n", $userinput);
 5568:         }
 5569:     } else {
 5570:         &Failure($client,"unknown_cmd\n",$userinput);
 5571:     }
 5572: }
 5573: &register_handler("instrulecheck",\&institutional_username_check,0,1,0);
 5574: 
 5575: sub institutional_id_check {
 5576:     my ($cmd, $tail, $client)   = @_;
 5577:     my $userinput               = "$cmd:$tail";
 5578:     my %rulecheck;
 5579:     my $outcome;
 5580:     my ($udom,$id,@rules) = split(/:/,$tail);
 5581:     $udom = &unescape($udom);
 5582:     $id = &unescape($id);
 5583:     @rules = map {&unescape($_);} (@rules);
 5584:     eval {
 5585:         local($SIG{__DIE__})='DEFAULT';
 5586:         $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
 5587:     };
 5588:     if (!$@) {
 5589:         if ($outcome eq 'ok') {
 5590:             my $result='';
 5591:             foreach my $key (keys(%rulecheck)) {
 5592:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
 5593:             }
 5594:             &Reply($client,\$result,$userinput);
 5595:         } else {
 5596:             &Reply($client,"error\n", $userinput);
 5597:         }
 5598:     } else {
 5599:         &Failure($client,"unknown_cmd\n",$userinput);
 5600:     }
 5601: }
 5602: &register_handler("instidrulecheck",\&institutional_id_check,0,1,0);
 5603: 
 5604: sub institutional_selfcreate_check {
 5605:     my ($cmd, $tail, $client)   = @_;
 5606:     my $userinput               = "$cmd:$tail";
 5607:     my %rulecheck;
 5608:     my $outcome;
 5609:     my ($udom,$email,@rules) = split(/:/,$tail);
 5610:     $udom = &unescape($udom);
 5611:     $email = &unescape($email);
 5612:     @rules = map {&unescape($_);} (@rules);
 5613:     eval {
 5614:         local($SIG{__DIE__})='DEFAULT';
 5615:         $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
 5616:     };
 5617:     if (!$@) {
 5618:         if ($outcome eq 'ok') {
 5619:             my $result='';
 5620:             foreach my $key (keys(%rulecheck)) {
 5621:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
 5622:             }
 5623:             &Reply($client,\$result,$userinput);
 5624:         } else {
 5625:             &Reply($client,"error\n", $userinput);
 5626:         }
 5627:     } else {
 5628:         &Failure($client,"unknown_cmd\n",$userinput);
 5629:     }
 5630: }
 5631: &register_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
 5632: 
 5633: # Get domain specific conditions for import of student photographs to a course
 5634: #
 5635: # Retrieves information from photo_permission subroutine in localenroll.
 5636: # Returns outcome (ok) if no processing errors, and whether course owner is 
 5637: # required to accept conditions of use (yes/no).
 5638: #
 5639: #    
 5640: sub photo_permission_handler {
 5641:     my ($cmd, $tail, $client)   = @_;
 5642:     my $userinput               = "$cmd:$tail";
 5643:     my $cdom = $tail;
 5644:     my ($perm_reqd,$conditions);
 5645:     my $outcome;
 5646:     eval {
 5647: 	local($SIG{__DIE__})='DEFAULT';
 5648: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
 5649: 						  \$conditions);
 5650:     };
 5651:     if (!$@) {
 5652: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
 5653: 	       $userinput);
 5654:     } else {
 5655: 	&Failure($client,"unknown_cmd\n",$userinput);
 5656:     }
 5657:     return 1;
 5658: }
 5659: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
 5660: 
 5661: #
 5662: # Checks if student photo is available for a user in the domain, in the user's
 5663: # directory (in /userfiles/internal/studentphoto.jpg).
 5664: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
 5665: # the student's photo.   
 5666: 
 5667: sub photo_check_handler {
 5668:     my ($cmd, $tail, $client)   = @_;
 5669:     my $userinput               = "$cmd:$tail";
 5670:     my ($udom,$uname,$pid) = split(/:/,$tail);
 5671:     $udom = &unescape($udom);
 5672:     $uname = &unescape($uname);
 5673:     $pid = &unescape($pid);
 5674:     my $path=&propath($udom,$uname).'/userfiles/internal/';
 5675:     if (!-e $path) {
 5676:         &mkpath($path);
 5677:     }
 5678:     my $response;
 5679:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
 5680:     $result .= ':'.$response;
 5681:     &Reply($client, &escape($result)."\n",$userinput);
 5682:     return 1;
 5683: }
 5684: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
 5685: 
 5686: #
 5687: # Retrieve information from localenroll about whether to provide a button     
 5688: # for users who have enbled import of student photos to initiate an 
 5689: # update of photo files for registered students. Also include 
 5690: # comment to display alongside button.  
 5691: 
 5692: sub photo_choice_handler {
 5693:     my ($cmd, $tail, $client) = @_;
 5694:     my $userinput             = "$cmd:$tail";
 5695:     my $cdom                  = &unescape($tail);
 5696:     my ($update,$comment);
 5697:     eval {
 5698: 	local($SIG{__DIE__})='DEFAULT';
 5699: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
 5700:     };
 5701:     if (!$@) {
 5702: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
 5703:     } else {
 5704: 	&Failure($client,"unknown_cmd\n",$userinput);
 5705:     }
 5706:     return 1;
 5707: }
 5708: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
 5709: 
 5710: #
 5711: # Gets a student's photo to exist (in the correct image type) in the user's 
 5712: # directory.
 5713: # Formal Parameters:
 5714: #    $cmd     - The command request that got us dispatched.
 5715: #    $tail    - A colon separated set of words that will be split into:
 5716: #               $domain - student's domain
 5717: #               $uname  - student username
 5718: #               $type   - image type desired
 5719: #    $client  - The socket open on the client.
 5720: # Returns:
 5721: #    1 - continue processing.
 5722: 
 5723: sub student_photo_handler {
 5724:     my ($cmd, $tail, $client) = @_;
 5725:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
 5726: 
 5727:     my $path=&propath($domain,$uname). '/userfiles/internal/';
 5728:     my $filename = 'studentphoto.'.$ext;
 5729:     if ($type eq 'thumbnail') {
 5730:         $filename = 'studentphoto_tn.'.$ext;
 5731:     }
 5732:     if (-e $path.$filename) {
 5733: 	&Reply($client,"ok\n","$cmd:$tail");
 5734: 	return 1;
 5735:     }
 5736:     &mkpath($path);
 5737:     my $file;
 5738:     if ($type eq 'thumbnail') {
 5739: 	eval {
 5740: 	    local($SIG{__DIE__})='DEFAULT';
 5741: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
 5742: 	};
 5743:     } else {
 5744:         $file=&localstudentphoto::fetch($domain,$uname);
 5745:     }
 5746:     if (!$file) {
 5747: 	&Failure($client,"unavailable\n","$cmd:$tail");
 5748: 	return 1;
 5749:     }
 5750:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
 5751:     if (-e $path.$filename) {
 5752: 	&Reply($client,"ok\n","$cmd:$tail");
 5753: 	return 1;
 5754:     }
 5755:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
 5756:     return 1;
 5757: }
 5758: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
 5759: 
 5760: sub inst_usertypes_handler {
 5761:     my ($cmd, $domain, $client) = @_;
 5762:     my $res;
 5763:     my $userinput = $cmd.":".$domain; # For logging purposes.
 5764:     my (%typeshash,@order,$result);
 5765:     eval {
 5766: 	local($SIG{__DIE__})='DEFAULT';
 5767: 	$result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
 5768:     };
 5769:     if ($result eq 'ok') {
 5770:         if (keys(%typeshash) > 0) {
 5771:             foreach my $key (keys(%typeshash)) {
 5772:                 $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
 5773:             }
 5774:         }
 5775:         $res=~s/\&$//;
 5776:         $res .= ':';
 5777:         if (@order > 0) {
 5778:             foreach my $item (@order) {
 5779:                 $res .= &escape($item).'&';
 5780:             }
 5781:         }
 5782:         $res=~s/\&$//;
 5783:     }
 5784:     &Reply($client, \$res, $userinput);
 5785:     return 1;
 5786: }
 5787: &register_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
 5788: 
 5789: # mkpath makes all directories for a file, expects an absolute path with a
 5790: # file or a trailing / if just a dir is passed
 5791: # returns 1 on success 0 on failure
 5792: sub mkpath {
 5793:     my ($file)=@_;
 5794:     my @parts=split(/\//,$file,-1);
 5795:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
 5796:     for (my $i=3;$i<= ($#parts-1);$i++) {
 5797: 	$now.='/'.$parts[$i]; 
 5798: 	if (!-e $now) {
 5799: 	    if  (!mkdir($now,0770)) { return 0; }
 5800: 	}
 5801:     }
 5802:     return 1;
 5803: }
 5804: 
 5805: #---------------------------------------------------------------
 5806: #
 5807: #   Getting, decoding and dispatching requests:
 5808: #
 5809: #
 5810: #   Get a Request:
 5811: #   Gets a Request message from the client.  The transaction
 5812: #   is defined as a 'line' of text.  We remove the new line
 5813: #   from the text line.  
 5814: #
 5815: sub get_request {
 5816:     my $input = <$client>;
 5817:     chomp($input);
 5818: 
 5819:     &Debug("get_request: Request = $input\n");
 5820: 
 5821:     &status('Processing '.$clientname.':'.$input);
 5822: 
 5823:     return $input;
 5824: }
 5825: #---------------------------------------------------------------
 5826: #
 5827: #  Process a request.  This sub should shrink as each action
 5828: #  gets farmed out into a separat sub that is registered 
 5829: #  with the dispatch hash.  
 5830: #
 5831: # Parameters:
 5832: #    user_input   - The request received from the client (lonc).
 5833: # Returns:
 5834: #    true to keep processing, false if caller should exit.
 5835: #
 5836: sub process_request {
 5837:     my ($userinput) = @_;      # Easier for now to break style than to
 5838:                                 # fix all the userinput -> user_input.
 5839:     my $wasenc    = 0;		# True if request was encrypted.
 5840: # ------------------------------------------------------------ See if encrypted
 5841:     # for command
 5842:     # sethost:<server>
 5843:     # <command>:<args>
 5844:     #   we just send it to the processor
 5845:     # for
 5846:     # sethost:<server>:<command>:<args>
 5847:     #  we do the implict set host and then do the command
 5848:     if ($userinput =~ /^sethost:/) {
 5849: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
 5850: 	if (defined($userinput)) {
 5851: 	    &sethost("$cmd:$newid");
 5852: 	} else {
 5853: 	    $userinput = "$cmd:$newid";
 5854: 	}
 5855:     }
 5856: 
 5857:     if ($userinput =~ /^enc/) {
 5858: 	$userinput = decipher($userinput);
 5859: 	$wasenc=1;
 5860: 	if(!$userinput) {	# Cipher not defined.
 5861: 	    &Failure($client, "error: Encrypted data without negotated key\n");
 5862: 	    return 0;
 5863: 	}
 5864:     }
 5865:     Debug("process_request: $userinput\n");
 5866:     
 5867:     #  
 5868:     #   The 'correct way' to add a command to lond is now to
 5869:     #   write a sub to execute it and Add it to the command dispatch
 5870:     #   hash via a call to register_handler..  The comments to that
 5871:     #   sub should give you enough to go on to show how to do this
 5872:     #   along with the examples that are building up as this code
 5873:     #   is getting refactored.   Until all branches of the
 5874:     #   if/elseif monster below have been factored out into
 5875:     #   separate procesor subs, if the dispatch hash is missing
 5876:     #   the command keyword, we will fall through to the remainder
 5877:     #   of the if/else chain below in order to keep this thing in 
 5878:     #   working order throughout the transmogrification.
 5879: 
 5880:     my ($command, $tail) = split(/:/, $userinput, 2);
 5881:     chomp($command);
 5882:     chomp($tail);
 5883:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
 5884:     $command =~ s/(\r)//;	# And this too for parameterless commands.
 5885:     if(!$tail) {
 5886: 	$tail ="";		# defined but blank.
 5887:     }
 5888: 
 5889:     &Debug("Command received: $command, encoded = $wasenc");
 5890: 
 5891:     if(defined $Dispatcher{$command}) {
 5892: 
 5893: 	my $dispatch_info = $Dispatcher{$command};
 5894: 	my $handler       = $$dispatch_info[0];
 5895: 	my $need_encode   = $$dispatch_info[1];
 5896: 	my $client_types  = $$dispatch_info[2];
 5897: 	Debug("Matched dispatch hash: mustencode: $need_encode "
 5898: 	      ."ClientType $client_types");
 5899:       
 5900: 	#  Validate the request:
 5901:       
 5902: 	my $ok = 1;
 5903: 	my $requesterprivs = 0;
 5904: 	if(&isClient()) {
 5905: 	    $requesterprivs |= $CLIENT_OK;
 5906: 	}
 5907: 	if(&isManager()) {
 5908: 	    $requesterprivs |= $MANAGER_OK;
 5909: 	}
 5910: 	if($need_encode && (!$wasenc)) {
 5911: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
 5912: 	    $ok = 0;
 5913: 	}
 5914: 	if(($client_types & $requesterprivs) == 0) {
 5915: 	    Debug("Client not privileged to do this operation");
 5916: 	    $ok = 0;
 5917: 	}
 5918: 
 5919: 	if($ok) {
 5920: 	    Debug("Dispatching to handler $command $tail");
 5921: 	    my $keep_going = &$handler($command, $tail, $client);
 5922: 	    return $keep_going;
 5923: 	} else {
 5924: 	    Debug("Refusing to dispatch because client did not match requirements");
 5925: 	    Failure($client, "refused\n", $userinput);
 5926: 	    return 1;
 5927: 	}
 5928: 
 5929:     }    
 5930: 
 5931:     print $client "unknown_cmd\n";
 5932: # -------------------------------------------------------------------- complete
 5933:     Debug("process_request - returning 1");
 5934:     return 1;
 5935: }
 5936: #
 5937: #   Decipher encoded traffic
 5938: #  Parameters:
 5939: #     input      - Encoded data.
 5940: #  Returns:
 5941: #     Decoded data or undef if encryption key was not yet negotiated.
 5942: #  Implicit input:
 5943: #     cipher  - This global holds the negotiated encryption key.
 5944: #
 5945: sub decipher {
 5946:     my ($input)  = @_;
 5947:     my $output = '';
 5948:     
 5949:     
 5950:     if($cipher) {
 5951: 	my($enc, $enclength, $encinput) = split(/:/, $input);
 5952: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
 5953: 	    $output .= 
 5954: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
 5955: 	}
 5956: 	return substr($output, 0, $enclength);
 5957:     } else {
 5958: 	return undef;
 5959:     }
 5960: }
 5961: 
 5962: #
 5963: #   Register a command processor.  This function is invoked to register a sub
 5964: #   to process a request.  Once registered, the ProcessRequest sub can automatically
 5965: #   dispatch requests to an appropriate sub, and do the top level validity checking
 5966: #   as well:
 5967: #    - Is the keyword recognized.
 5968: #    - Is the proper client type attempting the request.
 5969: #    - Is the request encrypted if it has to be.
 5970: #   Parameters:
 5971: #    $request_name         - Name of the request being registered.
 5972: #                           This is the command request that will match
 5973: #                           against the hash keywords to lookup the information
 5974: #                           associated with the dispatch information.
 5975: #    $procedure           - Reference to a sub to call to process the request.
 5976: #                           All subs get called as follows:
 5977: #                             Procedure($cmd, $tail, $replyfd, $key)
 5978: #                             $cmd    - the actual keyword that invoked us.
 5979: #                             $tail   - the tail of the request that invoked us.
 5980: #                             $replyfd- File descriptor connected to the client
 5981: #    $must_encode          - True if the request must be encoded to be good.
 5982: #    $client_ok            - True if it's ok for a client to request this.
 5983: #    $manager_ok           - True if it's ok for a manager to request this.
 5984: # Side effects:
 5985: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
 5986: #      - On failure, the program will die as it's a bad internal bug to try to 
 5987: #        register a duplicate command handler.
 5988: #
 5989: sub register_handler {
 5990:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
 5991: 
 5992:     #  Don't allow duplication#
 5993:    
 5994:     if (defined $Dispatcher{$request_name}) {
 5995: 	die "Attempting to define a duplicate request handler for $request_name\n";
 5996:     }
 5997:     #   Build the client type mask:
 5998:     
 5999:     my $client_type_mask = 0;
 6000:     if($client_ok) {
 6001: 	$client_type_mask  |= $CLIENT_OK;
 6002:     }
 6003:     if($manager_ok) {
 6004: 	$client_type_mask  |= $MANAGER_OK;
 6005:     }
 6006:    
 6007:     #  Enter the hash:
 6008:       
 6009:     my @entry = ($procedure, $must_encode, $client_type_mask);
 6010:    
 6011:     $Dispatcher{$request_name} = \@entry;
 6012:    
 6013: }
 6014: 
 6015: 
 6016: #------------------------------------------------------------------
 6017: 
 6018: 
 6019: 
 6020: 
 6021: #
 6022: #  Convert an error return code from lcpasswd to a string value.
 6023: #
 6024: sub lcpasswdstrerror {
 6025:     my $ErrorCode = shift;
 6026:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
 6027: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
 6028:     } else {
 6029: 	return $passwderrors[$ErrorCode];
 6030:     }
 6031: }
 6032: 
 6033: #
 6034: # Convert an error return code from lcuseradd to a string value:
 6035: #
 6036: sub lcuseraddstrerror {
 6037:     my $ErrorCode = shift;
 6038:     if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
 6039: 	return "lcuseradd - Unrecognized error code: ".$ErrorCode;
 6040:     } else {
 6041: 	return $adderrors[$ErrorCode];
 6042:     }
 6043: }
 6044: 
 6045: # grabs exception and records it to log before exiting
 6046: sub catchexception {
 6047:     my ($error)=@_;
 6048:     $SIG{'QUIT'}='DEFAULT';
 6049:     $SIG{__DIE__}='DEFAULT';
 6050:     &status("Catching exception");
 6051:     &logthis("<font color='red'>CRITICAL: "
 6052:      ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
 6053:      ."a crash with this error msg->[$error]</font>");
 6054:     &logthis('Famous last words: '.$status.' - '.$lastlog);
 6055:     if ($client) { print $client "error: $error\n"; }
 6056:     $server->close();
 6057:     die($error);
 6058: }
 6059: sub timeout {
 6060:     &status("Handling Timeout");
 6061:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
 6062:     &catchexception('Timeout');
 6063: }
 6064: # -------------------------------- Set signal handlers to record abnormal exits
 6065: 
 6066: 
 6067: $SIG{'QUIT'}=\&catchexception;
 6068: $SIG{__DIE__}=\&catchexception;
 6069: 
 6070: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
 6071: &status("Read loncapa.conf and loncapa_apache.conf");
 6072: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
 6073: %perlvar=%{$perlvarref};
 6074: undef $perlvarref;
 6075: 
 6076: # ----------------------------- Make sure this process is running from user=www
 6077: my $wwwid=getpwnam('www');
 6078: if ($wwwid!=$<) {
 6079:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
 6080:    my $subj="LON: $currenthostid User ID mismatch";
 6081:    system("echo 'User ID mismatch.  lond must be run as user www.' |\
 6082:  mailto $emailto -s '$subj' > /dev/null");
 6083:    exit 1;
 6084: }
 6085: 
 6086: # --------------------------------------------- Check if other instance running
 6087: 
 6088: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
 6089: 
 6090: if (-e $pidfile) {
 6091:    my $lfh=IO::File->new("$pidfile");
 6092:    my $pide=<$lfh>;
 6093:    chomp($pide);
 6094:    if (kill 0 => $pide) { die "already running"; }
 6095: }
 6096: 
 6097: # ------------------------------------------------------------- Read hosts file
 6098: 
 6099: 
 6100: 
 6101: # establish SERVER socket, bind and listen.
 6102: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
 6103:                                 Type      => SOCK_STREAM,
 6104:                                 Proto     => 'tcp',
 6105:                                 ReuseAddr     => 1,
 6106:                                 Listen    => 10 )
 6107:   or die "making socket: $@\n";
 6108: 
 6109: # --------------------------------------------------------- Do global variables
 6110: 
 6111: # global variables
 6112: 
 6113: my %children               = ();       # keys are current child process IDs
 6114: 
 6115: sub REAPER {                        # takes care of dead children
 6116:     $SIG{CHLD} = \&REAPER;
 6117:     &status("Handling child death");
 6118:     my $pid;
 6119:     do {
 6120: 	$pid = waitpid(-1,&WNOHANG());
 6121: 	if (defined($children{$pid})) {
 6122: 	    &logthis("Child $pid died");
 6123: 	    delete($children{$pid});
 6124: 	} elsif ($pid > 0) {
 6125: 	    &logthis("Unknown Child $pid died");
 6126: 	}
 6127:     } while ( $pid > 0 );
 6128:     foreach my $child (keys(%children)) {
 6129: 	$pid = waitpid($child,&WNOHANG());
 6130: 	if ($pid > 0) {
 6131: 	    &logthis("Child $child - $pid looks like we missed it's death");
 6132: 	    delete($children{$pid});
 6133: 	}
 6134:     }
 6135:     &status("Finished Handling child death");
 6136: }
 6137: 
 6138: sub HUNTSMAN {                      # signal handler for SIGINT
 6139:     &status("Killing children (INT)");
 6140:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
 6141:     kill 'INT' => keys %children;
 6142:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
 6143:     my $execdir=$perlvar{'lonDaemons'};
 6144:     unlink("$execdir/logs/lond.pid");
 6145:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
 6146:     &status("Done killing children");
 6147:     exit;                           # clean up with dignity
 6148: }
 6149: 
 6150: sub HUPSMAN {                      # signal handler for SIGHUP
 6151:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
 6152:     &status("Killing children for restart (HUP)");
 6153:     kill 'INT' => keys %children;
 6154:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
 6155:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
 6156:     my $execdir=$perlvar{'lonDaemons'};
 6157:     unlink("$execdir/logs/lond.pid");
 6158:     &status("Restarting self (HUP)");
 6159:     exec("$execdir/lond");         # here we go again
 6160: }
 6161: 
 6162: #
 6163: #  Reload the Apache daemon's state.
 6164: #  This is done by invoking /home/httpd/perl/apachereload
 6165: #  a setuid perl script that can be root for us to do this job.
 6166: #
 6167: sub ReloadApache {
 6168: # --------------------------- Handle case of another apachereload process (locking)
 6169:     if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
 6170:         my $execdir = $perlvar{'lonDaemons'};
 6171:         my $script  = $execdir."/apachereload";
 6172:         system($script);
 6173:         unlink('/tmp/lock_apachereload'); #  Remove the lock file.
 6174:     }
 6175: }
 6176: 
 6177: #
 6178: #   Called in response to a USR2 signal.
 6179: #   - Reread hosts.tab
 6180: #   - All children connected to hosts that were removed from hosts.tab
 6181: #     are killed via SIGINT
 6182: #   - All children connected to previously existing hosts are sent SIGUSR1
 6183: #   - Our internal hosts hash is updated to reflect the new contents of
 6184: #     hosts.tab causing connections from hosts added to hosts.tab to
 6185: #     now be honored.
 6186: #
 6187: sub UpdateHosts {
 6188:     &status("Reload hosts.tab");
 6189:     logthis('<font color="blue"> Updating connections </font>');
 6190:     #
 6191:     #  The %children hash has the set of IP's we currently have children
 6192:     #  on.  These need to be matched against records in the hosts.tab
 6193:     #  Any ip's no longer in the table get killed off they correspond to
 6194:     #  either dropped or changed hosts.  Note that the re-read of the table
 6195:     #  will take care of new and changed hosts as connections come into being.
 6196: 
 6197:     &Apache::lonnet::reset_hosts_info();
 6198: 
 6199:     foreach my $child (keys(%children)) {
 6200: 	my $childip = $children{$child};
 6201: 	if ($childip ne '127.0.0.1'
 6202: 	    && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
 6203: 	    logthis('<font color="blue"> UpdateHosts killing child '
 6204: 		    ." $child for ip $childip </font>");
 6205: 	    kill('INT', $child);
 6206: 	} else {
 6207: 	    logthis('<font color="green"> keeping child for ip '
 6208: 		    ." $childip (pid=$child) </font>");
 6209: 	}
 6210:     }
 6211:     ReloadApache;
 6212:     &status("Finished reloading hosts.tab");
 6213: }
 6214: 
 6215: 
 6216: sub checkchildren {
 6217:     &status("Checking on the children (sending signals)");
 6218:     &initnewstatus();
 6219:     &logstatus();
 6220:     &logthis('Going to check on the children');
 6221:     my $docdir=$perlvar{'lonDocRoot'};
 6222:     foreach (sort keys %children) {
 6223: 	#sleep 1;
 6224:         unless (kill 'USR1' => $_) {
 6225: 	    &logthis ('Child '.$_.' is dead');
 6226:             &logstatus($$.' is dead');
 6227: 	    delete($children{$_});
 6228:         } 
 6229:     }
 6230:     sleep 5;
 6231:     $SIG{ALRM} = sub { Debug("timeout"); 
 6232: 		       die "timeout";  };
 6233:     $SIG{__DIE__} = 'DEFAULT';
 6234:     &status("Checking on the children (waiting for reports)");
 6235:     foreach (sort keys %children) {
 6236:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
 6237:           eval {
 6238:             alarm(300);
 6239: 	    &logthis('Child '.$_.' did not respond');
 6240: 	    kill 9 => $_;
 6241: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
 6242: 	    #$subj="LON: $currenthostid killed lond process $_";
 6243: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
 6244: 	    #$execdir=$perlvar{'lonDaemons'};
 6245: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
 6246: 	    delete($children{$_});
 6247: 	    alarm(0);
 6248: 	  }
 6249:         }
 6250:     }
 6251:     $SIG{ALRM} = 'DEFAULT';
 6252:     $SIG{__DIE__} = \&catchexception;
 6253:     &status("Finished checking children");
 6254:     &logthis('Finished Checking children');
 6255: }
 6256: 
 6257: # --------------------------------------------------------------------- Logging
 6258: 
 6259: sub logthis {
 6260:     my $message=shift;
 6261:     my $execdir=$perlvar{'lonDaemons'};
 6262:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
 6263:     my $now=time;
 6264:     my $local=localtime($now);
 6265:     $lastlog=$local.': '.$message;
 6266:     print $fh "$local ($$): $message\n";
 6267: }
 6268: 
 6269: # ------------------------- Conditional log if $DEBUG true.
 6270: sub Debug {
 6271:     my $message = shift;
 6272:     if($DEBUG) {
 6273: 	&logthis($message);
 6274:     }
 6275: }
 6276: 
 6277: #
 6278: #   Sub to do replies to client.. this gives a hook for some
 6279: #   debug tracing too:
 6280: #  Parameters:
 6281: #     fd      - File open on client.
 6282: #     reply   - Text to send to client.
 6283: #     request - Original request from client.
 6284: #
 6285: sub Reply {
 6286:     my ($fd, $reply, $request) = @_;
 6287:     if (ref($reply)) {
 6288: 	print $fd $$reply;
 6289: 	print $fd "\n";
 6290: 	if ($DEBUG) { Debug("Request was $request  Reply was $$reply"); }
 6291:     } else {
 6292: 	print $fd $reply;
 6293: 	if ($DEBUG) { Debug("Request was $request  Reply was $reply"); }
 6294:     }
 6295:     $Transactions++;
 6296: }
 6297: 
 6298: 
 6299: #
 6300: #    Sub to report a failure.
 6301: #    This function:
 6302: #     -   Increments the failure statistic counters.
 6303: #     -   Invokes Reply to send the error message to the client.
 6304: # Parameters:
 6305: #    fd       - File descriptor open on the client
 6306: #    reply    - Reply text to emit.
 6307: #    request  - The original request message (used by Reply
 6308: #               to debug if that's enabled.
 6309: # Implicit outputs:
 6310: #    $Failures- The number of failures is incremented.
 6311: #    Reply (invoked here) sends a message to the 
 6312: #    client:
 6313: #
 6314: sub Failure {
 6315:     my $fd      = shift;
 6316:     my $reply   = shift;
 6317:     my $request = shift;
 6318:    
 6319:     $Failures++;
 6320:     Reply($fd, $reply, $request);      # That's simple eh?
 6321: }
 6322: # ------------------------------------------------------------------ Log status
 6323: 
 6324: sub logstatus {
 6325:     &status("Doing logging");
 6326:     my $docdir=$perlvar{'lonDocRoot'};
 6327:     {
 6328: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
 6329:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
 6330:         $fh->close();
 6331:     }
 6332:     &status("Finished $$.txt");
 6333:     {
 6334: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
 6335: 	flock(LOG,LOCK_EX);
 6336: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
 6337: 	    .$status."\t".$lastlog."\t $keymode\n";
 6338: 	flock(LOG,LOCK_UN);
 6339: 	close(LOG);
 6340:     }
 6341:     &status("Finished logging");
 6342: }
 6343: 
 6344: sub initnewstatus {
 6345:     my $docdir=$perlvar{'lonDocRoot'};
 6346:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
 6347:     my $now=time();
 6348:     my $local=localtime($now);
 6349:     print $fh "LOND status $local - parent $$\n\n";
 6350:     opendir(DIR,"$docdir/lon-status/londchld");
 6351:     while (my $filename=readdir(DIR)) {
 6352:         unlink("$docdir/lon-status/londchld/$filename");
 6353:     }
 6354:     closedir(DIR);
 6355: }
 6356: 
 6357: # -------------------------------------------------------------- Status setting
 6358: 
 6359: sub status {
 6360:     my $what=shift;
 6361:     my $now=time;
 6362:     my $local=localtime($now);
 6363:     $status=$local.': '.$what;
 6364:     $0='lond: '.$what.' '.$local;
 6365: }
 6366: 
 6367: # -------------------------------------------------------------- Talk to lonsql
 6368: 
 6369: sub sql_reply {
 6370:     my ($cmd)=@_;
 6371:     my $answer=&sub_sql_reply($cmd);
 6372:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
 6373:     return $answer;
 6374: }
 6375: 
 6376: sub sub_sql_reply {
 6377:     my ($cmd)=@_;
 6378:     my $unixsock="mysqlsock";
 6379:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
 6380:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
 6381:                                       Type    => SOCK_STREAM,
 6382:                                       Timeout => 10)
 6383:        or return "con_lost";
 6384:     print $sclient "$cmd:$currentdomainid\n";
 6385:     my $answer=<$sclient>;
 6386:     chomp($answer);
 6387:     if (!$answer) { $answer="con_lost"; }
 6388:     return $answer;
 6389: }
 6390: 
 6391: # --------------------------------------- Is this the home server of an author?
 6392: 
 6393: sub ishome {
 6394:     my $author=shift;
 6395:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 6396:     my ($udom,$uname)=split(/\//,$author);
 6397:     my $proname=propath($udom,$uname);
 6398:     if (-e $proname) {
 6399: 	return 'owner';
 6400:     } else {
 6401:         return 'not_owner';
 6402:     }
 6403: }
 6404: 
 6405: # ======================================================= Continue main program
 6406: # ---------------------------------------------------- Fork once and dissociate
 6407: 
 6408: my $fpid=fork;
 6409: exit if $fpid;
 6410: die "Couldn't fork: $!" unless defined ($fpid);
 6411: 
 6412: POSIX::setsid() or die "Can't start new session: $!";
 6413: 
 6414: # ------------------------------------------------------- Write our PID on disk
 6415: 
 6416: my $execdir=$perlvar{'lonDaemons'};
 6417: open (PIDSAVE,">$execdir/logs/lond.pid");
 6418: print PIDSAVE "$$\n";
 6419: close(PIDSAVE);
 6420: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
 6421: &status('Starting');
 6422: 
 6423: 
 6424: 
 6425: # ----------------------------------------------------- Install signal handlers
 6426: 
 6427: 
 6428: $SIG{CHLD} = \&REAPER;
 6429: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 6430: $SIG{HUP}  = \&HUPSMAN;
 6431: $SIG{USR1} = \&checkchildren;
 6432: $SIG{USR2} = \&UpdateHosts;
 6433: 
 6434: #  Read the host hashes:
 6435: &Apache::lonnet::load_hosts_tab();
 6436: my %iphost = &Apache::lonnet::get_iphost(1);
 6437: 
 6438: $dist=`$perlvar{'lonDaemons'}/distprobe`;
 6439: 
 6440: my $arch = `uname -i`;
 6441: chomp($arch);
 6442: if ($arch eq 'unknown') {
 6443:     $arch = `uname -m`;
 6444:     chomp($arch);
 6445: }
 6446: 
 6447: # --------------------------------------------------------------
 6448: #   Accept connections.  When a connection comes in, it is validated
 6449: #   and if good, a child process is created to process transactions
 6450: #   along the connection.
 6451: 
 6452: while (1) {
 6453:     &status('Starting accept');
 6454:     $client = $server->accept() or next;
 6455:     &status('Accepted '.$client.' off to spawn');
 6456:     make_new_child($client);
 6457:     &status('Finished spawning');
 6458: }
 6459: 
 6460: sub make_new_child {
 6461:     my $pid;
 6462: #    my $cipher;     # Now global
 6463:     my $sigset;
 6464: 
 6465:     $client = shift;
 6466:     &status('Starting new child '.$client);
 6467:     &logthis('<font color="green"> Attempting to start child ('.$client.
 6468: 	     ")</font>");    
 6469:     # block signal for fork
 6470:     $sigset = POSIX::SigSet->new(SIGINT);
 6471:     sigprocmask(SIG_BLOCK, $sigset)
 6472:         or die "Can't block SIGINT for fork: $!\n";
 6473: 
 6474:     die "fork: $!" unless defined ($pid = fork);
 6475: 
 6476:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
 6477: 	                               # connection liveness.
 6478: 
 6479:     #
 6480:     #  Figure out who we're talking to so we can record the peer in 
 6481:     #  the pid hash.
 6482:     #
 6483:     my $caller = getpeername($client);
 6484:     my ($port,$iaddr);
 6485:     if (defined($caller) && length($caller) > 0) {
 6486: 	($port,$iaddr)=unpack_sockaddr_in($caller);
 6487:     } else {
 6488: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
 6489:     }
 6490:     if (defined($iaddr)) {
 6491: 	$clientip  = inet_ntoa($iaddr);
 6492: 	Debug("Connected with $clientip");
 6493:     } else {
 6494: 	&logthis("Unable to determine clientip");
 6495: 	$clientip='Unavailable';
 6496:     }
 6497:     
 6498:     if ($pid) {
 6499:         # Parent records the child's birth and returns.
 6500:         sigprocmask(SIG_UNBLOCK, $sigset)
 6501:             or die "Can't unblock SIGINT for fork: $!\n";
 6502:         $children{$pid} = $clientip;
 6503:         &status('Started child '.$pid);
 6504: 	close($client);
 6505:         return;
 6506:     } else {
 6507:         # Child can *not* return from this subroutine.
 6508:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
 6509:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
 6510:                                 #don't get intercepted
 6511:         $SIG{USR1}= \&logstatus;
 6512:         $SIG{ALRM}= \&timeout;
 6513: 	#
 6514: 	# Block sigpipe as it gets thrownon socket disconnect and we want to 
 6515: 	# deal with that as a read faiure instead.
 6516: 	#
 6517: 	my $blockset = POSIX::SigSet->new(SIGPIPE);
 6518: 	sigprocmask(SIG_BLOCK, $blockset);
 6519: 
 6520:         $lastlog='Forked ';
 6521:         $status='Forked';
 6522: 
 6523:         # unblock signals
 6524:         sigprocmask(SIG_UNBLOCK, $sigset)
 6525:             or die "Can't unblock SIGINT for fork: $!\n";
 6526: 
 6527: #        my $tmpsnum=0;            # Now global
 6528: #---------------------------------------------------- kerberos 5 initialization
 6529:         &Authen::Krb5::init_context();
 6530: 	unless (($dist eq 'fedora5') || ($dist eq 'fedora4') ||  
 6531: 		($dist eq 'fedora6') || ($dist eq 'suse9.3')) {
 6532: 	    &Authen::Krb5::init_ets();
 6533: 	}
 6534: 
 6535: 	&status('Accepted connection');
 6536: # =============================================================================
 6537:             # do something with the connection
 6538: # -----------------------------------------------------------------------------
 6539: 	# see if we know client and 'check' for spoof IP by ineffective challenge
 6540: 
 6541: 	my $outsideip=$clientip;
 6542: 	if ($clientip eq '127.0.0.1') {
 6543: 	    $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
 6544: 	}
 6545: 	&ReadManagerTable();
 6546: 	my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
 6547: 	my $ismanager=($managers{$outsideip}    ne undef);
 6548: 	$clientname  = "[unknown]";
 6549: 	if($clientrec) {	# Establish client type.
 6550: 	    $ConnectionType = "client";
 6551: 	    $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
 6552: 	    if($ismanager) {
 6553: 		$ConnectionType = "both";
 6554: 	    }
 6555: 	} else {
 6556: 	    $ConnectionType = "manager";
 6557: 	    $clientname = $managers{$outsideip};
 6558: 	}
 6559: 	my $clientok;
 6560: 
 6561: 	if ($clientrec || $ismanager) {
 6562: 	    &status("Waiting for init from $clientip $clientname");
 6563: 	    &logthis('<font color="yellow">INFO: Connection, '.
 6564: 		     $clientip.
 6565: 		  " ($clientname) connection type = $ConnectionType </font>" );
 6566: 	    &status("Connecting $clientip  ($clientname))"); 
 6567: 	    my $remotereq=<$client>;
 6568: 	    chomp($remotereq);
 6569: 	    Debug("Got init: $remotereq");
 6570: 
 6571: 	    if ($remotereq =~ /^init/) {
 6572: 		&sethost("sethost:$perlvar{'lonHostID'}");
 6573: 		#
 6574: 		#  If the remote is attempting a local init... give that a try:
 6575: 		#
 6576: 		(my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
 6577: 
 6578: 		# If the connection type is ssl, but I didn't get my
 6579: 		# certificate files yet, then I'll drop  back to 
 6580: 		# insecure (if allowed).
 6581: 		
 6582: 		if($inittype eq "ssl") {
 6583: 		    my ($ca, $cert) = lonssl::CertificateFile;
 6584: 		    my $kfile       = lonssl::KeyFile;
 6585: 		    if((!$ca)   || 
 6586: 		       (!$cert) || 
 6587: 		       (!$kfile)) {
 6588: 			$inittype = ""; # This forces insecure attempt.
 6589: 			&logthis("<font color=\"blue\"> Certificates not "
 6590: 				 ."installed -- trying insecure auth</font>");
 6591: 		    } else {	# SSL certificates are in place so
 6592: 		    }		# Leave the inittype alone.
 6593: 		}
 6594: 
 6595: 		if($inittype eq "local") {
 6596:                     $clientversion = $perlvar{'lonVersion'};
 6597: 		    my $key = LocalConnection($client, $remotereq);
 6598: 		    if($key) {
 6599: 			Debug("Got local key $key");
 6600: 			$clientok     = 1;
 6601: 			my $cipherkey = pack("H32", $key);
 6602: 			$cipher       = new IDEA($cipherkey);
 6603: 			print $client "ok:local\n";
 6604: 			&logthis('<font color="green">'
 6605: 				 . "Successful local authentication </font>");
 6606: 			$keymode = "local"
 6607: 		    } else {
 6608: 			Debug("Failed to get local key");
 6609: 			$clientok = 0;
 6610: 			shutdown($client, 3);
 6611: 			close $client;
 6612: 		    }
 6613: 		} elsif ($inittype eq "ssl") {
 6614: 		    my $key = SSLConnection($client);
 6615: 		    if ($key) {
 6616: 			$clientok = 1;
 6617: 			my $cipherkey = pack("H32", $key);
 6618: 			$cipher       = new IDEA($cipherkey);
 6619: 			&logthis('<font color="green">'
 6620: 				 ."Successfull ssl authentication with $clientname </font>");
 6621: 			$keymode = "ssl";
 6622: 	     
 6623: 		    } else {
 6624: 			$clientok = 0;
 6625: 			close $client;
 6626: 		    }
 6627: 	   
 6628: 		} else {
 6629: 		    my $ok = InsecureConnection($client);
 6630: 		    if($ok) {
 6631: 			$clientok = 1;
 6632: 			&logthis('<font color="green">'
 6633: 				 ."Successful insecure authentication with $clientname </font>");
 6634: 			print $client "ok\n";
 6635: 			$keymode = "insecure";
 6636: 		    } else {
 6637: 			&logthis('<font color="yellow">'
 6638: 				  ."Attempted insecure connection disallowed </font>");
 6639: 			close $client;
 6640: 			$clientok = 0;
 6641: 			
 6642: 		    }
 6643: 		}
 6644: 	    } else {
 6645: 		&logthis(
 6646: 			 "<font color='blue'>WARNING: "
 6647: 			 ."$clientip failed to initialize: >$remotereq< </font>");
 6648: 		&status('No init '.$clientip);
 6649: 	    }
 6650: 	    
 6651: 	} else {
 6652: 	    &logthis(
 6653: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
 6654: 	    &status('Hung up on '.$clientip);
 6655: 	}
 6656:  
 6657: 	if ($clientok) {
 6658: # ---------------- New known client connecting, could mean machine online again
 6659: 	    if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip 
 6660: 		&& $clientip ne '127.0.0.1') {
 6661: 		&Apache::lonnet::reconlonc($clientname);
 6662: 	    }
 6663: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
 6664: 	    &status('Will listen to '.$clientname);
 6665: # ------------------------------------------------------------ Process requests
 6666: 	    my $keep_going = 1;
 6667: 	    my $user_input;
 6668:             my $clienthost = &Apache::lonnet::hostname($clientname);
 6669:             my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
 6670:             $clienthomedom = &Apache::lonnet::host_domain($clientserverhomeID);
 6671: 	    while(($user_input = get_request) && $keep_going) {
 6672: 		alarm(120);
 6673: 		Debug("Main: Got $user_input\n");
 6674: 		$keep_going = &process_request($user_input);
 6675: 		alarm(0);
 6676: 		&status('Listening to '.$clientname." ($keymode)");	   
 6677: 	    }
 6678: 
 6679: # --------------------------------------------- client unknown or fishy, refuse
 6680: 	}  else {
 6681: 	    print $client "refused\n";
 6682: 	    $client->close();
 6683: 	    &logthis("<font color='blue'>WARNING: "
 6684: 		     ."Rejected client $clientip, closing connection</font>");
 6685: 	}
 6686:     }            
 6687:     
 6688: # =============================================================================
 6689:     
 6690:     &logthis("<font color='red'>CRITICAL: "
 6691: 	     ."Disconnect from $clientip ($clientname)</font>");    
 6692:     
 6693:     
 6694:     # this exit is VERY important, otherwise the child will become
 6695:     # a producer of more and more children, forking yourself into
 6696:     # process death.
 6697:     exit;
 6698:     
 6699: }
 6700: #
 6701: #   Determine if a user is an author for the indicated domain.
 6702: #
 6703: # Parameters:
 6704: #    domain          - domain to check in .
 6705: #    user            - Name of user to check.
 6706: #
 6707: # Return:
 6708: #     1             - User is an author for domain.
 6709: #     0             - User is not an author for domain.
 6710: sub is_author {
 6711:     my ($domain, $user) = @_;
 6712: 
 6713:     &Debug("is_author: $user @ $domain");
 6714: 
 6715:     my $hashref = &tie_user_hash($domain, $user, "roles",
 6716: 				 &GDBM_READER());
 6717: 
 6718:     #  Author role should show up as a key /domain/_au
 6719: 
 6720:     my $key    = "/$domain/_au";
 6721:     my $value;
 6722:     if (defined($hashref)) {
 6723: 	$value = $hashref->{$key};
 6724:     }
 6725: 
 6726:     if(defined($value)) {
 6727: 	&Debug("$user @ $domain is an author");
 6728:     }
 6729: 
 6730:     return defined($value);
 6731: }
 6732: #
 6733: #   Checks to see if the input roleput request was to set
 6734: # an author role.  If so, creates construction space 
 6735: # Parameters:
 6736: #    request   - The request sent to the rolesput subchunk.
 6737: #                We're looking for  /domain/_au
 6738: #    domain    - The domain in which the user is having roles doctored.
 6739: #    user      - Name of the user for which the role is being put.
 6740: #    authtype  - The authentication type associated with the user.
 6741: #
 6742: sub manage_permissions {
 6743:     my ($request, $domain, $user, $authtype) = @_;
 6744:     # See if the request is of the form /$domain/_au
 6745:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
 6746:         my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
 6747:         unless (-e $path) {        
 6748:            mkdir($path);
 6749:         }
 6750:         unless (-e $path.'/'.$user) {
 6751:            mkdir($path.'/'.$user);
 6752:         }
 6753:     }
 6754: }
 6755: 
 6756: 
 6757: #
 6758: #  Return the full path of a user password file, whether it exists or not.
 6759: # Parameters:
 6760: #   domain     - Domain in which the password file lives.
 6761: #   user       - name of the user.
 6762: # Returns:
 6763: #    Full passwd path:
 6764: #
 6765: sub password_path {
 6766:     my ($domain, $user) = @_;
 6767:     return &propath($domain, $user).'/passwd';
 6768: }
 6769: 
 6770: #   Password Filename
 6771: #   Returns the path to a passwd file given domain and user... only if
 6772: #  it exists.
 6773: # Parameters:
 6774: #   domain    - Domain in which to search.
 6775: #   user      - username.
 6776: # Returns:
 6777: #   - If the password file exists returns its path.
 6778: #   - If the password file does not exist, returns undefined.
 6779: #
 6780: sub password_filename {
 6781:     my ($domain, $user) = @_;
 6782: 
 6783:     Debug ("PasswordFilename called: dom = $domain user = $user");
 6784: 
 6785:     my $path  = &password_path($domain, $user);
 6786:     Debug("PasswordFilename got path: $path");
 6787:     if(-e $path) {
 6788: 	return $path;
 6789:     } else {
 6790: 	return undef;
 6791:     }
 6792: }
 6793: 
 6794: #
 6795: #   Rewrite the contents of the user's passwd file.
 6796: #  Parameters:
 6797: #    domain    - domain of the user.
 6798: #    name      - User's name.
 6799: #    contents  - New contents of the file.
 6800: # Returns:
 6801: #   0    - Failed.
 6802: #   1    - Success.
 6803: #
 6804: sub rewrite_password_file {
 6805:     my ($domain, $user, $contents) = @_;
 6806: 
 6807:     my $file = &password_filename($domain, $user);
 6808:     if (defined $file) {
 6809: 	my $pf = IO::File->new(">$file");
 6810: 	if($pf) {
 6811: 	    print $pf "$contents\n";
 6812: 	    return 1;
 6813: 	} else {
 6814: 	    return 0;
 6815: 	}
 6816:     } else {
 6817: 	return 0;
 6818:     }
 6819: 
 6820: }
 6821: 
 6822: #
 6823: #   get_auth_type - Determines the authorization type of a user in a domain.
 6824: 
 6825: #     Returns the authorization type or nouser if there is no such user.
 6826: #
 6827: sub get_auth_type {
 6828:     my ($domain, $user)  = @_;
 6829: 
 6830:     Debug("get_auth_type( $domain, $user ) \n");
 6831:     my $proname    = &propath($domain, $user); 
 6832:     my $passwdfile = "$proname/passwd";
 6833:     if( -e $passwdfile ) {
 6834: 	my $pf = IO::File->new($passwdfile);
 6835: 	my $realpassword = <$pf>;
 6836: 	chomp($realpassword);
 6837: 	Debug("Password info = $realpassword\n");
 6838: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
 6839: 	Debug("Authtype = $authtype, content = $contentpwd\n");
 6840: 	return "$authtype:$contentpwd";     
 6841:     } else {
 6842: 	Debug("Returning nouser");
 6843: 	return "nouser";
 6844:     }
 6845: }
 6846: 
 6847: #
 6848: #  Validate a user given their domain, name and password.  This utility
 6849: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
 6850: #  to validate the login credentials of a user.
 6851: # Parameters:
 6852: #    $domain    - The domain being logged into (this is required due to
 6853: #                 the capability for multihomed systems.
 6854: #    $user      - The name of the user being validated.
 6855: #    $password  - The user's propoposed password.
 6856: #
 6857: # Returns:
 6858: #     1        - The domain,user,pasword triplet corresponds to a valid
 6859: #                user.
 6860: #     0        - The domain,user,password triplet is not a valid user.
 6861: #
 6862: sub validate_user {
 6863:     my ($domain, $user, $password, $checkdefauth) = @_;
 6864: 
 6865:     # Why negative ~pi you may well ask?  Well this function is about
 6866:     # authentication, and therefore very important to get right.
 6867:     # I've initialized the flag that determines whether or not I've 
 6868:     # validated correctly to a value it's not supposed to get.
 6869:     # At the end of this function. I'll ensure that it's not still that
 6870:     # value so we don't just wind up returning some accidental value
 6871:     # as a result of executing an unforseen code path that
 6872:     # did not set $validated.  At the end of valid execution paths,
 6873:     # validated shoule be 1 for success or 0 for failuer.
 6874: 
 6875:     my $validated = -3.14159;
 6876: 
 6877:     #  How we authenticate is determined by the type of authentication
 6878:     #  the user has been assigned.  If the authentication type is
 6879:     #  "nouser", the user does not exist so we will return 0.
 6880: 
 6881:     my $contents = &get_auth_type($domain, $user);
 6882:     my ($howpwd, $contentpwd) = split(/:/, $contents);
 6883: 
 6884:     my $null = pack("C",0);	# Used by kerberos auth types.
 6885: 
 6886:     if ($howpwd eq 'nouser') {
 6887:         if ($checkdefauth) {
 6888:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 6889:             if ($domdefaults{'auth_def'} eq 'localauth') {
 6890:                 $howpwd = $domdefaults{'auth_def'};
 6891:                 $contentpwd = $domdefaults{'auth_arg_def'};
 6892:             } elsif ((($domdefaults{'auth_def'} eq 'krb4') || 
 6893:                       ($domdefaults{'auth_def'} eq 'krb5')) &&
 6894:                      ($domdefaults{'auth_arg_def'} ne '')) {
 6895:                 $howpwd = $domdefaults{'auth_def'};
 6896:                 $contentpwd = $domdefaults{'auth_arg_def'}; 
 6897:             }
 6898:         }
 6899:     } 
 6900:     if ($howpwd ne 'nouser') {
 6901: 	if($howpwd eq "internal") { # Encrypted is in local password file.
 6902: 	    $validated = (crypt($password, $contentpwd) eq $contentpwd);
 6903: 	}
 6904: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
 6905: 	    $contentpwd = (getpwnam($user))[1];
 6906: 	    if($contentpwd) {
 6907: 		if($contentpwd eq 'x') { # Shadow password file...
 6908: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
 6909: 		    open PWAUTH,  "|$pwauth_path" or
 6910: 			die "Cannot invoke authentication";
 6911: 		    print PWAUTH "$user\n$password\n";
 6912: 		    close PWAUTH;
 6913: 		    $validated = ! $?;
 6914: 
 6915: 		} else { 	         # Passwords in /etc/passwd. 
 6916: 		    $validated = (crypt($password,
 6917: 					$contentpwd) eq $contentpwd);
 6918: 		}
 6919: 	    } else {
 6920: 		$validated = 0;
 6921: 	    }
 6922: 	} elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
 6923:             my $checkwithkrb5 = 0;
 6924:             if ($dist =~/^fedora(\d+)$/) {
 6925:                 if ($1 > 11) {
 6926:                     $checkwithkrb5 = 1;
 6927:                 }
 6928:             } elsif ($dist =~ /^suse([\d.]+)$/) {
 6929:                 if ($1 > 11.1) {
 6930:                     $checkwithkrb5 = 1; 
 6931:                 }
 6932:             }
 6933:             if ($checkwithkrb5) {
 6934:                 $validated = &krb5_authen($password,$null,$user,$contentpwd);
 6935:             } else {
 6936:                 $validated = &krb4_authen($password,$null,$user,$contentpwd);
 6937:             }
 6938: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
 6939:             $validated = &krb5_authen($password,$null,$user,$contentpwd);
 6940: 	} elsif ($howpwd eq "localauth") { 
 6941: 	    #  Authenticate via installation specific authentcation method:
 6942: 	    $validated = &localauth::localauth($user, 
 6943: 					       $password, 
 6944: 					       $contentpwd,
 6945: 					       $domain);
 6946: 	    if ($validated < 0) {
 6947: 		&logthis("localauth for $contentpwd $user:$domain returned a $validated");
 6948: 		$validated = 0;
 6949: 	    }
 6950: 	} else {			# Unrecognized auth is also bad.
 6951: 	    $validated = 0;
 6952: 	}
 6953:     } else {
 6954: 	$validated = 0;
 6955:     }
 6956:     #
 6957:     #  $validated has the correct stat of the authentication:
 6958:     #
 6959: 
 6960:     unless ($validated != -3.14159) {
 6961: 	#  I >really really< want to know if this happens.
 6962: 	#  since it indicates that user authentication is badly
 6963: 	#  broken in some code path.
 6964:         #
 6965: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
 6966:     }
 6967:     return $validated;
 6968: }
 6969: 
 6970: sub krb4_authen {
 6971:     my ($password,$null,$user,$contentpwd) = @_;
 6972:     my $validated = 0;
 6973:     if (!($password =~ /$null/) ) {  # Null password not allowed.
 6974:         eval {
 6975:             require Authen::Krb4;
 6976:         };
 6977:         if (!$@) {
 6978:             my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
 6979:                                                        "",
 6980:                                                        $contentpwd,,
 6981:                                                        'krbtgt',
 6982:                                                        $contentpwd,
 6983:                                                        1,
 6984:                                                        $password);
 6985:             if(!$k4error) {
 6986:                 $validated = 1;
 6987:             } else {
 6988:                 $validated = 0;
 6989:                 &logthis('krb4: '.$user.', '.$contentpwd.', '.
 6990:                           &Authen::Krb4::get_err_txt($Authen::Krb4::error));
 6991:             }
 6992:         } else {
 6993:             $validated = krb5_authen($password,$null,$user,$contentpwd);
 6994:         }
 6995:     }
 6996:     return $validated;
 6997: }
 6998: 
 6999: sub krb5_authen {
 7000:     my ($password,$null,$user,$contentpwd) = @_;
 7001:     my $validated = 0;
 7002:     if(!($password =~ /$null/)) { # Null password not allowed.
 7003:         my $krbclient = &Authen::Krb5::parse_name($user.'@'
 7004:                                                   .$contentpwd);
 7005:         my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
 7006:         my $krbserver  = &Authen::Krb5::parse_name($krbservice);
 7007:         my $credentials= &Authen::Krb5::cc_default();
 7008:         $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
 7009:                                                             .$contentpwd));
 7010:         my $krbreturn;
 7011:         if (exists(&Authen::Krb5::get_init_creds_password)) {
 7012:             $krbreturn =
 7013:                 &Authen::Krb5::get_init_creds_password($krbclient,$password,
 7014:                                                           $krbservice);
 7015:             $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
 7016:         } else {
 7017:             $krbreturn  =
 7018:                 &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
 7019:                                                          $password,$credentials);
 7020:             $validated = ($krbreturn == 1);
 7021:         }
 7022:         if (!$validated) {
 7023:             &logthis('krb5: '.$user.', '.$contentpwd.', '.
 7024:                      &Authen::Krb5::error());
 7025:         }
 7026:     }
 7027:     return $validated;
 7028: }
 7029: 
 7030: sub addline {
 7031:     my ($fname,$hostid,$ip,$newline)=@_;
 7032:     my $contents;
 7033:     my $found=0;
 7034:     my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
 7035:     my $sh;
 7036:     if ($sh=IO::File->new("$fname.subscription")) {
 7037: 	while (my $subline=<$sh>) {
 7038: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
 7039: 	}
 7040: 	$sh->close();
 7041:     }
 7042:     $sh=IO::File->new(">$fname.subscription");
 7043:     if ($contents) { print $sh $contents; }
 7044:     if ($newline) { print $sh $newline; }
 7045:     $sh->close();
 7046:     return $found;
 7047: }
 7048: 
 7049: sub get_chat {
 7050:     my ($cdom,$cname,$udom,$uname,$group)=@_;
 7051: 
 7052:     my @entries=();
 7053:     my $namespace = 'nohist_chatroom';
 7054:     my $namespace_inroom = 'nohist_inchatroom';
 7055:     if ($group ne '') {
 7056:         $namespace .= '_'.$group;
 7057:         $namespace_inroom .= '_'.$group;
 7058:     }
 7059:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
 7060: 				 &GDBM_READER());
 7061:     if ($hashref) {
 7062: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
 7063: 	&untie_user_hash($hashref);
 7064:     }
 7065:     my @participants=();
 7066:     my $cutoff=time-60;
 7067:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
 7068: 			      &GDBM_WRCREAT());
 7069:     if ($hashref) {
 7070:         $hashref->{$uname.':'.$udom}=time;
 7071:         foreach my $user (sort(keys(%$hashref))) {
 7072: 	    if ($hashref->{$user}>$cutoff) {
 7073: 		push(@participants, 'active_participant:'.$user);
 7074:             }
 7075:         }
 7076:         &untie_user_hash($hashref);
 7077:     }
 7078:     return (@participants,@entries);
 7079: }
 7080: 
 7081: sub chat_add {
 7082:     my ($cdom,$cname,$newchat,$group)=@_;
 7083:     my @entries=();
 7084:     my $time=time;
 7085:     my $namespace = 'nohist_chatroom';
 7086:     my $logfile = 'chatroom.log';
 7087:     if ($group ne '') {
 7088:         $namespace .= '_'.$group;
 7089:         $logfile = 'chatroom_'.$group.'.log';
 7090:     }
 7091:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
 7092: 				 &GDBM_WRCREAT());
 7093:     if ($hashref) {
 7094: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
 7095: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
 7096: 	my ($thentime,$idnum)=split(/\_/,$lastid);
 7097: 	my $newid=$time.'_000000';
 7098: 	if ($thentime==$time) {
 7099: 	    $idnum=~s/^0+//;
 7100: 	    $idnum++;
 7101: 	    $idnum=substr('000000'.$idnum,-6,6);
 7102: 	    $newid=$time.'_'.$idnum;
 7103: 	}
 7104: 	$hashref->{$newid}=$newchat;
 7105: 	my $expired=$time-3600;
 7106: 	foreach my $comment (keys(%$hashref)) {
 7107: 	    my ($thistime) = ($comment=~/(\d+)\_/);
 7108: 	    if ($thistime<$expired) {
 7109: 		delete $hashref->{$comment};
 7110: 	    }
 7111: 	}
 7112: 	{
 7113: 	    my $proname=&propath($cdom,$cname);
 7114: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
 7115: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
 7116: 	    }
 7117: 	    close(CHATLOG);
 7118: 	}
 7119: 	&untie_user_hash($hashref);
 7120:     }
 7121: }
 7122: 
 7123: sub unsub {
 7124:     my ($fname,$clientip)=@_;
 7125:     my $result;
 7126:     my $unsubs = 0;		# Number of successful unsubscribes:
 7127: 
 7128: 
 7129:     # An old way subscriptions were handled was to have a 
 7130:     # subscription marker file:
 7131: 
 7132:     Debug("Attempting unlink of $fname.$clientname");
 7133:     if (unlink("$fname.$clientname")) {
 7134: 	$unsubs++;		# Successful unsub via marker file.
 7135:     } 
 7136: 
 7137:     # The more modern way to do it is to have a subscription list
 7138:     # file:
 7139: 
 7140:     if (-e "$fname.subscription") {
 7141: 	my $found=&addline($fname,$clientname,$clientip,'');
 7142: 	if ($found) { 
 7143: 	    $unsubs++;
 7144: 	}
 7145:     } 
 7146: 
 7147:     #  If either or both of these mechanisms succeeded in unsubscribing a 
 7148:     #  resource we can return ok:
 7149: 
 7150:     if($unsubs) {
 7151: 	$result = "ok\n";
 7152:     } else {
 7153: 	$result = "not_subscribed\n";
 7154:     }
 7155: 
 7156:     return $result;
 7157: }
 7158: 
 7159: sub currentversion {
 7160:     my $fname=shift;
 7161:     my $version=-1;
 7162:     my $ulsdir='';
 7163:     if ($fname=~/^(.+)\/[^\/]+$/) {
 7164:        $ulsdir=$1;
 7165:     }
 7166:     my ($fnamere1,$fnamere2);
 7167:     # remove version if already specified
 7168:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
 7169:     # get the bits that go before and after the version number
 7170:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
 7171: 	$fnamere1=$1;
 7172: 	$fnamere2='.'.$2;
 7173:     }
 7174:     if (-e $fname) { $version=1; }
 7175:     if (-e $ulsdir) {
 7176: 	if(-d $ulsdir) {
 7177: 	    if (opendir(LSDIR,$ulsdir)) {
 7178: 		my $ulsfn;
 7179: 		while ($ulsfn=readdir(LSDIR)) {
 7180: # see if this is a regular file (ignore links produced earlier)
 7181: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
 7182: 		    unless (-l $thisfile) {
 7183: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
 7184: 			    if ($1>$version) { $version=$1; }
 7185: 			}
 7186: 		    }
 7187: 		}
 7188: 		closedir(LSDIR);
 7189: 		$version++;
 7190: 	    }
 7191: 	}
 7192:     }
 7193:     return $version;
 7194: }
 7195: 
 7196: sub thisversion {
 7197:     my $fname=shift;
 7198:     my $version=-1;
 7199:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
 7200: 	$version=$1;
 7201:     }
 7202:     return $version;
 7203: }
 7204: 
 7205: sub subscribe {
 7206:     my ($userinput,$clientip)=@_;
 7207:     my $result;
 7208:     my ($cmd,$fname)=split(/:/,$userinput,2);
 7209:     my $ownership=&ishome($fname);
 7210:     if ($ownership eq 'owner') {
 7211: # explitly asking for the current version?
 7212:         unless (-e $fname) {
 7213:             my $currentversion=&currentversion($fname);
 7214: 	    if (&thisversion($fname)==$currentversion) {
 7215:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
 7216: 		    my $root=$1;
 7217:                     my $extension=$2;
 7218:                     symlink($root.'.'.$extension,
 7219:                             $root.'.'.$currentversion.'.'.$extension);
 7220:                     unless ($extension=~/\.meta$/) {
 7221:                        symlink($root.'.'.$extension.'.meta',
 7222:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
 7223: 		    }
 7224:                 }
 7225:             }
 7226:         }
 7227: 	if (-e $fname) {
 7228: 	    if (-d $fname) {
 7229: 		$result="directory\n";
 7230: 	    } else {
 7231: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
 7232: 		my $now=time;
 7233: 		my $found=&addline($fname,$clientname,$clientip,
 7234: 				   "$clientname:$clientip:$now\n");
 7235: 		if ($found) { $result="$fname\n"; }
 7236: 		# if they were subscribed to only meta data, delete that
 7237:                 # subscription, when you subscribe to a file you also get
 7238:                 # the metadata
 7239: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
 7240: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
 7241:                 my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
 7242:                 $protocol = 'http' if ($protocol ne 'https');
 7243: 		$fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
 7244: 		$result="$fname\n";
 7245: 	    }
 7246: 	} else {
 7247: 	    $result="not_found\n";
 7248: 	}
 7249:     } else {
 7250: 	$result="rejected\n";
 7251:     }
 7252:     return $result;
 7253: }
 7254: #  Change the passwd of a unix user.  The caller must have
 7255: #  first verified that the user is a loncapa user.
 7256: #
 7257: # Parameters:
 7258: #    user      - Unix user name to change.
 7259: #    pass      - New password for the user.
 7260: # Returns:
 7261: #    ok    - if success
 7262: #    other - Some meaningfule error message string.
 7263: # NOTE:
 7264: #    invokes a setuid script to change the passwd.
 7265: sub change_unix_password {
 7266:     my ($user, $pass) = @_;
 7267: 
 7268:     &Debug("change_unix_password");
 7269:     my $execdir=$perlvar{'lonDaemons'};
 7270:     &Debug("Opening lcpasswd pipeline");
 7271:     my $pf = IO::File->new("|$execdir/lcpasswd > "
 7272: 			   ."$perlvar{'lonDaemons'}"
 7273: 			   ."/logs/lcpasswd.log");
 7274:     print $pf "$user\n$pass\n$pass\n";
 7275:     close $pf;
 7276:     my $err = $?;
 7277:     return ($err < @passwderrors) ? $passwderrors[$err] : 
 7278: 	"pwchange_falure - unknown error";
 7279: 
 7280:     
 7281: }
 7282: 
 7283: 
 7284: sub make_passwd_file {
 7285:     my ($uname,$udom,$umode,$npass,$passfilename)=@_;
 7286:     my $result="ok";
 7287:     if ($umode eq 'krb4' or $umode eq 'krb5') {
 7288: 	{
 7289: 	    my $pf = IO::File->new(">$passfilename");
 7290: 	    if ($pf) {
 7291: 		print $pf "$umode:$npass\n";
 7292: 	    } else {
 7293: 		$result = "pass_file_failed_error";
 7294: 	    }
 7295: 	}
 7296:     } elsif ($umode eq 'internal') {
 7297: 	my $salt=time;
 7298: 	$salt=substr($salt,6,2);
 7299: 	my $ncpass=crypt($npass,$salt);
 7300: 	{
 7301: 	    &Debug("Creating internal auth");
 7302: 	    my $pf = IO::File->new(">$passfilename");
 7303: 	    if($pf) {
 7304: 		print $pf "internal:$ncpass\n"; 
 7305: 	    } else {
 7306: 		$result = "pass_file_failed_error";
 7307: 	    }
 7308: 	}
 7309:     } elsif ($umode eq 'localauth') {
 7310: 	{
 7311: 	    my $pf = IO::File->new(">$passfilename");
 7312: 	    if($pf) {
 7313: 		print $pf "localauth:$npass\n";
 7314: 	    } else {
 7315: 		$result = "pass_file_failed_error";
 7316: 	    }
 7317: 	}
 7318:     } elsif ($umode eq 'unix') {
 7319: 	{
 7320: 	    #
 7321: 	    #  Don't allow the creation of privileged accounts!!! that would
 7322: 	    #  be real bad!!!
 7323: 	    #
 7324: 	    my $uid = getpwnam($uname);
 7325: 	    if((defined $uid) && ($uid == 0)) {
 7326: 		&logthis(">>>Attempt to create privileged account blocked");
 7327: 		return "no_priv_account_error\n";
 7328: 	    }
 7329: 
 7330: 	    my $execpath       ="$perlvar{'lonDaemons'}/"."lcuseradd";
 7331: 
 7332: 	    my $lc_error_file  = $execdir."/tmp/lcuseradd".$$.".status";
 7333: 	    {
 7334: 		&Debug("Executing external: ".$execpath);
 7335: 		&Debug("user  = ".$uname.", Password =". $npass);
 7336: 		my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
 7337: 		print $se "$uname\n";
 7338:                 print $se "$udom\n";
 7339: 		print $se "$npass\n";
 7340: 		print $se "$npass\n";
 7341: 		print $se "$lc_error_file\n"; # Status -> unique file.
 7342: 	    }
 7343: 	    if (-r $lc_error_file) {
 7344: 		&Debug("Opening error file: $lc_error_file");
 7345: 		my $error = IO::File->new("< $lc_error_file");
 7346: 		my $useraddok = <$error>;
 7347: 		$error->close;
 7348: 		unlink($lc_error_file);
 7349: 		
 7350: 		chomp $useraddok;
 7351: 	
 7352: 		if($useraddok > 0) {
 7353: 		    my $error_text = &lcuseraddstrerror($useraddok);
 7354: 		    &logthis("Failed lcuseradd: $error_text");
 7355: 		    $result = "lcuseradd_failed:$error_text";
 7356: 		}  else {
 7357: 		    my $pf = IO::File->new(">$passfilename");
 7358: 		    if($pf) {
 7359: 			print $pf "unix:\n";
 7360: 		    } else {
 7361: 			$result = "pass_file_failed_error";
 7362: 		    }
 7363: 		}
 7364: 	    }  else {
 7365: 		&Debug("Could not locate lcuseradd error: $lc_error_file");
 7366: 		$result="bug_lcuseradd_no_output_file";
 7367: 	    }
 7368: 	}
 7369:     } elsif ($umode eq 'none') {
 7370: 	{
 7371: 	    my $pf = IO::File->new("> $passfilename");
 7372: 	    if($pf) {
 7373: 		print $pf "none:\n";
 7374: 	    } else {
 7375: 		$result = "pass_file_failed_error";
 7376: 	    }
 7377: 	}
 7378:     } else {
 7379: 	$result="auth_mode_error";
 7380:     }
 7381:     return $result;
 7382: }
 7383: 
 7384: sub convert_photo {
 7385:     my ($start,$dest)=@_;
 7386:     system("convert $start $dest");
 7387: }
 7388: 
 7389: sub sethost {
 7390:     my ($remotereq) = @_;
 7391:     my (undef,$hostid)=split(/:/,$remotereq);
 7392:     # ignore sethost if we are already correct
 7393:     if ($hostid eq $currenthostid) {
 7394: 	return 'ok';
 7395:     }
 7396: 
 7397:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
 7398:     if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'}) 
 7399: 	eq &Apache::lonnet::get_host_ip($hostid)) {
 7400: 	$currenthostid  =$hostid;
 7401: 	$currentdomainid=&Apache::lonnet::host_domain($hostid);
 7402: #	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
 7403:     } else {
 7404: 	&logthis("Requested host id $hostid not an alias of ".
 7405: 		 $perlvar{'lonHostID'}." refusing connection");
 7406: 	return 'unable_to_set';
 7407:     }
 7408:     return 'ok';
 7409: }
 7410: 
 7411: sub version {
 7412:     my ($userinput)=@_;
 7413:     $remoteVERSION=(split(/:/,$userinput))[1];
 7414:     return "version:$VERSION";
 7415: }
 7416: 
 7417: sub get_usersession_config {
 7418:     my ($dom,$name) = @_;
 7419:     my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
 7420:     if (defined($cached)) {
 7421:         return $usersessionconf;
 7422:     } else {
 7423:         my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
 7424:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 7425:             &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
 7426:             return $domconfig{'usersessions'};
 7427:         }
 7428:     }
 7429:     return;
 7430: }
 7431: 
 7432: sub releasereqd_check {
 7433:     my ($cnum,$cdom,$key,$value,$major,$minor,$homecourses,$ids) = @_;
 7434:     my $home = &Apache::lonnet::homeserver($cnum,$cdom);
 7435:     return if ($home eq 'no_host');
 7436:     my ($reqdmajor,$reqdminor,$displayrole);
 7437:     if ($cnum =~ /$LONCAPA::match_community/) {
 7438:         if ($major eq '' && $minor eq '') {
 7439:             return unless ((ref($ids) eq 'ARRAY') && 
 7440:                            (grep(/^\Q$home\E$/,@{$ids})));
 7441:         } else {
 7442:             $reqdmajor = 2;
 7443:             $reqdminor = 9;
 7444:             return unless (&useable_role($reqdmajor,$reqdminor,$major,$minor));
 7445:         }
 7446:     }
 7447:     my $hashid = $cdom.':'.$cnum;
 7448:     my ($courseinfo,$cached) =
 7449:         &Apache::lonnet::is_cached_new('courseinfo',$hashid);
 7450:     if (defined($cached)) {
 7451:         if (ref($courseinfo) eq 'HASH') {
 7452:             if (exists($courseinfo->{'releaserequired'})) {
 7453:                 my ($reqdmajor,$reqdminor) = split(/\./,$courseinfo->{'releaserequired'});
 7454:                 return unless (&useable_role($reqdmajor,$reqdminor,$major,$minor));
 7455:             }
 7456:         }
 7457:     } else {
 7458:         if (ref($ids) eq 'ARRAY') {
 7459:             if (grep(/^\Q$home\E$/,@{$ids})) {
 7460:                 if (ref($homecourses) eq 'HASH') {
 7461:                     if (ref($homecourses->{$hashid}) eq 'ARRAY') {
 7462:                         push(@{$homecourses->{$hashid}},{$key=>$value});
 7463:                     } else {
 7464:                         $homecourses->{$hashid} = [{$key=>$value}];
 7465:                     }
 7466:                 }
 7467:                 return;
 7468:             }
 7469:         }
 7470:         my $courseinfo = &get_courseinfo_hash($cnum,$cdom,$home);
 7471:         if (ref($courseinfo) eq 'HASH') {
 7472:             if (exists($courseinfo->{'releaserequired'})) {
 7473:                 my ($reqdmajor,$reqdminor) = split(/\./,$courseinfo->{'releaserequired'});
 7474:                 return unless (&useable_role($reqdmajor,$reqdminor,$major,$minor));
 7475:             }
 7476:         } else {
 7477:             return;
 7478:         }
 7479:     }
 7480:     return 1;
 7481: }
 7482: 
 7483: sub get_courseinfo_hash {
 7484:     my ($cnum,$cdom,$home) = @_;
 7485:     my %info;
 7486:     eval {
 7487:         local($SIG{ALRM}) = sub { die "timeout\n"; };
 7488:         local($SIG{__DIE__})='DEFAULT';
 7489:         alarm(3);
 7490:         %info = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,1,[$home],'.');
 7491:         alarm(0);
 7492:     };
 7493:     if ($@) {
 7494:         if ($@ eq "timeout\n") {
 7495:             &logthis("<font color='blue'>WARNING courseiddump for $cnum:$cdom from $home timedout</font>");
 7496:         } else {
 7497:             &logthis("<font color='yellow'>WARNING unexpected error during eval of call for courseiddump from $home</font>");
 7498:         }
 7499:     } else {
 7500:         if (ref($info{$cdom.'_'.$cnum}) eq 'HASH') {
 7501:             my $hashid = $cdom.':'.$cnum;
 7502:             return &Apache::lonnet::do_cache_new('courseinfo',$hashid,$info{$cdom.'_'.$cnum},600);
 7503:         }
 7504:     }
 7505:     return;
 7506: }
 7507: 
 7508: sub check_homecourses {
 7509:     my ($homecourses,$udom,$regexp,$count,$range,$start,$end,$major,$minor) = @_;
 7510:     my ($result,%addtocache);
 7511:     my $yesterday = time - 24*3600; 
 7512:     if (ref($homecourses) eq 'HASH') {
 7513:         my (%okcourses,%courseinfo,%recent);
 7514:         my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 7515:         if ($hashref) {
 7516:             while (my ($key,$value) = each(%$hashref)) {
 7517:                 my $unesc_key = &unescape($key);
 7518:                 if ($unesc_key =~ /^lasttime:(\w+)$/) {
 7519:                     my $cid = $1;
 7520:                     $cid =~ s/_/:/;
 7521:                     if ($value > $yesterday ) {
 7522:                         $recent{$cid} = 1;
 7523:                     }
 7524:                     next;
 7525:                 }
 7526:                 my $items = &Apache::lonnet::thaw_unescape($value);
 7527:                 if (ref($items) eq 'HASH') {
 7528:                     my $hashid = $unesc_key;
 7529:                     $hashid =~ s/_/:/;
 7530:                     $courseinfo{$hashid} = $items;
 7531:                     if (ref($homecourses->{$hashid}) eq 'ARRAY') {
 7532:                         my ($reqdmajor,$reqdminor) = split(/\./,$items->{'releaserequired'});
 7533:                         if (&useable_role($reqdmajor,$reqdminor,$major,$minor)) {
 7534:                             $okcourses{$hashid} = 1;
 7535:                         }
 7536:                     }
 7537:                 }
 7538:             }
 7539:             unless (&untie_domain_hash($hashref)) {
 7540:                 &logthis('Failed to untie tied hash for nohist_courseids.db');
 7541:             }
 7542:         } else {
 7543:             &logthis('Failed to tie hash for nohist_courseids.db');
 7544:             return;
 7545:         }
 7546:         foreach my $hashid (keys(%recent)) {
 7547:             my ($result,$cached)=&Apache::lonnet::is_cached_new('courseinfo',$hashid);
 7548:             unless ($cached) {
 7549:                 &Apache::lonnet::do_cache_new('courseinfo',$hashid,$courseinfo{$hashid},600);
 7550:             }
 7551:         }
 7552:         foreach my $hashid (keys(%{$homecourses})) {
 7553:             next if ($recent{$hashid});
 7554:             &Apache::lonnet::do_cache_new('courseinfo',$hashid,$courseinfo{$hashid},600);
 7555:         }
 7556:         foreach my $hashid (keys(%okcourses)) {
 7557:             if (ref($homecourses->{$hashid}) eq 'ARRAY') {
 7558:                 foreach my $role (@{$homecourses->{$hashid}}) {
 7559:                     if (ref($role) eq 'HASH') {
 7560:                         while (my ($key,$value) = each(%{$role})) {
 7561:                             if ($regexp eq '.') {
 7562:                                 $count++;
 7563:                                 if (defined($range) && $count >= $end)   { last; }
 7564:                                 if (defined($range) && $count <  $start) { next; }
 7565:                                 $result.=$key.'='.$value.'&';
 7566:                             } else {
 7567:                                 my $unescapeKey = &unescape($key);
 7568:                                 if (eval('$unescapeKey=~/$regexp/')) {
 7569:                                     $count++;
 7570:                                     if (defined($range) && $count >= $end)   { last; }
 7571:                                     if (defined($range) && $count <  $start) { next; }
 7572:                                     $result.="$key=$value&";
 7573:                                 }
 7574:                             }
 7575:                         }
 7576:                     }
 7577:                 }
 7578:             }
 7579:         }
 7580:     }
 7581:     return $result;
 7582: }
 7583: 
 7584: sub useable_role {
 7585:     my ($reqdmajor,$reqdminor,$major,$minor) = @_; 
 7586:     if ($reqdmajor ne '' && $reqdminor ne '') {
 7587:         return if (($major eq '' && $minor eq '') ||
 7588:                    ($major < $reqdmajor) ||
 7589:                    (($major == $reqdmajor) && ($minor < $reqdminor)));
 7590:     }
 7591:     return 1;
 7592: }
 7593: 
 7594: sub distro_and_arch {
 7595:     return $dist.':'.$arch;
 7596: }
 7597: 
 7598: # ----------------------------------- POD (plain old documentation, CPAN style)
 7599: 
 7600: =head1 NAME
 7601: 
 7602: lond - "LON Daemon" Server (port "LOND" 5663)
 7603: 
 7604: =head1 SYNOPSIS
 7605: 
 7606: Usage: B<lond>
 7607: 
 7608: Should only be run as user=www.  This is a command-line script which
 7609: is invoked by B<loncron>.  There is no expectation that a typical user
 7610: will manually start B<lond> from the command-line.  (In other words,
 7611: DO NOT START B<lond> YOURSELF.)
 7612: 
 7613: =head1 DESCRIPTION
 7614: 
 7615: There are two characteristics associated with the running of B<lond>,
 7616: PROCESS MANAGEMENT (starting, stopping, handling child processes)
 7617: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
 7618: subscriptions, etc).  These are described in two large
 7619: sections below.
 7620: 
 7621: B<PROCESS MANAGEMENT>
 7622: 
 7623: Preforker - server who forks first. Runs as a daemon. HUPs.
 7624: Uses IDEA encryption
 7625: 
 7626: B<lond> forks off children processes that correspond to the other servers
 7627: in the network.  Management of these processes can be done at the
 7628: parent process level or the child process level.
 7629: 
 7630: B<logs/lond.log> is the location of log messages.
 7631: 
 7632: The process management is now explained in terms of linux shell commands,
 7633: subroutines internal to this code, and signal assignments:
 7634: 
 7635: =over 4
 7636: 
 7637: =item *
 7638: 
 7639: PID is stored in B<logs/lond.pid>
 7640: 
 7641: This is the process id number of the parent B<lond> process.
 7642: 
 7643: =item *
 7644: 
 7645: SIGTERM and SIGINT
 7646: 
 7647: Parent signal assignment:
 7648:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 7649: 
 7650: Child signal assignment:
 7651:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
 7652: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
 7653:  to restart a new child.)
 7654: 
 7655: Command-line invocations:
 7656:  B<kill> B<-s> SIGTERM I<PID>
 7657:  B<kill> B<-s> SIGINT I<PID>
 7658: 
 7659: Subroutine B<HUNTSMAN>:
 7660:  This is only invoked for the B<lond> parent I<PID>.
 7661: This kills all the children, and then the parent.
 7662: The B<lonc.pid> file is cleared.
 7663: 
 7664: =item *
 7665: 
 7666: SIGHUP
 7667: 
 7668: Current bug:
 7669:  This signal can only be processed the first time
 7670: on the parent process.  Subsequent SIGHUP signals
 7671: have no effect.
 7672: 
 7673: Parent signal assignment:
 7674:  $SIG{HUP}  = \&HUPSMAN;
 7675: 
 7676: Child signal assignment:
 7677:  none (nothing happens)
 7678: 
 7679: Command-line invocations:
 7680:  B<kill> B<-s> SIGHUP I<PID>
 7681: 
 7682: Subroutine B<HUPSMAN>:
 7683:  This is only invoked for the B<lond> parent I<PID>,
 7684: This kills all the children, and then the parent.
 7685: The B<lond.pid> file is cleared.
 7686: 
 7687: =item *
 7688: 
 7689: SIGUSR1
 7690: 
 7691: Parent signal assignment:
 7692:  $SIG{USR1} = \&USRMAN;
 7693: 
 7694: Child signal assignment:
 7695:  $SIG{USR1}= \&logstatus;
 7696: 
 7697: Command-line invocations:
 7698:  B<kill> B<-s> SIGUSR1 I<PID>
 7699: 
 7700: Subroutine B<USRMAN>:
 7701:  When invoked for the B<lond> parent I<PID>,
 7702: SIGUSR1 is sent to all the children, and the status of
 7703: each connection is logged.
 7704: 
 7705: =item *
 7706: 
 7707: SIGUSR2
 7708: 
 7709: Parent Signal assignment:
 7710:     $SIG{USR2} = \&UpdateHosts
 7711: 
 7712: Child signal assignment:
 7713:     NONE
 7714: 
 7715: 
 7716: =item *
 7717: 
 7718: SIGCHLD
 7719: 
 7720: Parent signal assignment:
 7721:  $SIG{CHLD} = \&REAPER;
 7722: 
 7723: Child signal assignment:
 7724:  none
 7725: 
 7726: Command-line invocations:
 7727:  B<kill> B<-s> SIGCHLD I<PID>
 7728: 
 7729: Subroutine B<REAPER>:
 7730:  This is only invoked for the B<lond> parent I<PID>.
 7731: Information pertaining to the child is removed.
 7732: The socket port is cleaned up.
 7733: 
 7734: =back
 7735: 
 7736: B<SERVER-SIDE ACTIVITIES>
 7737: 
 7738: Server-side information can be accepted in an encrypted or non-encrypted
 7739: method.
 7740: 
 7741: =over 4
 7742: 
 7743: =item ping
 7744: 
 7745: Query a client in the hosts.tab table; "Are you there?"
 7746: 
 7747: =item pong
 7748: 
 7749: Respond to a ping query.
 7750: 
 7751: =item ekey
 7752: 
 7753: Read in encrypted key, make cipher.  Respond with a buildkey.
 7754: 
 7755: =item load
 7756: 
 7757: Respond with CPU load based on a computation upon /proc/loadavg.
 7758: 
 7759: =item currentauth
 7760: 
 7761: Reply with current authentication information (only over an
 7762: encrypted channel).
 7763: 
 7764: =item auth
 7765: 
 7766: Only over an encrypted channel, reply as to whether a user's
 7767: authentication information can be validated.
 7768: 
 7769: =item passwd
 7770: 
 7771: Allow for a password to be set.
 7772: 
 7773: =item makeuser
 7774: 
 7775: Make a user.
 7776: 
 7777: =item passwd
 7778: 
 7779: Allow for authentication mechanism and password to be changed.
 7780: 
 7781: =item home
 7782: 
 7783: Respond to a question "are you the home for a given user?"
 7784: 
 7785: =item update
 7786: 
 7787: Update contents of a subscribed resource.
 7788: 
 7789: =item unsubscribe
 7790: 
 7791: The server is unsubscribing from a resource.
 7792: 
 7793: =item subscribe
 7794: 
 7795: The server is subscribing to a resource.
 7796: 
 7797: =item log
 7798: 
 7799: Place in B<logs/lond.log>
 7800: 
 7801: =item put
 7802: 
 7803: stores hash in namespace
 7804: 
 7805: =item rolesputy
 7806: 
 7807: put a role into a user's environment
 7808: 
 7809: =item get
 7810: 
 7811: returns hash with keys from array
 7812: reference filled in from namespace
 7813: 
 7814: =item eget
 7815: 
 7816: returns hash with keys from array
 7817: reference filled in from namesp (encrypts the return communication)
 7818: 
 7819: =item rolesget
 7820: 
 7821: get a role from a user's environment
 7822: 
 7823: =item del
 7824: 
 7825: deletes keys out of array from namespace
 7826: 
 7827: =item keys
 7828: 
 7829: returns namespace keys
 7830: 
 7831: =item dump
 7832: 
 7833: dumps the complete (or key matching regexp) namespace into a hash
 7834: 
 7835: =item store
 7836: 
 7837: stores hash permanently
 7838: for this url; hashref needs to be given and should be a \%hashname; the
 7839: remaining args aren't required and if they aren't passed or are '' they will
 7840: be derived from the ENV
 7841: 
 7842: =item restore
 7843: 
 7844: returns a hash for a given url
 7845: 
 7846: =item querysend
 7847: 
 7848: Tells client about the lonsql process that has been launched in response
 7849: to a sent query.
 7850: 
 7851: =item queryreply
 7852: 
 7853: Accept information from lonsql and make appropriate storage in temporary
 7854: file space.
 7855: 
 7856: =item idput
 7857: 
 7858: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
 7859: for each student, defined perhaps by the institutional Registrar.)
 7860: 
 7861: =item idget
 7862: 
 7863: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
 7864: for each student, defined perhaps by the institutional Registrar.)
 7865: 
 7866: =item tmpput
 7867: 
 7868: Accept and store information in temporary space.
 7869: 
 7870: =item tmpget
 7871: 
 7872: Send along temporarily stored information.
 7873: 
 7874: =item ls
 7875: 
 7876: List part of a user's directory.
 7877: 
 7878: =item pushtable
 7879: 
 7880: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
 7881: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
 7882: must be restored manually in case of a problem with the new table file.
 7883: pushtable requires that the request be encrypted and validated via
 7884: ValidateManager.  The form of the command is:
 7885: enc:pushtable tablename <tablecontents> \n
 7886: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
 7887: cleartext newline.
 7888: 
 7889: =item Hanging up (exit or init)
 7890: 
 7891: What to do when a client tells the server that they (the client)
 7892: are leaving the network.
 7893: 
 7894: =item unknown command
 7895: 
 7896: If B<lond> is sent an unknown command (not in the list above),
 7897: it replys to the client "unknown_cmd".
 7898: 
 7899: 
 7900: =item UNKNOWN CLIENT
 7901: 
 7902: If the anti-spoofing algorithm cannot verify the client,
 7903: the client is rejected (with a "refused" message sent
 7904: to the client, and the connection is closed.
 7905: 
 7906: =back
 7907: 
 7908: =head1 PREREQUISITES
 7909: 
 7910: IO::Socket
 7911: IO::File
 7912: Apache::File
 7913: POSIX
 7914: Crypt::IDEA
 7915: LWP::UserAgent()
 7916: GDBM_File
 7917: Authen::Krb4
 7918: Authen::Krb5
 7919: 
 7920: =head1 COREQUISITES
 7921: 
 7922: =head1 OSNAMES
 7923: 
 7924: linux
 7925: 
 7926: =head1 SCRIPT CATEGORIES
 7927: 
 7928: Server/Process
 7929: 
 7930: =cut
 7931: 
 7932: 
 7933: =pod
 7934: 
 7935: =head1 LOG MESSAGES
 7936: 
 7937: The messages below can be emitted in the lond log.  This log is located
 7938: in ~httpd/perl/logs/lond.log  Many log messages have HTML encapsulation
 7939: to provide coloring if examined from inside a web page. Some do not.
 7940: Where color is used, the colors are; Red for sometihhng to get excited
 7941: about and to follow up on. Yellow for something to keep an eye on to
 7942: be sure it does not get worse, Green,and Blue for informational items.
 7943: 
 7944: In the discussions below, sometimes reference is made to ~httpd
 7945: when describing file locations.  There isn't really an httpd 
 7946: user, however there is an httpd directory that gets installed in the
 7947: place that user home directories go.  On linux, this is usually
 7948: (always?) /home/httpd.
 7949: 
 7950: 
 7951: Some messages are colorless.  These are usually (not always)
 7952: Green/Blue color level messages.
 7953: 
 7954: =over 2
 7955: 
 7956: =item (Red)  LocalConnection rejecting non local: <ip> ne 127.0.0.1
 7957: 
 7958: A local connection negotiation was attempted by
 7959: a host whose IP address was not 127.0.0.1.
 7960: The socket is closed and the child will exit.
 7961: lond has three ways to establish an encyrption
 7962: key with a client:
 7963: 
 7964: =over 2
 7965: 
 7966: =item local 
 7967: 
 7968: The key is written and read from a file.
 7969: This is only valid for connections from localhost.
 7970: 
 7971: =item insecure 
 7972: 
 7973: The key is generated by the server and
 7974: transmitted to the client.
 7975: 
 7976: =item  ssl (secure)
 7977: 
 7978: An ssl connection is negotiated with the client,
 7979: the key is generated by the server and sent to the 
 7980: client across this ssl connection before the
 7981: ssl connectionis terminated and clear text
 7982: transmission resumes.
 7983: 
 7984: =back
 7985: 
 7986: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
 7987: 
 7988: The client is local but has not sent an initialization
 7989: string that is the literal "init:local"  The connection
 7990: is closed and the child exits.
 7991: 
 7992: =item Red CRITICAL Can't get key file <error>        
 7993: 
 7994: SSL key negotiation is being attempted but the call to
 7995: lonssl::KeyFile  failed.  This usually means that the
 7996: configuration file is not correctly defining or protecting
 7997: the directories/files lonCertificateDirectory or
 7998: lonnetPrivateKey
 7999: <error> is a string that describes the reason that
 8000: the key file could not be located.
 8001: 
 8002: =item (Red) CRITICAL  Can't get certificates <error>  
 8003: 
 8004: SSL key negotiation failed because we were not able to retrives our certificate
 8005: or the CA's certificate in the call to lonssl::CertificateFile
 8006: <error> is the textual reason this failed.  Usual reasons:
 8007: 
 8008: =over 2
 8009:        
 8010: =item Apache config file for loncapa  incorrect:
 8011:  
 8012: one of the variables 
 8013: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
 8014: undefined or incorrect
 8015: 
 8016: =item Permission error:
 8017: 
 8018: The directory pointed to by lonCertificateDirectory is not readable by lond
 8019: 
 8020: =item Permission error:
 8021: 
 8022: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
 8023: 
 8024: =item Installation error:                         
 8025: 
 8026: Either the certificate authority file or the certificate have not
 8027: been installed in lonCertificateDirectory.
 8028: 
 8029: =item (Red) CRITICAL SSL Socket promotion failed:  <err> 
 8030: 
 8031: The promotion of the connection from plaintext to SSL failed
 8032: <err> is the reason for the failure.  There are two
 8033: system calls involved in the promotion (one of which failed), 
 8034: a dup to produce
 8035: a second fd on the raw socket over which the encrypted data
 8036: will flow and IO::SOcket::SSL->new_from_fd which creates
 8037: the SSL connection on the duped fd.
 8038: 
 8039: =item (Blue)   WARNING client did not respond to challenge 
 8040: 
 8041: This occurs on an insecure (non SSL) connection negotiation request.
 8042: lond generates some number from the time, the PID and sends it to
 8043: the client.  The client must respond by echoing this information back.
 8044: If the client does not do so, that's a violation of the challenge
 8045: protocols and the connection will be failed.
 8046: 
 8047: =item (Red) No manager table. Nobody can manage!!    
 8048: 
 8049: lond has the concept of privileged hosts that
 8050: can perform remote management function such
 8051: as update the hosts.tab.   The manager hosts
 8052: are described in the 
 8053: ~httpd/lonTabs/managers.tab file.
 8054: this message is logged if this file is missing.
 8055: 
 8056: 
 8057: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
 8058: 
 8059: Reports the successful parse and registration
 8060: of a specific manager. 
 8061: 
 8062: =item Green existing host <clustername:dnsname>  
 8063: 
 8064: The manager host is already defined in the hosts.tab
 8065: the information in that table, rather than the info in the
 8066: manager table will be used to determine the manager's ip.
 8067: 
 8068: =item (Red) Unable to craete <filename>                 
 8069: 
 8070: lond has been asked to create new versions of an administrative
 8071: file (by a manager).  When this is done, the new file is created
 8072: in a temp file and then renamed into place so that there are always
 8073: usable administrative files, even if the update fails.  This failure
 8074: message means that the temp file could not be created.
 8075: The update is abandoned, and the old file is available for use.
 8076: 
 8077: =item (Green) CopyFile from <oldname> to <newname> failed
 8078: 
 8079: In an update of administrative files, the copy of the existing file to a
 8080: backup file failed.  The installation of the new file may still succeed,
 8081: but there will not be a back up file to rever to (this should probably
 8082: be yellow).
 8083: 
 8084: =item (Green) Pushfile: backed up <oldname> to <newname>
 8085: 
 8086: See above, the backup of the old administrative file succeeded.
 8087: 
 8088: =item (Red)  Pushfile: Unable to install <filename> <reason>
 8089: 
 8090: The new administrative file could not be installed.  In this case,
 8091: the old administrative file is still in use.
 8092: 
 8093: =item (Green) Installed new < filename>.                      
 8094: 
 8095: The new administrative file was successfullly installed.                                               
 8096: 
 8097: =item (Red) Reinitializing lond pid=<pid>                    
 8098: 
 8099: The lonc child process <pid> will be sent a USR2 
 8100: signal.
 8101: 
 8102: =item (Red) Reinitializing self                                    
 8103: 
 8104: We've been asked to re-read our administrative files,and
 8105: are doing so.
 8106: 
 8107: =item (Yellow) error:Invalid process identifier <ident>  
 8108: 
 8109: A reinit command was received, but the target part of the 
 8110: command was not valid.  It must be either
 8111: 'lond' or 'lonc' but was <ident>
 8112: 
 8113: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
 8114: 
 8115: Checking to see if lond has been handed a valid edit
 8116: command.  It is possible the edit command is not valid
 8117: in that case there are no log messages to indicate that.
 8118: 
 8119: =item Result of password change for  <username> pwchange_success
 8120: 
 8121: The password for <username> was
 8122: successfully changed.
 8123: 
 8124: =item Unable to open <user> passwd to change password
 8125: 
 8126: Could not rewrite the 
 8127: internal password file for a user
 8128: 
 8129: =item Result of password change for <user> : <result>
 8130:                                                                      
 8131: A unix password change for <user> was attempted 
 8132: and the pipe returned <result>  
 8133: 
 8134: =item LWP GET: <message> for <fname> (<remoteurl>)
 8135: 
 8136: The lightweight process fetch for a resource failed
 8137: with <message> the local filename that should
 8138: have existed/been created was  <fname> the
 8139: corresponding URI: <remoteurl>  This is emitted in several
 8140: places.
 8141: 
 8142: =item Unable to move <transname> to <destname>     
 8143: 
 8144: From fetch_user_file_handler - the user file was replicated but could not
 8145: be mv'd to its final location.
 8146: 
 8147: =item Looking for <domain> <username>              
 8148: 
 8149: From user_has_session_handler - This should be a Debug call instead
 8150: it indicates lond is about to check whether the specified user has a 
 8151: session active on the specified domain on the local host.
 8152: 
 8153: =item Client <ip> (<name>) hanging up: <input>     
 8154: 
 8155: lond has been asked to exit by its client.  The <ip> and <name> identify the
 8156: client systemand <input> is the full exit command sent to the server.
 8157: 
 8158: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
 8159:                                                  
 8160: A lond child terminated.  NOte that this termination can also occur when the
 8161: child receives the QUIT or DIE signals.  <pid> is the process id of the child,
 8162: <hostname> the host lond is working for, and <message> the reason the child died
 8163: to the best of our ability to get it (I would guess that any numeric value
 8164: represents and errno value).  This is immediately followed by
 8165: 
 8166: =item  Famous last words: Catching exception - <log> 
 8167: 
 8168: Where log is some recent information about the state of the child.
 8169: 
 8170: =item Red CRITICAL: TIME OUT <pid>                     
 8171: 
 8172: Some timeout occured for server <pid>.  THis is normally a timeout on an LWP
 8173: doing an HTTP::GET.
 8174: 
 8175: =item child <pid> died                              
 8176: 
 8177: The reaper caught a SIGCHILD for the lond child process <pid>
 8178: This should be modified to also display the IP of the dying child
 8179: $children{$pid}
 8180: 
 8181: =item Unknown child 0 died                           
 8182: A child died but the wait for it returned a pid of zero which really should not
 8183: ever happen. 
 8184: 
 8185: =item Child <which> - <pid> looks like we missed it's death 
 8186: 
 8187: When a sigchild is received, the reaper process checks all children to see if they are
 8188: alive.  If children are dying quite quickly, the lack of signal queuing can mean
 8189: that a signal hearalds the death of more than one child.  If so this message indicates
 8190: which other one died. <which> is the ip of a dead child
 8191: 
 8192: =item Free socket: <shutdownretval>                
 8193: 
 8194: The HUNTSMAN sub was called due to a SIGINT in a child process.  The socket is being shutdown.
 8195: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
 8196: to return anything. This is followed by: 
 8197: 
 8198: =item Red CRITICAL: Shutting down                       
 8199: 
 8200: Just prior to exit.
 8201: 
 8202: =item Free socket: <shutdownretval>                 
 8203: 
 8204: The HUPSMAN sub was called due to a SIGHUP.  all children get killsed, and lond execs itself.
 8205: This is followed by:
 8206: 
 8207: =item (Red) CRITICAL: Restarting                         
 8208: 
 8209: lond is about to exec itself to restart.
 8210: 
 8211: =item (Blue) Updating connections                        
 8212: 
 8213: (In response to a USR2).  All the children (except the one for localhost)
 8214: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
 8215: 
 8216: =item (Blue) UpdateHosts killing child <pid> for ip <ip>   
 8217: 
 8218: Due to USR2 as above.
 8219: 
 8220: =item (Green) keeping child for ip <ip> (pid = <pid>)    
 8221: 
 8222: In response to USR2 as above, the child indicated is not being restarted because
 8223: it's assumed that we'll always need a child for the localhost.
 8224: 
 8225: 
 8226: =item Going to check on the children                
 8227: 
 8228: Parent is about to check on the health of the child processes.
 8229: Note that this is in response to a USR1 sent to the parent lond.
 8230: there may be one or more of the next two messages:
 8231: 
 8232: =item <pid> is dead                                 
 8233: 
 8234: A child that we have in our child hash as alive has evidently died.
 8235: 
 8236: =item  Child <pid> did not respond                   
 8237: 
 8238: In the health check the child <pid> did not update/produce a pid_.txt
 8239: file when sent it's USR1 signal.  That process is killed with a 9 signal, as it's
 8240: assumed to be hung in some un-fixable way.
 8241: 
 8242: =item Finished checking children                   
 8243:  
 8244: Master processs's USR1 processing is cojmplete.
 8245: 
 8246: =item (Red) CRITICAL: ------- Starting ------            
 8247: 
 8248: (There are more '-'s on either side).  Lond has forked itself off to 
 8249: form a new session and is about to start actual initialization.
 8250: 
 8251: =item (Green) Attempting to start child (<client>)       
 8252: 
 8253: Started a new child process for <client>.  Client is IO::Socket object
 8254: connected to the child.  This was as a result of a TCP/IP connection from a client.
 8255: 
 8256: =item Unable to determine who caller was, getpeername returned nothing
 8257:                                                   
 8258: In child process initialization.  either getpeername returned undef or
 8259: a zero sized object was returned.  Processing continues, but in my opinion,
 8260: this should be cause for the child to exit.
 8261: 
 8262: =item Unable to determine clientip                  
 8263: 
 8264: In child process initialization.  The peer address from getpeername was not defined.
 8265: The client address is stored as "Unavailable" and processing continues.
 8266: 
 8267: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
 8268:                                                   
 8269: In child initialization.  A good connectionw as received from <ip>.
 8270: 
 8271: =over 2
 8272: 
 8273: =item <name> 
 8274: 
 8275: is the name of the client from hosts.tab.
 8276: 
 8277: =item <type> 
 8278: 
 8279: Is the connection type which is either 
 8280: 
 8281: =over 2
 8282: 
 8283: =item manager 
 8284: 
 8285: The connection is from a manager node, not in hosts.tab
 8286: 
 8287: =item client  
 8288: 
 8289: the connection is from a non-manager in the hosts.tab
 8290: 
 8291: =item both
 8292: 
 8293: The connection is from a manager in the hosts.tab.
 8294: 
 8295: =back
 8296: 
 8297: =back
 8298: 
 8299: =item (Blue) Certificates not installed -- trying insecure auth
 8300: 
 8301: One of the certificate file, key file or
 8302: certificate authority file could not be found for a client attempting
 8303: SSL connection intiation.  COnnection will be attemptied in in-secure mode.
 8304: (this would be a system with an up to date lond that has not gotten a 
 8305: certificate from us).
 8306: 
 8307: =item (Green)  Successful local authentication            
 8308: 
 8309: A local connection successfully negotiated the encryption key. 
 8310: In this case the IDEA key is in a file (that is hopefully well protected).
 8311: 
 8312: =item (Green) Successful ssl authentication with <client>  
 8313: 
 8314: The client (<client> is the peer's name in hosts.tab), has successfully
 8315: negotiated an SSL connection with this child process.
 8316: 
 8317: =item (Green) Successful insecure authentication with <client>
 8318:                                                    
 8319: 
 8320: The client has successfully negotiated an  insecure connection withthe child process.
 8321: 
 8322: =item (Yellow) Attempted insecure connection disallowed    
 8323: 
 8324: The client attempted and failed to successfully negotiate a successful insecure
 8325: connection.  This can happen either because the variable londAllowInsecure is false
 8326: or undefined, or becuse the child did not successfully echo back the challenge
 8327: string.
 8328: 
 8329: 
 8330: =back
 8331: 
 8332: =back
 8333: 
 8334: 
 8335: =cut

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