File:  [LON-CAPA] / loncom / lond
Revision 1.489.2.19: download - view: text, annotated - select for diffs
Sat Aug 6 20:05:01 2016 UTC (7 years, 8 months ago) by raeburn
Branches: version_2_11_X
- For 2.11
  - Backport 1.520

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

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