File:  [LON-CAPA] / loncom / lond
Revision 1.489.2.8: download - view: text, annotated - select for diffs
Sat Aug 10 14:20:52 2013 UTC (10 years, 8 months ago) by raeburn
Branches: version_2_11_X
CVS tags: version_2_11_0_RC1
- For 2.11
  - Backport 1.502.

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

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