File:  [LON-CAPA] / loncom / lond
Revision 1.450: download - view: text, annotated - select for diffs
Mon Jul 26 21:52:10 2010 UTC (13 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- For Course/Community roles requiring a specific minimum LON-CAPA version,
  where server hosting session is not running a recent enough version:
  (a) If server hosting session is running 2.10 or later, switch server
      link shown for role on roles/courses screen.
      - switch is to a server in user's domain (if any have required version)
        or to a server in course's domain (if any have required version).
  (b) For servers hosting sessions running 2.9 or earlier, lond on the
      user's home machine will only supply information for roles which
      can be run on the version on the server hosting the session.

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

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