File:  [LON-CAPA] / loncom / lond
Revision 1.447: download - view: text, annotated - select for diffs
Sat Jul 17 20:01:56 2010 UTC (13 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Following the switch to 2.10, domains may prefer that their users do not have sessions hosted on older versions of LON-CAPA.
- Domain Coordinators can control:
  (a) where their users may have sessions hosted (by domain and/or LON-CAPA version).
  (b) which other domains will have user sessions hosted on servers in the domain.

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

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