File:  [LON-CAPA] / loncom / lond
Revision 1.490: download - view: text, annotated - select for diffs
Wed Apr 11 21:32:28 2012 UTC (12 years ago) by droeschl
Branches: MAIN
CVS tags: HEAD
*work in progress* BZ #6585
Outsource functional aspects of lond into a separate module Lond.pm.
Functionality in Lond.pm will be used in lond and lonnet.  lond will continue
to handle data transfer across the network while lonnet will handle requests
(e.g. dump) in cases where the request originates from the library server that
hosts the data. Thus avoiding serialization and IPC through several sockets
(lonnet <unix socket> lonc <inet socket> lond <- file.db becomes
lonnet <- file.db).
This greatly improves performance on library servers that are also used as
access servers.

See Bugzilla 6585 for details.

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

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