File:  [LON-CAPA] / loncom / lond
Revision 1.485: download - view: text, annotated - select for diffs
Thu Nov 17 18:22:36 2011 UTC (12 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: language_hyphenation_merge, language_hyphenation, HEAD, BZ4492-merge, BZ4492-feature_horizontal_radioresponse, BZ4492-feature_Support_horizontal_radioresponse, BZ4492-Support_horizontal_radioresponse
- In &dump_course_id_handler(), make filtering of courses by owner work
  when course owner is the only filter.

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

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