File:  [LON-CAPA] / loncom / lond
Revision 1.410.2.2: download - view: text, annotated - select for diffs
Fri Oct 9 12:36:10 2009 UTC (14 years, 6 months ago) by raeburn
Branches: version_2_8_X
CVS tags: version_2_8_2
Diff to branchpoint 1.410: preferred, unified
- Backport 1.428.

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

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