File:  [LON-CAPA] / loncom / lond
Revision 1.517: download - view: text, annotated - select for diffs
Sun Jan 31 21:25:53 2016 UTC (8 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Score upload form supports identification of a user based on clicker ID,
  for Course Coordinators who prefer not to use LON-CAPA's in-built
  "Process Clicker" utility.
- clickers.db file on a library server contains key = value pairs, where key
  is (escaped) clicker ID, and value is (escaped) comma-separated list of
  usernames who registered that particular clicker ID.
- bi-nightly run of searchcat.pl will update clickers.db file.

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

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