File:  [LON-CAPA] / loncom / lond
Revision 1.489.2.31: download - view: text, annotated - select for diffs
Fri Jul 26 20:19:35 2019 UTC (4 years, 9 months ago) by raeburn
Branches: version_2_11_X
- For 2.11
  Backport 1.550, 1.559

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

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