File:  [LON-CAPA] / loncom / lond
Revision 1.489.2.43.2.2: download - view: text, annotated - select for diffs
Mon Feb 7 12:12:07 2022 UTC (2 years, 2 months ago) by raeburn
Branches: version_2_11_4_msu
- For 2.11.4 (modified)
  Include changes in 1.572

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

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