File:  [LON-CAPA] / loncom / lond
Revision 1.397: download - view: text, annotated - select for diffs
Fri Feb 29 21:01:03 2008 UTC (16 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Replace "selfenroll" with "selfcreate" in various subroutine names, and modify text which refers to self-enrollment to refer to user creation of accounts.
- Intended to clarify that these procedures relate to a user creating his/her own account in a LON-CAPA domain as opposed to self-enrolling in a course, once the user has an account.

    1: #!/usr/bin/perl
    2: # The LearningOnline Network
    3: # lond "LON Daemon" Server (port "LOND" 5663)
    4: #
    5: # $Id: lond,v 1.397 2008/02/29 21:01:03 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.397 $'; #' 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: #
 1225: #   du  - list the disk usuage of a directory recursively. 
 1226: #    
 1227: #   note: stolen code from the ls file handler
 1228: #   under construction by Rick Banghart 
 1229: #    .
 1230: # Parameters:
 1231: #    $cmd        - The command that dispatched us (du).
 1232: #    $ududir     - The directory path to list... I'm not sure what this
 1233: #                  is relative as things like ls:. return e.g.
 1234: #                  no_such_dir.
 1235: #    $client     - Socket open on the client.
 1236: # Returns:
 1237: #     1 - indicating that the daemon should not disconnect.
 1238: # Side Effects:
 1239: #   The reply is written to  $client.
 1240: #
 1241: sub du_handler {
 1242:     my ($cmd, $ududir, $client) = @_;
 1243:     ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
 1244:     my $userinput = "$cmd:$ududir";
 1245: 
 1246:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
 1247: 	&Failure($client,"refused\n","$cmd:$ududir");
 1248: 	return 1;
 1249:     }
 1250:     #  Since $ududir could have some nasties in it,
 1251:     #  we will require that ududir is a valid
 1252:     #  directory.  Just in case someone tries to
 1253:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
 1254:     #  etc.
 1255:     #
 1256:     if (-d $ududir) {
 1257: 	my $total_size=0;
 1258: 	my $code=sub { 
 1259: 	    if ($_=~/\.\d+\./) { return;} 
 1260: 	    if ($_=~/\.meta$/) { return;}
 1261: 	    if (-d $_)         { return;}
 1262: 	    $total_size+=(stat($_))[7];
 1263: 	};
 1264: 	chdir($ududir);
 1265: 	find($code,$ududir);
 1266: 	$total_size=int($total_size/1024);
 1267: 	&Reply($client,\$total_size,"$cmd:$ududir");
 1268:     } else {
 1269: 	&Failure($client, "bad_directory:$ududir\n","$cmd:$ududir"); 
 1270:     }
 1271:     return 1;
 1272: }
 1273: &register_handler("du", \&du_handler, 0, 1, 0);
 1274: 
 1275: #
 1276: # The ls_handler routine should be considered obosolete and is retained
 1277: # for communication with legacy servers.  Please see the ls2_handler.
 1278: #
 1279: #   ls  - list the contents of a directory.  For each file in the
 1280: #    selected directory the filename followed by the full output of
 1281: #    the stat function is returned.  The returned info for each
 1282: #    file are separated by ':'.  The stat fields are separated by &'s.
 1283: # Parameters:
 1284: #    $cmd        - The command that dispatched us (ls).
 1285: #    $ulsdir     - The directory path to list... I'm not sure what this
 1286: #                  is relative as things like ls:. return e.g.
 1287: #                  no_such_dir.
 1288: #    $client     - Socket open on the client.
 1289: # Returns:
 1290: #     1 - indicating that the daemon should not disconnect.
 1291: # Side Effects:
 1292: #   The reply is written to  $client.
 1293: #
 1294: sub ls_handler {
 1295:     # obsoleted by ls2_handler
 1296:     my ($cmd, $ulsdir, $client) = @_;
 1297: 
 1298:     my $userinput = "$cmd:$ulsdir";
 1299: 
 1300:     my $obs;
 1301:     my $rights;
 1302:     my $ulsout='';
 1303:     my $ulsfn;
 1304:     if (-e $ulsdir) {
 1305: 	if(-d $ulsdir) {
 1306: 	    if (opendir(LSDIR,$ulsdir)) {
 1307: 		while ($ulsfn=readdir(LSDIR)) {
 1308: 		    undef($obs);
 1309: 		    undef($rights); 
 1310: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1311: 		    #We do some obsolete checking here
 1312: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
 1313: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
 1314: 			my @obsolete=<FILE>;
 1315: 			foreach my $obsolete (@obsolete) {
 1316: 			    if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
 1317: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
 1318: 			}
 1319: 		    }
 1320: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
 1321: 		    if($obs eq '1') { $ulsout.="&1"; }
 1322: 		    else { $ulsout.="&0"; }
 1323: 		    if($rights eq '1') { $ulsout.="&1:"; }
 1324: 		    else { $ulsout.="&0:"; }
 1325: 		}
 1326: 		closedir(LSDIR);
 1327: 	    }
 1328: 	} else {
 1329: 	    my @ulsstats=stat($ulsdir);
 1330: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1331: 	}
 1332:     } else {
 1333: 	$ulsout='no_such_dir';
 1334:     }
 1335:     if ($ulsout eq '') { $ulsout='empty'; }
 1336:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
 1337:     
 1338:     return 1;
 1339: 
 1340: }
 1341: &register_handler("ls", \&ls_handler, 0, 1, 0);
 1342: 
 1343: #
 1344: # Please also see the ls_handler, which this routine obosolets.
 1345: # ls2_handler differs from ls_handler in that it escapes its return 
 1346: # values before concatenating them together with ':'s.
 1347: #
 1348: #   ls2  - list the contents of a directory.  For each file in the
 1349: #    selected directory the filename followed by the full output of
 1350: #    the stat function is returned.  The returned info for each
 1351: #    file are separated by ':'.  The stat fields are separated by &'s.
 1352: # Parameters:
 1353: #    $cmd        - The command that dispatched us (ls).
 1354: #    $ulsdir     - The directory path to list... I'm not sure what this
 1355: #                  is relative as things like ls:. return e.g.
 1356: #                  no_such_dir.
 1357: #    $client     - Socket open on the client.
 1358: # Returns:
 1359: #     1 - indicating that the daemon should not disconnect.
 1360: # Side Effects:
 1361: #   The reply is written to  $client.
 1362: #
 1363: sub ls2_handler {
 1364:     my ($cmd, $ulsdir, $client) = @_;
 1365: 
 1366:     my $userinput = "$cmd:$ulsdir";
 1367: 
 1368:     my $obs;
 1369:     my $rights;
 1370:     my $ulsout='';
 1371:     my $ulsfn;
 1372:     if (-e $ulsdir) {
 1373:         if(-d $ulsdir) {
 1374:             if (opendir(LSDIR,$ulsdir)) {
 1375:                 while ($ulsfn=readdir(LSDIR)) {
 1376:                     undef($obs);
 1377: 		    undef($rights); 
 1378:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1379:                     #We do some obsolete checking here
 1380:                     if(-e $ulsdir.'/'.$ulsfn.".meta") { 
 1381:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
 1382:                         my @obsolete=<FILE>;
 1383:                         foreach my $obsolete (@obsolete) {
 1384:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
 1385:                             if($obsolete =~ m|(<copyright>)(default)|) {
 1386:                                 $rights = 1;
 1387:                             }
 1388:                         }
 1389:                     }
 1390:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
 1391:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1392:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1393:                     $ulsout.= &escape($tmp).':';
 1394:                 }
 1395:                 closedir(LSDIR);
 1396:             }
 1397:         } else {
 1398:             my @ulsstats=stat($ulsdir);
 1399:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1400:         }
 1401:     } else {
 1402:         $ulsout='no_such_dir';
 1403:    }
 1404:    if ($ulsout eq '') { $ulsout='empty'; }
 1405:    &Reply($client, \$ulsout, $userinput); # This supports debug logging.
 1406:    return 1;
 1407: }
 1408: &register_handler("ls2", \&ls2_handler, 0, 1, 0);
 1409: 
 1410: #   Process a reinit request.  Reinit requests that either
 1411: #   lonc or lond be reinitialized so that an updated 
 1412: #   host.tab or domain.tab can be processed.
 1413: #
 1414: # Parameters:
 1415: #      $cmd    - the actual keyword that invoked us.
 1416: #      $tail   - the tail of the request that invoked us.
 1417: #      $client - File descriptor connected to the client
 1418: #  Returns:
 1419: #      1       - Ok to continue processing.
 1420: #      0       - Program should exit
 1421: #  Implicit output:
 1422: #     a reply is sent to the client.
 1423: #
 1424: sub reinit_process_handler {
 1425:     my ($cmd, $tail, $client) = @_;
 1426:    
 1427:     my $userinput = "$cmd:$tail";
 1428:    
 1429:     my $cert = &GetCertificate($userinput);
 1430:     if(&ValidManager($cert)) {
 1431: 	chomp($userinput);
 1432: 	my $reply = &ReinitProcess($userinput);
 1433: 	&Reply( $client,  \$reply, $userinput);
 1434:     } else {
 1435: 	&Failure( $client, "refused\n", $userinput);
 1436:     }
 1437:     return 1;
 1438: }
 1439: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
 1440: 
 1441: #  Process the editing script for a table edit operation.
 1442: #  the editing operation must be encrypted and requested by
 1443: #  a manager host.
 1444: #
 1445: # Parameters:
 1446: #      $cmd    - the actual keyword that invoked us.
 1447: #      $tail   - the tail of the request that invoked us.
 1448: #      $client - File descriptor connected to the client
 1449: #  Returns:
 1450: #      1       - Ok to continue processing.
 1451: #      0       - Program should exit
 1452: #  Implicit output:
 1453: #     a reply is sent to the client.
 1454: #
 1455: sub edit_table_handler {
 1456:     my ($command, $tail, $client) = @_;
 1457:    
 1458:     my $userinput = "$command:$tail";
 1459: 
 1460:     my $cert = &GetCertificate($userinput);
 1461:     if(&ValidManager($cert)) {
 1462: 	my($filetype, $script) = split(/:/, $tail);
 1463: 	if (($filetype eq "hosts") || 
 1464: 	    ($filetype eq "domain")) {
 1465: 	    if($script ne "") {
 1466: 		&Reply($client,              # BUGBUG - EditFile
 1467: 		      &EditFile($userinput), #   could fail.
 1468: 		      $userinput);
 1469: 	    } else {
 1470: 		&Failure($client,"refused\n",$userinput);
 1471: 	    }
 1472: 	} else {
 1473: 	    &Failure($client,"refused\n",$userinput);
 1474: 	}
 1475:     } else {
 1476: 	&Failure($client,"refused\n",$userinput);
 1477:     }
 1478:     return 1;
 1479: }
 1480: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
 1481: 
 1482: #
 1483: #   Authenticate a user against the LonCAPA authentication
 1484: #   database.  Note that there are several authentication
 1485: #   possibilities:
 1486: #   - unix     - The user can be authenticated against the unix
 1487: #                password file.
 1488: #   - internal - The user can be authenticated against a purely 
 1489: #                internal per user password file.
 1490: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
 1491: #                ticket granting authority.
 1492: #   - user     - The person tailoring LonCAPA can supply a user authentication
 1493: #                mechanism that is per system.
 1494: #
 1495: # Parameters:
 1496: #    $cmd      - The command that got us here.
 1497: #    $tail     - Tail of the command (remaining parameters).
 1498: #    $client   - File descriptor connected to client.
 1499: # Returns
 1500: #     0        - Requested to exit, caller should shut down.
 1501: #     1        - Continue processing.
 1502: # Implicit inputs:
 1503: #    The authentication systems describe above have their own forms of implicit
 1504: #    input into the authentication process that are described above.
 1505: #
 1506: sub authenticate_handler {
 1507:     my ($cmd, $tail, $client) = @_;
 1508: 
 1509:     
 1510:     #  Regenerate the full input line 
 1511:     
 1512:     my $userinput  = $cmd.":".$tail;
 1513:     
 1514:     #  udom    - User's domain.
 1515:     #  uname   - Username.
 1516:     #  upass   - User's password.
 1517:     #  checkdefauth - Pass to validate_user() to try authentication
 1518:     #                 with default auth type(s) if no user account.
 1519:     
 1520:     my ($udom, $uname, $upass, $checkdefauth)=split(/:/,$tail);
 1521:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass");
 1522:     chomp($upass);
 1523:     $upass=&unescape($upass);
 1524: 
 1525:     my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
 1526:     if($pwdcorrect) {
 1527: 	&Reply( $client, "authorized\n", $userinput);
 1528: 	#
 1529: 	#  Bad credentials: Failed to authorize
 1530: 	#
 1531:     } else {
 1532: 	&Failure( $client, "non_authorized\n", $userinput);
 1533:     }
 1534: 
 1535:     return 1;
 1536: }
 1537: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
 1538: 
 1539: #
 1540: #   Change a user's password.  Note that this function is complicated by
 1541: #   the fact that a user may be authenticated in more than one way:
 1542: #   At present, we are not able to change the password for all types of
 1543: #   authentication methods.  Only for:
 1544: #      unix    - unix password or shadow passoword style authentication.
 1545: #      local   - Locally written authentication mechanism.
 1546: #   For now, kerb4 and kerb5 password changes are not supported and result
 1547: #   in an error.
 1548: # FUTURE WORK:
 1549: #    Support kerberos passwd changes?
 1550: # Parameters:
 1551: #    $cmd      - The command that got us here.
 1552: #    $tail     - Tail of the command (remaining parameters).
 1553: #    $client   - File descriptor connected to client.
 1554: # Returns
 1555: #     0        - Requested to exit, caller should shut down.
 1556: #     1        - Continue processing.
 1557: # Implicit inputs:
 1558: #    The authentication systems describe above have their own forms of implicit
 1559: #    input into the authentication process that are described above.
 1560: sub change_password_handler {
 1561:     my ($cmd, $tail, $client) = @_;
 1562: 
 1563:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
 1564: 
 1565:     #
 1566:     #  udom  - user's domain.
 1567:     #  uname - Username.
 1568:     #  upass - Current password.
 1569:     #  npass - New password.
 1570:     #  context - Context in which this was called 
 1571:     #            (preferences or reset_by_email).
 1572:    
 1573:     my ($udom,$uname,$upass,$npass,$context)=split(/:/,$tail);
 1574: 
 1575:     $upass=&unescape($upass);
 1576:     $npass=&unescape($npass);
 1577:     &Debug("Trying to change password for $uname");
 1578: 
 1579:     # First require that the user can be authenticated with their
 1580:     # old password unless context was 'reset_by_email':
 1581:     
 1582:     my $validated;
 1583:     if ($context eq 'reset_by_email') {
 1584:         $validated = 1;
 1585:     } else {
 1586:         $validated = &validate_user($udom, $uname, $upass);
 1587:     }
 1588:     if($validated) {
 1589: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
 1590: 	
 1591: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
 1592: 	if ($howpwd eq 'internal') {
 1593: 	    &Debug("internal auth");
 1594: 	    my $salt=time;
 1595: 	    $salt=substr($salt,6,2);
 1596: 	    my $ncpass=crypt($npass,$salt);
 1597: 	    if(&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
 1598: 		&logthis("Result of password change for "
 1599: 			 ."$uname: pwchange_success");
 1600: 		&Reply($client, "ok\n", $userinput);
 1601: 	    } else {
 1602: 		&logthis("Unable to open $uname passwd "               
 1603: 			 ."to change password");
 1604: 		&Failure( $client, "non_authorized\n",$userinput);
 1605: 	    }
 1606: 	} elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
 1607: 	    my $result = &change_unix_password($uname, $npass);
 1608: 	    &logthis("Result of password change for $uname: ".
 1609: 		     $result);
 1610: 	    &Reply($client, \$result, $userinput);
 1611: 	} else {
 1612: 	    # this just means that the current password mode is not
 1613: 	    # one we know how to change (e.g the kerberos auth modes or
 1614: 	    # locally written auth handler).
 1615: 	    #
 1616: 	    &Failure( $client, "auth_mode_error\n", $userinput);
 1617: 	}  
 1618: 	
 1619:     } else {
 1620: 	&Failure( $client, "non_authorized\n", $userinput);
 1621:     }
 1622: 
 1623:     return 1;
 1624: }
 1625: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
 1626: 
 1627: #
 1628: #   Create a new user.  User in this case means a lon-capa user.
 1629: #   The user must either already exist in some authentication realm
 1630: #   like kerberos or the /etc/passwd.  If not, a user completely local to
 1631: #   this loncapa system is created.
 1632: #
 1633: # Parameters:
 1634: #    $cmd      - The command that got us here.
 1635: #    $tail     - Tail of the command (remaining parameters).
 1636: #    $client   - File descriptor connected to client.
 1637: # Returns
 1638: #     0        - Requested to exit, caller should shut down.
 1639: #     1        - Continue processing.
 1640: # Implicit inputs:
 1641: #    The authentication systems describe above have their own forms of implicit
 1642: #    input into the authentication process that are described above.
 1643: sub add_user_handler {
 1644: 
 1645:     my ($cmd, $tail, $client) = @_;
 1646: 
 1647: 
 1648:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
 1649:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
 1650: 
 1651:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
 1652: 
 1653: 
 1654:     if($udom eq $currentdomainid) { # Reject new users for other domains...
 1655: 	
 1656: 	my $oldumask=umask(0077);
 1657: 	chomp($npass);
 1658: 	$npass=&unescape($npass);
 1659: 	my $passfilename  = &password_path($udom, $uname);
 1660: 	&Debug("Password file created will be:".$passfilename);
 1661: 	if (-e $passfilename) {
 1662: 	    &Failure( $client, "already_exists\n", $userinput);
 1663: 	} else {
 1664: 	    my $fperror='';
 1665: 	    if (!&mkpath($passfilename)) {
 1666: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
 1667: 		    ."makeuser";
 1668: 	    }
 1669: 	    unless ($fperror) {
 1670: 		my $result=&make_passwd_file($uname, $umode,$npass, $passfilename);
 1671: 		&Reply($client,\$result, $userinput);     #BUGBUG - could be fail
 1672: 	    } else {
 1673: 		&Failure($client, \$fperror, $userinput);
 1674: 	    }
 1675: 	}
 1676: 	umask($oldumask);
 1677:     }  else {
 1678: 	&Failure($client, "not_right_domain\n",
 1679: 		$userinput);	# Even if we are multihomed.
 1680:     
 1681:     }
 1682:     return 1;
 1683: 
 1684: }
 1685: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
 1686: 
 1687: #
 1688: #   Change the authentication method of a user.  Note that this may
 1689: #   also implicitly change the user's password if, for example, the user is
 1690: #   joining an existing authentication realm.  Known authentication realms at
 1691: #   this time are:
 1692: #    internal   - Purely internal password file (only loncapa knows this user)
 1693: #    local      - Institutionally written authentication module.
 1694: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
 1695: #    kerb4      - kerberos version 4
 1696: #    kerb5      - kerberos version 5
 1697: #
 1698: # Parameters:
 1699: #    $cmd      - The command that got us here.
 1700: #    $tail     - Tail of the command (remaining parameters).
 1701: #    $client   - File descriptor connected to client.
 1702: # Returns
 1703: #     0        - Requested to exit, caller should shut down.
 1704: #     1        - Continue processing.
 1705: # Implicit inputs:
 1706: #    The authentication systems describe above have their own forms of implicit
 1707: #    input into the authentication process that are described above.
 1708: # NOTE:
 1709: #   This is also used to change the authentication credential values (e.g. passwd).
 1710: #   
 1711: #
 1712: sub change_authentication_handler {
 1713: 
 1714:     my ($cmd, $tail, $client) = @_;
 1715:    
 1716:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
 1717: 
 1718:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
 1719:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
 1720:     if ($udom ne $currentdomainid) {
 1721: 	&Failure( $client, "not_right_domain\n", $client);
 1722:     } else {
 1723: 	
 1724: 	chomp($npass);
 1725: 	
 1726: 	$npass=&unescape($npass);
 1727: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
 1728: 	my $passfilename = &password_path($udom, $uname);
 1729: 	if ($passfilename) {	# Not allowed to create a new user!!
 1730: 	    # If just changing the unix passwd. need to arrange to run
 1731: 	    # passwd since otherwise make_passwd_file will run
 1732: 	    # lcuseradd which fails if an account already exists
 1733: 	    # (to prevent an unscrupulous LONCAPA admin from stealing
 1734: 	    # an existing account by overwriting it as a LonCAPA account).
 1735: 
 1736: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
 1737: 		my $result = &change_unix_password($uname, $npass);
 1738: 		&logthis("Result of password change for $uname: ".$result);
 1739: 		if ($result eq "ok") {
 1740: 		    &Reply($client, \$result);
 1741: 		} else {
 1742: 		    &Failure($client, \$result);
 1743: 		}
 1744: 	    } else {
 1745: 		my $result=&make_passwd_file($uname, $umode,$npass,$passfilename);
 1746: 		#
 1747: 		#  If the current auth mode is internal, and the old auth mode was
 1748: 		#  unix, or krb*,  and the user is an author for this domain,
 1749: 		#  re-run manage_permissions for that role in order to be able
 1750: 		#  to take ownership of the construction space back to www:www
 1751: 		#
 1752: 		
 1753: 		
 1754: 		if( (($oldauth =~ /^unix/) && ($umode eq "internal")) ||
 1755: 		    (($oldauth =~ /^internal/) && ($umode eq "unix")) ) { 
 1756: 		    if(&is_author($udom, $uname)) {
 1757: 			&Debug(" Need to manage author permissions...");
 1758: 			&manage_permissions("/$udom/_au", $udom, $uname, "$umode:");
 1759: 		    }
 1760: 		}
 1761: 		&Reply($client, \$result, $userinput);
 1762: 	    }
 1763: 	       
 1764: 
 1765: 	} else {	       
 1766: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
 1767: 	}
 1768:     }
 1769:     return 1;
 1770: }
 1771: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
 1772: 
 1773: #
 1774: #   Determines if this is the home server for a user.  The home server
 1775: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
 1776: #   to do is determine if this file exists.
 1777: #
 1778: # Parameters:
 1779: #    $cmd      - The command that got us here.
 1780: #    $tail     - Tail of the command (remaining parameters).
 1781: #    $client   - File descriptor connected to client.
 1782: # Returns
 1783: #     0        - Requested to exit, caller should shut down.
 1784: #     1        - Continue processing.
 1785: # Implicit inputs:
 1786: #    The authentication systems describe above have their own forms of implicit
 1787: #    input into the authentication process that are described above.
 1788: #
 1789: sub is_home_handler {
 1790:     my ($cmd, $tail, $client) = @_;
 1791:    
 1792:     my $userinput  = "$cmd:$tail";
 1793:    
 1794:     my ($udom,$uname)=split(/:/,$tail);
 1795:     chomp($uname);
 1796:     my $passfile = &password_filename($udom, $uname);
 1797:     if($passfile) {
 1798: 	&Reply( $client, "found\n", $userinput);
 1799:     } else {
 1800: 	&Failure($client, "not_found\n", $userinput);
 1801:     }
 1802:     return 1;
 1803: }
 1804: &register_handler("home", \&is_home_handler, 0,1,0);
 1805: 
 1806: #
 1807: #   Process an update request for a resource?? I think what's going on here is
 1808: #   that a resource has been modified that we hold a subscription to.
 1809: #   If the resource is not local, then we must update, or at least invalidate our
 1810: #   cached copy of the resource. 
 1811: #   FUTURE WORK:
 1812: #      I need to look at this logic carefully.  My druthers would be to follow
 1813: #      typical caching logic, and simple invalidate the cache, drop any subscription
 1814: #      an let the next fetch start the ball rolling again... however that may
 1815: #      actually be more difficult than it looks given the complex web of
 1816: #      proxy servers.
 1817: # Parameters:
 1818: #    $cmd      - The command that got us here.
 1819: #    $tail     - Tail of the command (remaining parameters).
 1820: #    $client   - File descriptor connected to client.
 1821: # Returns
 1822: #     0        - Requested to exit, caller should shut down.
 1823: #     1        - Continue processing.
 1824: # Implicit inputs:
 1825: #    The authentication systems describe above have their own forms of implicit
 1826: #    input into the authentication process that are described above.
 1827: #
 1828: sub update_resource_handler {
 1829: 
 1830:     my ($cmd, $tail, $client) = @_;
 1831:    
 1832:     my $userinput = "$cmd:$tail";
 1833:    
 1834:     my $fname= $tail;		# This allows interactive testing
 1835: 
 1836: 
 1837:     my $ownership=ishome($fname);
 1838:     if ($ownership eq 'not_owner') {
 1839: 	if (-e $fname) {
 1840: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
 1841: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
 1842: 	    my $now=time;
 1843: 	    my $since=$now-$atime;
 1844: 	    if ($since>$perlvar{'lonExpire'}) {
 1845: 		my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
 1846: 		&devalidate_meta_cache($fname);
 1847: 		unlink("$fname");
 1848: 		unlink("$fname.meta");
 1849: 	    } else {
 1850: 		my $transname="$fname.in.transfer";
 1851: 		my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
 1852: 		my $response;
 1853: 		alarm(120);
 1854: 		{
 1855: 		    my $ua=new LWP::UserAgent;
 1856: 		    my $request=new HTTP::Request('GET',"$remoteurl");
 1857: 		    $response=$ua->request($request,$transname);
 1858: 		}
 1859: 		alarm(0);
 1860: 		if ($response->is_error()) {
 1861: 		    unlink($transname);
 1862: 		    my $message=$response->status_line;
 1863: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
 1864: 		} else {
 1865: 		    if ($remoteurl!~/\.meta$/) {
 1866: 			alarm(120);
 1867: 			{
 1868: 			    my $ua=new LWP::UserAgent;
 1869: 			    my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1870: 			    my $mresponse=$ua->request($mrequest,$fname.'.meta');
 1871: 			    if ($mresponse->is_error()) {
 1872: 				unlink($fname.'.meta');
 1873: 			    }
 1874: 			}
 1875: 			alarm(0);
 1876: 		    }
 1877: 		    rename($transname,$fname);
 1878: 		    &devalidate_meta_cache($fname);
 1879: 		}
 1880: 	    }
 1881: 	    &Reply( $client, "ok\n", $userinput);
 1882: 	} else {
 1883: 	    &Failure($client, "not_found\n", $userinput);
 1884: 	}
 1885:     } else {
 1886: 	&Failure($client, "rejected\n", $userinput);
 1887:     }
 1888:     return 1;
 1889: }
 1890: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
 1891: 
 1892: sub devalidate_meta_cache {
 1893:     my ($url) = @_;
 1894:     use Cache::Memcached;
 1895:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
 1896:     $url = &Apache::lonnet::declutter($url);
 1897:     $url =~ s-\.meta$--;
 1898:     my $id = &escape('meta:'.$url);
 1899:     $memcache->delete($id);
 1900: }
 1901: 
 1902: #
 1903: #   Fetch a user file from a remote server to the user's home directory
 1904: #   userfiles subdir.
 1905: # Parameters:
 1906: #    $cmd      - The command that got us here.
 1907: #    $tail     - Tail of the command (remaining parameters).
 1908: #    $client   - File descriptor connected to client.
 1909: # Returns
 1910: #     0        - Requested to exit, caller should shut down.
 1911: #     1        - Continue processing.
 1912: #
 1913: sub fetch_user_file_handler {
 1914: 
 1915:     my ($cmd, $tail, $client) = @_;
 1916: 
 1917:     my $userinput = "$cmd:$tail";
 1918:     my $fname           = $tail;
 1919:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
 1920:     my $udir=&propath($udom,$uname).'/userfiles';
 1921:     unless (-e $udir) {
 1922: 	mkdir($udir,0770); 
 1923:     }
 1924:     Debug("fetch user file for $fname");
 1925:     if (-e $udir) {
 1926: 	$ufile=~s/^[\.\~]+//;
 1927: 
 1928: 	# IF necessary, create the path right down to the file.
 1929: 	# Note that any regular files in the way of this path are
 1930: 	# wiped out to deal with some earlier folly of mine.
 1931: 
 1932: 	if (!&mkpath($udir.'/'.$ufile)) {
 1933: 	    &Failure($client, "unable_to_create\n", $userinput);	    
 1934: 	}
 1935: 
 1936: 	my $destname=$udir.'/'.$ufile;
 1937: 	my $transname=$udir.'/'.$ufile.'.in.transit';
 1938: 	my $remoteurl='http://'.$clientip.'/userfiles/'.$fname;
 1939: 	my $response;
 1940: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
 1941: 	alarm(120);
 1942: 	{
 1943: 	    my $ua=new LWP::UserAgent;
 1944: 	    my $request=new HTTP::Request('GET',"$remoteurl");
 1945: 	    $response=$ua->request($request,$transname);
 1946: 	}
 1947: 	alarm(0);
 1948: 	if ($response->is_error()) {
 1949: 	    unlink($transname);
 1950: 	    my $message=$response->status_line;
 1951: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
 1952: 	    &Failure($client, "failed\n", $userinput);
 1953: 	} else {
 1954: 	    Debug("Renaming $transname to $destname");
 1955: 	    if (!rename($transname,$destname)) {
 1956: 		&logthis("Unable to move $transname to $destname");
 1957: 		unlink($transname);
 1958: 		&Failure($client, "failed\n", $userinput);
 1959: 	    } else {
 1960: 		&Reply($client, "ok\n", $userinput);
 1961: 	    }
 1962: 	}   
 1963:     } else {
 1964: 	&Failure($client, "not_home\n", $userinput);
 1965:     }
 1966:     return 1;
 1967: }
 1968: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
 1969: 
 1970: #
 1971: #   Remove a file from a user's home directory userfiles subdirectory.
 1972: # Parameters:
 1973: #    cmd   - the Lond request keyword that got us here.
 1974: #    tail  - the part of the command past the keyword.
 1975: #    client- File descriptor connected with the client.
 1976: #
 1977: # Returns:
 1978: #    1    - Continue processing.
 1979: sub remove_user_file_handler {
 1980:     my ($cmd, $tail, $client) = @_;
 1981: 
 1982:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
 1983: 
 1984:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
 1985:     if ($ufile =~m|/\.\./|) {
 1986: 	# any files paths with /../ in them refuse 
 1987: 	# to deal with
 1988: 	&Failure($client, "refused\n", "$cmd:$tail");
 1989:     } else {
 1990: 	my $udir = &propath($udom,$uname);
 1991: 	if (-e $udir) {
 1992: 	    my $file=$udir.'/userfiles/'.$ufile;
 1993: 	    if (-e $file) {
 1994: 		#
 1995: 		#   If the file is a regular file unlink is fine...
 1996: 		#   However it's possible the client wants a dir.
 1997: 		#   removed, in which case rmdir is more approprate:
 1998: 		#
 1999: 	        if (-f $file){
 2000: 		    unlink($file);
 2001: 		} elsif(-d $file) {
 2002: 		    rmdir($file);
 2003: 		}
 2004: 		if (-e $file) {
 2005: 		    #  File is still there after we deleted it ?!?
 2006: 
 2007: 		    &Failure($client, "failed\n", "$cmd:$tail");
 2008: 		} else {
 2009: 		    &Reply($client, "ok\n", "$cmd:$tail");
 2010: 		}
 2011: 	    } else {
 2012: 		&Failure($client, "not_found\n", "$cmd:$tail");
 2013: 	    }
 2014: 	} else {
 2015: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 2016: 	}
 2017:     }
 2018:     return 1;
 2019: }
 2020: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
 2021: 
 2022: #
 2023: #   make a directory in a user's home directory userfiles subdirectory.
 2024: # Parameters:
 2025: #    cmd   - the Lond request keyword that got us here.
 2026: #    tail  - the part of the command past the keyword.
 2027: #    client- File descriptor connected with the client.
 2028: #
 2029: # Returns:
 2030: #    1    - Continue processing.
 2031: sub mkdir_user_file_handler {
 2032:     my ($cmd, $tail, $client) = @_;
 2033: 
 2034:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
 2035:     $dir=&unescape($dir);
 2036:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
 2037:     if ($ufile =~m|/\.\./|) {
 2038: 	# any files paths with /../ in them refuse 
 2039: 	# to deal with
 2040: 	&Failure($client, "refused\n", "$cmd:$tail");
 2041:     } else {
 2042: 	my $udir = &propath($udom,$uname);
 2043: 	if (-e $udir) {
 2044: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
 2045: 	    if (!&mkpath($newdir)) {
 2046: 		&Failure($client, "failed\n", "$cmd:$tail");
 2047: 	    }
 2048: 	    &Reply($client, "ok\n", "$cmd:$tail");
 2049: 	} else {
 2050: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 2051: 	}
 2052:     }
 2053:     return 1;
 2054: }
 2055: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
 2056: 
 2057: #
 2058: #   rename a file in a user's home directory userfiles subdirectory.
 2059: # Parameters:
 2060: #    cmd   - the Lond request keyword that got us here.
 2061: #    tail  - the part of the command past the keyword.
 2062: #    client- File descriptor connected with the client.
 2063: #
 2064: # Returns:
 2065: #    1    - Continue processing.
 2066: sub rename_user_file_handler {
 2067:     my ($cmd, $tail, $client) = @_;
 2068: 
 2069:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
 2070:     $old=&unescape($old);
 2071:     $new=&unescape($new);
 2072:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
 2073: 	# any files paths with /../ in them refuse to deal with
 2074: 	&Failure($client, "refused\n", "$cmd:$tail");
 2075:     } else {
 2076: 	my $udir = &propath($udom,$uname);
 2077: 	if (-e $udir) {
 2078: 	    my $oldfile=$udir.'/userfiles/'.$old;
 2079: 	    my $newfile=$udir.'/userfiles/'.$new;
 2080: 	    if (-e $newfile) {
 2081: 		&Failure($client, "exists\n", "$cmd:$tail");
 2082: 	    } elsif (! -e $oldfile) {
 2083: 		&Failure($client, "not_found\n", "$cmd:$tail");
 2084: 	    } else {
 2085: 		if (!rename($oldfile,$newfile)) {
 2086: 		    &Failure($client, "failed\n", "$cmd:$tail");
 2087: 		} else {
 2088: 		    &Reply($client, "ok\n", "$cmd:$tail");
 2089: 		}
 2090: 	    }
 2091: 	} else {
 2092: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 2093: 	}
 2094:     }
 2095:     return 1;
 2096: }
 2097: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
 2098: 
 2099: #
 2100: #  Checks if the specified user has an active session on the server
 2101: #  return ok if so, not_found if not
 2102: #
 2103: # Parameters:
 2104: #   cmd      - The request keyword that dispatched to tus.
 2105: #   tail     - The tail of the request (colon separated parameters).
 2106: #   client   - Filehandle open on the client.
 2107: # Return:
 2108: #    1.
 2109: sub user_has_session_handler {
 2110:     my ($cmd, $tail, $client) = @_;
 2111: 
 2112:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
 2113:     
 2114:     &logthis("Looking for $udom $uname");
 2115:     opendir(DIR,$perlvar{'lonIDsDir'});
 2116:     my $filename;
 2117:     while ($filename=readdir(DIR)) {
 2118: 	last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
 2119:     }
 2120:     if ($filename) {
 2121: 	&Reply($client, "ok\n", "$cmd:$tail");
 2122:     } else {
 2123: 	&Failure($client, "not_found\n", "$cmd:$tail");
 2124:     }
 2125:     return 1;
 2126: 
 2127: }
 2128: &register_handler("userhassession", \&user_has_session_handler, 0,1,0);
 2129: 
 2130: #
 2131: #  Authenticate access to a user file by checking that the token the user's 
 2132: #  passed also exists in their session file
 2133: #
 2134: # Parameters:
 2135: #   cmd      - The request keyword that dispatched to tus.
 2136: #   tail     - The tail of the request (colon separated parameters).
 2137: #   client   - Filehandle open on the client.
 2138: # Return:
 2139: #    1.
 2140: sub token_auth_user_file_handler {
 2141:     my ($cmd, $tail, $client) = @_;
 2142: 
 2143:     my ($fname, $session) = split(/:/, $tail);
 2144:     
 2145:     chomp($session);
 2146:     my $reply="non_auth";
 2147:     my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
 2148:     if (open(ENVIN,"$file")) {
 2149: 	flock(ENVIN,LOCK_SH);
 2150: 	tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
 2151: 	if (exists($disk_env{"userfile.$fname"})) {
 2152: 	    $reply="ok";
 2153: 	} else {
 2154: 	    foreach my $envname (keys(%disk_env)) {
 2155: 		if ($envname=~ m|^userfile\.\Q$fname\E|) {
 2156: 		    $reply="ok";
 2157: 		    last;
 2158: 		}
 2159: 	    }
 2160: 	}
 2161: 	untie(%disk_env);
 2162: 	close(ENVIN);
 2163: 	&Reply($client, \$reply, "$cmd:$tail");
 2164:     } else {
 2165: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
 2166:     }
 2167:     return 1;
 2168: 
 2169: }
 2170: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
 2171: 
 2172: #
 2173: #   Unsubscribe from a resource.
 2174: #
 2175: # Parameters:
 2176: #    $cmd      - The command that got us here.
 2177: #    $tail     - Tail of the command (remaining parameters).
 2178: #    $client   - File descriptor connected to client.
 2179: # Returns
 2180: #     0        - Requested to exit, caller should shut down.
 2181: #     1        - Continue processing.
 2182: #
 2183: sub unsubscribe_handler {
 2184:     my ($cmd, $tail, $client) = @_;
 2185: 
 2186:     my $userinput= "$cmd:$tail";
 2187:     
 2188:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
 2189: 
 2190:     &Debug("Unsubscribing $fname");
 2191:     if (-e $fname) {
 2192: 	&Debug("Exists");
 2193: 	&Reply($client, &unsub($fname,$clientip), $userinput);
 2194:     } else {
 2195: 	&Failure($client, "not_found\n", $userinput);
 2196:     }
 2197:     return 1;
 2198: }
 2199: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
 2200: 
 2201: #   Subscribe to a resource
 2202: #
 2203: # Parameters:
 2204: #    $cmd      - The command that got us here.
 2205: #    $tail     - Tail of the command (remaining parameters).
 2206: #    $client   - File descriptor connected to client.
 2207: # Returns
 2208: #     0        - Requested to exit, caller should shut down.
 2209: #     1        - Continue processing.
 2210: #
 2211: sub subscribe_handler {
 2212:     my ($cmd, $tail, $client)= @_;
 2213: 
 2214:     my $userinput  = "$cmd:$tail";
 2215: 
 2216:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
 2217: 
 2218:     return 1;
 2219: }
 2220: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
 2221: 
 2222: #
 2223: #   Determine the latest version of a resource (it looks for the highest
 2224: #   past version and then returns that +1)
 2225: #
 2226: # Parameters:
 2227: #    $cmd      - The command that got us here.
 2228: #    $tail     - Tail of the command (remaining parameters).
 2229: #                 (Should consist of an absolute path to a file)
 2230: #    $client   - File descriptor connected to client.
 2231: # Returns
 2232: #     0        - Requested to exit, caller should shut down.
 2233: #     1        - Continue processing.
 2234: #
 2235: sub current_version_handler {
 2236:     my ($cmd, $tail, $client) = @_;
 2237: 
 2238:     my $userinput= "$cmd:$tail";
 2239:    
 2240:     my $fname   = $tail;
 2241:     &Reply( $client, &currentversion($fname)."\n", $userinput);
 2242:     return 1;
 2243: 
 2244: }
 2245: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
 2246: 
 2247: #  Make an entry in a user's activity log.
 2248: #
 2249: # Parameters:
 2250: #    $cmd      - The command that got us here.
 2251: #    $tail     - Tail of the command (remaining parameters).
 2252: #    $client   - File descriptor connected to client.
 2253: # Returns
 2254: #     0        - Requested to exit, caller should shut down.
 2255: #     1        - Continue processing.
 2256: #
 2257: sub activity_log_handler {
 2258:     my ($cmd, $tail, $client) = @_;
 2259: 
 2260: 
 2261:     my $userinput= "$cmd:$tail";
 2262: 
 2263:     my ($udom,$uname,$what)=split(/:/,$tail);
 2264:     chomp($what);
 2265:     my $proname=&propath($udom,$uname);
 2266:     my $now=time;
 2267:     my $hfh;
 2268:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
 2269: 	print $hfh "$now:$clientname:$what\n";
 2270: 	&Reply( $client, "ok\n", $userinput); 
 2271:     } else {
 2272: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
 2273: 		 ."while attempting log\n", 
 2274: 		 $userinput);
 2275:     }
 2276: 
 2277:     return 1;
 2278: }
 2279: &register_handler("log", \&activity_log_handler, 0, 1, 0);
 2280: 
 2281: #
 2282: #   Put a namespace entry in a user profile hash.
 2283: #   My druthers would be for this to be an encrypted interaction too.
 2284: #   anything that might be an inadvertent covert channel about either
 2285: #   user authentication or user personal information....
 2286: #
 2287: # Parameters:
 2288: #    $cmd      - The command that got us here.
 2289: #    $tail     - Tail of the command (remaining parameters).
 2290: #    $client   - File descriptor connected to client.
 2291: # Returns
 2292: #     0        - Requested to exit, caller should shut down.
 2293: #     1        - Continue processing.
 2294: #
 2295: sub put_user_profile_entry {
 2296:     my ($cmd, $tail, $client)  = @_;
 2297: 
 2298:     my $userinput = "$cmd:$tail";
 2299:     
 2300:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
 2301:     if ($namespace ne 'roles') {
 2302: 	chomp($what);
 2303: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2304: 				  &GDBM_WRCREAT(),"P",$what);
 2305: 	if($hashref) {
 2306: 	    my @pairs=split(/\&/,$what);
 2307: 	    foreach my $pair (@pairs) {
 2308: 		my ($key,$value)=split(/=/,$pair);
 2309: 		$hashref->{$key}=$value;
 2310: 	    }
 2311: 	    if (&untie_user_hash($hashref)) {
 2312: 		&Reply( $client, "ok\n", $userinput);
 2313: 	    } else {
 2314: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 2315: 			"while attempting put\n", 
 2316: 			$userinput);
 2317: 	    }
 2318: 	} else {
 2319: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 2320: 		     "while attempting put\n", $userinput);
 2321: 	}
 2322:     } else {
 2323:         &Failure( $client, "refused\n", $userinput);
 2324:     }
 2325:     
 2326:     return 1;
 2327: }
 2328: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
 2329: 
 2330: #   Put a piece of new data in hash, returns error if entry already exists
 2331: # Parameters:
 2332: #    $cmd      - The command that got us here.
 2333: #    $tail     - Tail of the command (remaining parameters).
 2334: #    $client   - File descriptor connected to client.
 2335: # Returns
 2336: #     0        - Requested to exit, caller should shut down.
 2337: #     1        - Continue processing.
 2338: #
 2339: sub newput_user_profile_entry {
 2340:     my ($cmd, $tail, $client)  = @_;
 2341: 
 2342:     my $userinput = "$cmd:$tail";
 2343: 
 2344:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
 2345:     if ($namespace eq 'roles') {
 2346:         &Failure( $client, "refused\n", $userinput);
 2347: 	return 1;
 2348:     }
 2349: 
 2350:     chomp($what);
 2351: 
 2352:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2353: 				 &GDBM_WRCREAT(),"N",$what);
 2354:     if(!$hashref) {
 2355: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 2356: 		  "while attempting put\n", $userinput);
 2357: 	return 1;
 2358:     }
 2359: 
 2360:     my @pairs=split(/\&/,$what);
 2361:     foreach my $pair (@pairs) {
 2362: 	my ($key,$value)=split(/=/,$pair);
 2363: 	if (exists($hashref->{$key})) {
 2364: 	    &Failure($client, "key_exists: ".$key."\n",$userinput);
 2365: 	    return 1;
 2366: 	}
 2367:     }
 2368: 
 2369:     foreach my $pair (@pairs) {
 2370: 	my ($key,$value)=split(/=/,$pair);
 2371: 	$hashref->{$key}=$value;
 2372:     }
 2373: 
 2374:     if (&untie_user_hash($hashref)) {
 2375: 	&Reply( $client, "ok\n", $userinput);
 2376:     } else {
 2377: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 2378: 		 "while attempting put\n", 
 2379: 		 $userinput);
 2380:     }
 2381:     return 1;
 2382: }
 2383: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
 2384: 
 2385: # 
 2386: #   Increment a profile entry in the user history file.
 2387: #   The history contains keyword value pairs.  In this case,
 2388: #   The value itself is a pair of numbers.  The first, the current value
 2389: #   the second an increment that this function applies to the current
 2390: #   value.
 2391: #
 2392: # Parameters:
 2393: #    $cmd      - The command that got us here.
 2394: #    $tail     - Tail of the command (remaining parameters).
 2395: #    $client   - File descriptor connected to client.
 2396: # Returns
 2397: #     0        - Requested to exit, caller should shut down.
 2398: #     1        - Continue processing.
 2399: #
 2400: sub increment_user_value_handler {
 2401:     my ($cmd, $tail, $client) = @_;
 2402:     
 2403:     my $userinput   = "$cmd:$tail";
 2404:     
 2405:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
 2406:     if ($namespace ne 'roles') {
 2407:         chomp($what);
 2408: 	my $hashref = &tie_user_hash($udom, $uname,
 2409: 				     $namespace, &GDBM_WRCREAT(),
 2410: 				     "P",$what);
 2411: 	if ($hashref) {
 2412: 	    my @pairs=split(/\&/,$what);
 2413: 	    foreach my $pair (@pairs) {
 2414: 		my ($key,$value)=split(/=/,$pair);
 2415:                 $value = &unescape($value);
 2416: 		# We could check that we have a number...
 2417: 		if (! defined($value) || $value eq '') {
 2418: 		    $value = 1;
 2419: 		}
 2420: 		$hashref->{$key}+=$value;
 2421:                 if ($namespace eq 'nohist_resourcetracker') {
 2422:                     if ($hashref->{$key} < 0) {
 2423:                         $hashref->{$key} = 0;
 2424:                     }
 2425:                 }
 2426: 	    }
 2427: 	    if (&untie_user_hash($hashref)) {
 2428: 		&Reply( $client, "ok\n", $userinput);
 2429: 	    } else {
 2430: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 2431: 			 "while attempting inc\n", $userinput);
 2432: 	    }
 2433: 	} else {
 2434: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 2435: 		     "while attempting inc\n", $userinput);
 2436: 	}
 2437:     } else {
 2438: 	&Failure($client, "refused\n", $userinput);
 2439:     }
 2440:     
 2441:     return 1;
 2442: }
 2443: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
 2444: 
 2445: #
 2446: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
 2447: #   Each 'role' a user has implies a set of permissions.  Adding a new role
 2448: #   for a person grants the permissions packaged with that role
 2449: #   to that user when the role is selected.
 2450: #
 2451: # Parameters:
 2452: #    $cmd       - The command string (rolesput).
 2453: #    $tail      - The remainder of the request line.  For rolesput this
 2454: #                 consists of a colon separated list that contains:
 2455: #                 The domain and user that is granting the role (logged).
 2456: #                 The domain and user that is getting the role.
 2457: #                 The roles being granted as a set of & separated pairs.
 2458: #                 each pair a key value pair.
 2459: #    $client    - File descriptor connected to the client.
 2460: # Returns:
 2461: #     0         - If the daemon should exit
 2462: #     1         - To continue processing.
 2463: #
 2464: #
 2465: sub roles_put_handler {
 2466:     my ($cmd, $tail, $client) = @_;
 2467: 
 2468:     my $userinput  = "$cmd:$tail";
 2469: 
 2470:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
 2471:     
 2472: 
 2473:     my $namespace='roles';
 2474:     chomp($what);
 2475:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2476: 				 &GDBM_WRCREAT(), "P",
 2477: 				 "$exedom:$exeuser:$what");
 2478:     #
 2479:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
 2480:     #  handle is open for the minimal amount of time.  Since the flush
 2481:     #  is done on close this improves the chances the log will be an un-
 2482:     #  corrupted ordered thing.
 2483:     if ($hashref) {
 2484: 	my $pass_entry = &get_auth_type($udom, $uname);
 2485: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
 2486: 	$auth_type = $auth_type.":";
 2487: 	my @pairs=split(/\&/,$what);
 2488: 	foreach my $pair (@pairs) {
 2489: 	    my ($key,$value)=split(/=/,$pair);
 2490: 	    &manage_permissions($key, $udom, $uname,
 2491: 			       $auth_type);
 2492: 	    $hashref->{$key}=$value;
 2493: 	}
 2494: 	if (&untie_user_hash($hashref)) {
 2495: 	    &Reply($client, "ok\n", $userinput);
 2496: 	} else {
 2497: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 2498: 		     "while attempting rolesput\n", $userinput);
 2499: 	}
 2500:     } else {
 2501: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 2502: 		 "while attempting rolesput\n", $userinput);
 2503:     }
 2504:     return 1;
 2505: }
 2506: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
 2507: 
 2508: #
 2509: #   Deletes (removes) a role for a user.   This is equivalent to removing
 2510: #  a permissions package associated with the role from the user's profile.
 2511: #
 2512: # Parameters:
 2513: #     $cmd                 - The command (rolesdel)
 2514: #     $tail                - The remainder of the request line. This consists
 2515: #                             of:
 2516: #                             The domain and user requesting the change (logged)
 2517: #                             The domain and user being changed.
 2518: #                             The roles being revoked.  These are shipped to us
 2519: #                             as a bunch of & separated role name keywords.
 2520: #     $client              - The file handle open on the client.
 2521: # Returns:
 2522: #     1                    - Continue processing
 2523: #     0                    - Exit.
 2524: #
 2525: sub roles_delete_handler {
 2526:     my ($cmd, $tail, $client)  = @_;
 2527: 
 2528:     my $userinput    = "$cmd:$tail";
 2529:    
 2530:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
 2531:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
 2532: 	   "what = ".$what);
 2533:     my $namespace='roles';
 2534:     chomp($what);
 2535:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2536: 				 &GDBM_WRCREAT(), "D",
 2537: 				 "$exedom:$exeuser:$what");
 2538:     
 2539:     if ($hashref) {
 2540: 	my @rolekeys=split(/\&/,$what);
 2541: 	
 2542: 	foreach my $key (@rolekeys) {
 2543: 	    delete $hashref->{$key};
 2544: 	}
 2545: 	if (&untie_user_hash($hashref)) {
 2546: 	    &Reply($client, "ok\n", $userinput);
 2547: 	} else {
 2548: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 2549: 		     "while attempting rolesdel\n", $userinput);
 2550: 	}
 2551:     } else {
 2552:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 2553: 		 "while attempting rolesdel\n", $userinput);
 2554:     }
 2555:     
 2556:     return 1;
 2557: }
 2558: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
 2559: 
 2560: # Unencrypted get from a user's profile database.  See 
 2561: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
 2562: # This function retrieves a keyed item from a specific named database in the
 2563: # user's directory.
 2564: #
 2565: # Parameters:
 2566: #   $cmd             - Command request keyword (get).
 2567: #   $tail            - Tail of the command.  This is a colon separated list
 2568: #                      consisting of the domain and username that uniquely
 2569: #                      identifies the profile,
 2570: #                      The 'namespace' which selects the gdbm file to 
 2571: #                      do the lookup in, 
 2572: #                      & separated list of keys to lookup.  Note that
 2573: #                      the values are returned as an & separated list too.
 2574: #   $client          - File descriptor open on the client.
 2575: # Returns:
 2576: #   1       - Continue processing.
 2577: #   0       - Exit.
 2578: #
 2579: sub get_profile_entry {
 2580:     my ($cmd, $tail, $client) = @_;
 2581: 
 2582:     my $userinput= "$cmd:$tail";
 2583:    
 2584:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 2585:     chomp($what);
 2586: 
 2587: 
 2588:     my $replystring = read_profile($udom, $uname, $namespace, $what);
 2589:     my ($first) = split(/:/,$replystring);
 2590:     if($first ne "error") {
 2591: 	&Reply($client, \$replystring, $userinput);
 2592:     } else {
 2593: 	&Failure($client, $replystring." while attempting get\n", $userinput);
 2594:     }
 2595:     return 1;
 2596: 
 2597: 
 2598: }
 2599: &register_handler("get", \&get_profile_entry, 0,1,0);
 2600: 
 2601: #
 2602: #  Process the encrypted get request.  Note that the request is sent
 2603: #  in clear, but the reply is encrypted.  This is a small covert channel:
 2604: #  information about the sensitive keys is given to the snooper.  Just not
 2605: #  information about the values of the sensitive key.  Hmm if I wanted to
 2606: #  know these I'd snoop for the egets. Get the profile item names from them
 2607: #  and then issue a get for them since there's no enforcement of the
 2608: #  requirement of an encrypted get for particular profile items.  If I
 2609: #  were re-doing this, I'd force the request to be encrypted as well as the
 2610: #  reply.  I'd also just enforce encrypted transactions for all gets since
 2611: #  that would prevent any covert channel snooping.
 2612: #
 2613: #  Parameters:
 2614: #     $cmd               - Command keyword of request (eget).
 2615: #     $tail              - Tail of the command.  See GetProfileEntry
#                          for more information about this.
 2616: #     $client            - File open on the client.
 2617: #  Returns:
 2618: #     1      - Continue processing
 2619: #     0      - server should exit.
 2620: sub get_profile_entry_encrypted {
 2621:     my ($cmd, $tail, $client) = @_;
 2622: 
 2623:     my $userinput = "$cmd:$tail";
 2624:    
 2625:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 2626:     chomp($what);
 2627:     my $qresult = read_profile($udom, $uname, $namespace, $what);
 2628:     my ($first) = split(/:/, $qresult);
 2629:     if($first ne "error") {
 2630: 	
 2631: 	if ($cipher) {
 2632: 	    my $cmdlength=length($qresult);
 2633: 	    $qresult.="         ";
 2634: 	    my $encqresult='';
 2635: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 2636: 		$encqresult.= unpack("H16", 
 2637: 				     $cipher->encrypt(substr($qresult,
 2638: 							     $encidx,
 2639: 							     8)));
 2640: 	    }
 2641: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
 2642: 	} else {
 2643: 		&Failure( $client, "error:no_key\n", $userinput);
 2644: 	    }
 2645:     } else {
 2646: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
 2647: 
 2648:     }
 2649:     
 2650:     return 1;
 2651: }
 2652: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
 2653: 
 2654: #
 2655: #   Deletes a key in a user profile database.
 2656: #   
 2657: #   Parameters:
 2658: #       $cmd                  - Command keyword (del).
 2659: #       $tail                 - Command tail.  IN this case a colon
 2660: #                               separated list containing:
 2661: #                               The domain and user that identifies uniquely
 2662: #                               the identity of the user.
 2663: #                               The profile namespace (name of the profile
 2664: #                               database file).
 2665: #                               & separated list of keywords to delete.
 2666: #       $client              - File open on client socket.
 2667: # Returns:
 2668: #     1   - Continue processing
 2669: #     0   - Exit server.
 2670: #
 2671: #
 2672: sub delete_profile_entry {
 2673:     my ($cmd, $tail, $client) = @_;
 2674: 
 2675:     my $userinput = "cmd:$tail";
 2676: 
 2677:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 2678:     chomp($what);
 2679:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2680: 				 &GDBM_WRCREAT(),
 2681: 				 "D",$what);
 2682:     if ($hashref) {
 2683:         my @keys=split(/\&/,$what);
 2684: 	foreach my $key (@keys) {
 2685: 	    delete($hashref->{$key});
 2686: 	}
 2687: 	if (&untie_user_hash($hashref)) {
 2688: 	    &Reply($client, "ok\n", $userinput);
 2689: 	} else {
 2690: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 2691: 		    "while attempting del\n", $userinput);
 2692: 	}
 2693:     } else {
 2694: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 2695: 		 "while attempting del\n", $userinput);
 2696:     }
 2697:     return 1;
 2698: }
 2699: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
 2700: 
 2701: #
 2702: #  List the set of keys that are defined in a profile database file.
 2703: #  A successful reply from this will contain an & separated list of
 2704: #  the keys. 
 2705: # Parameters:
 2706: #     $cmd              - Command request (keys).
 2707: #     $tail             - Remainder of the request, a colon separated
 2708: #                         list containing domain/user that identifies the
 2709: #                         user being queried, and the database namespace
 2710: #                         (database filename essentially).
 2711: #     $client           - File open on the client.
 2712: #  Returns:
 2713: #    1    - Continue processing.
 2714: #    0    - Exit the server.
 2715: #
 2716: sub get_profile_keys {
 2717:     my ($cmd, $tail, $client) = @_;
 2718: 
 2719:     my $userinput = "$cmd:$tail";
 2720: 
 2721:     my ($udom,$uname,$namespace)=split(/:/,$tail);
 2722:     my $qresult='';
 2723:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2724: 				  &GDBM_READER());
 2725:     if ($hashref) {
 2726: 	foreach my $key (keys %$hashref) {
 2727: 	    $qresult.="$key&";
 2728: 	}
 2729: 	if (&untie_user_hash($hashref)) {
 2730: 	    $qresult=~s/\&$//;
 2731: 	    &Reply($client, \$qresult, $userinput);
 2732: 	} else {
 2733: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 2734: 		    "while attempting keys\n", $userinput);
 2735: 	}
 2736:     } else {
 2737: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 2738: 		 "while attempting keys\n", $userinput);
 2739:     }
 2740:    
 2741:     return 1;
 2742: }
 2743: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
 2744: 
 2745: #
 2746: #   Dump the contents of a user profile database.
 2747: #   Note that this constitutes a very large covert channel too since
 2748: #   the dump will return sensitive information that is not encrypted.
 2749: #   The naive security assumption is that the session negotiation ensures
 2750: #   our client is trusted and I don't believe that's assured at present.
 2751: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
 2752: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
 2753: # 
 2754: #  Parameters:
 2755: #     $cmd           - The command request keyword (currentdump).
 2756: #     $tail          - Remainder of the request, consisting of a colon
 2757: #                      separated list that has the domain/username and
 2758: #                      the namespace to dump (database file).
 2759: #     $client        - file open on the remote client.
 2760: # Returns:
 2761: #     1    - Continue processing.
 2762: #     0    - Exit the server.
 2763: #
 2764: sub dump_profile_database {
 2765:     my ($cmd, $tail, $client) = @_;
 2766: 
 2767:     my $userinput = "$cmd:$tail";
 2768:    
 2769:     my ($udom,$uname,$namespace) = split(/:/,$tail);
 2770:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2771: 				 &GDBM_READER());
 2772:     if ($hashref) {
 2773: 	# Structure of %data:
 2774: 	# $data{$symb}->{$parameter}=$value;
 2775: 	# $data{$symb}->{'v.'.$parameter}=$version;
 2776: 	# since $parameter will be unescaped, we do not
 2777:  	# have to worry about silly parameter names...
 2778: 	
 2779:         my $qresult='';
 2780: 	my %data = ();                     # A hash of anonymous hashes..
 2781: 	while (my ($key,$value) = each(%$hashref)) {
 2782: 	    my ($v,$symb,$param) = split(/:/,$key);
 2783: 	    next if ($v eq 'version' || $symb eq 'keys');
 2784: 	    next if (exists($data{$symb}) && 
 2785: 		     exists($data{$symb}->{$param}) &&
 2786: 		     $data{$symb}->{'v.'.$param} > $v);
 2787: 	    $data{$symb}->{$param}=$value;
 2788: 	    $data{$symb}->{'v.'.$param}=$v;
 2789: 	}
 2790: 	if (&untie_user_hash($hashref)) {
 2791: 	    while (my ($symb,$param_hash) = each(%data)) {
 2792: 		while(my ($param,$value) = each (%$param_hash)){
 2793: 		    next if ($param =~ /^v\./);       # Ignore versions...
 2794: 		    #
 2795: 		    #   Just dump the symb=value pairs separated by &
 2796: 		    #
 2797: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
 2798: 		}
 2799: 	    }
 2800: 	    chop($qresult);
 2801: 	    &Reply($client , \$qresult, $userinput);
 2802: 	} else {
 2803: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 2804: 		     "while attempting currentdump\n", $userinput);
 2805: 	}
 2806:     } else {
 2807: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 2808: 		"while attempting currentdump\n", $userinput);
 2809:     }
 2810: 
 2811:     return 1;
 2812: }
 2813: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
 2814: 
 2815: #
 2816: #   Dump a profile database with an optional regular expression
 2817: #   to match against the keys.  In this dump, no effort is made
 2818: #   to separate symb from version information. Presumably the
 2819: #   databases that are dumped by this command are of a different
 2820: #   structure.  Need to look at this and improve the documentation of
 2821: #   both this and the currentdump handler.
 2822: # Parameters:
 2823: #    $cmd                     - The command keyword.
 2824: #    $tail                    - All of the characters after the $cmd:
 2825: #                               These are expected to be a colon
 2826: #                               separated list containing:
 2827: #                               domain/user - identifying the user.
 2828: #                               namespace   - identifying the database.
 2829: #                               regexp      - optional regular expression
 2830: #                                             that is matched against
 2831: #                                             database keywords to do
 2832: #                                             selective dumps.
 2833: #   $client                   - Channel open on the client.
 2834: # Returns:
 2835: #    1    - Continue processing.
 2836: # Side effects:
 2837: #    response is written to $client.
 2838: #
 2839: sub dump_with_regexp {
 2840:     my ($cmd, $tail, $client) = @_;
 2841: 
 2842: 
 2843:     my $userinput = "$cmd:$tail";
 2844: 
 2845:     my ($udom,$uname,$namespace,$regexp,$range)=split(/:/,$tail);
 2846:     if (defined($regexp)) {
 2847: 	$regexp=&unescape($regexp);
 2848:     } else {
 2849: 	$regexp='.';
 2850:     }
 2851:     my ($start,$end);
 2852:     if (defined($range)) {
 2853: 	if ($range =~/^(\d+)\-(\d+)$/) {
 2854: 	    ($start,$end) = ($1,$2);
 2855: 	} elsif ($range =~/^(\d+)$/) {
 2856: 	    ($start,$end) = (0,$1);
 2857: 	} else {
 2858: 	    undef($range);
 2859: 	}
 2860:     }
 2861:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2862: 				 &GDBM_READER());
 2863:     if ($hashref) {
 2864:         my $qresult='';
 2865: 	my $count=0;
 2866: 	while (my ($key,$value) = each(%$hashref)) {
 2867: 	    if ($regexp eq '.') {
 2868: 		$count++;
 2869: 		if (defined($range) && $count >= $end)   { last; }
 2870: 		if (defined($range) && $count <  $start) { next; }
 2871: 		$qresult.=$key.'='.$value.'&';
 2872: 	    } else {
 2873: 		my $unescapeKey = &unescape($key);
 2874: 		if (eval('$unescapeKey=~/$regexp/')) {
 2875: 		    $count++;
 2876: 		    if (defined($range) && $count >= $end)   { last; }
 2877: 		    if (defined($range) && $count <  $start) { next; }
 2878: 		    $qresult.="$key=$value&";
 2879: 		}
 2880: 	    }
 2881: 	}
 2882: 	if (&untie_user_hash($hashref)) {
 2883: 	    chop($qresult);
 2884: 	    &Reply($client, \$qresult, $userinput);
 2885: 	} else {
 2886: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 2887: 		     "while attempting dump\n", $userinput);
 2888: 	}
 2889:     } else {
 2890: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 2891: 		"while attempting dump\n", $userinput);
 2892:     }
 2893: 
 2894:     return 1;
 2895: }
 2896: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
 2897: 
 2898: #  Store a set of key=value pairs associated with a versioned name.
 2899: #
 2900: #  Parameters:
 2901: #    $cmd                - Request command keyword.
 2902: #    $tail               - Tail of the request.  This is a colon
 2903: #                          separated list containing:
 2904: #                          domain/user - User and authentication domain.
 2905: #                          namespace   - Name of the database being modified
 2906: #                          rid         - Resource keyword to modify.
 2907: #                          what        - new value associated with rid.
 2908: #
 2909: #    $client             - Socket open on the client.
 2910: #
 2911: #
 2912: #  Returns:
 2913: #      1 (keep on processing).
 2914: #  Side-Effects:
 2915: #    Writes to the client
 2916: sub store_handler {
 2917:     my ($cmd, $tail, $client) = @_;
 2918:  
 2919:     my $userinput = "$cmd:$tail";
 2920: 
 2921:     my ($udom,$uname,$namespace,$rid,$what) =split(/:/,$tail);
 2922:     if ($namespace ne 'roles') {
 2923: 
 2924: 	chomp($what);
 2925: 	my @pairs=split(/\&/,$what);
 2926: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
 2927: 				       &GDBM_WRCREAT(), "S",
 2928: 				       "$rid:$what");
 2929: 	if ($hashref) {
 2930: 	    my $now = time;
 2931: 	    my @previouskeys=split(/&/,$hashref->{"keys:$rid"});
 2932: 	    my $key;
 2933: 	    $hashref->{"version:$rid"}++;
 2934: 	    my $version=$hashref->{"version:$rid"};
 2935: 	    my $allkeys=''; 
 2936: 	    foreach my $pair (@pairs) {
 2937: 		my ($key,$value)=split(/=/,$pair);
 2938: 		$allkeys.=$key.':';
 2939: 		$hashref->{"$version:$rid:$key"}=$value;
 2940: 	    }
 2941: 	    $hashref->{"$version:$rid:timestamp"}=$now;
 2942: 	    $allkeys.='timestamp';
 2943: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
 2944: 	    if (&untie_user_hash($hashref)) {
 2945: 		&Reply($client, "ok\n", $userinput);
 2946: 	    } else {
 2947: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 2948: 			"while attempting store\n", $userinput);
 2949: 	    }
 2950: 	} else {
 2951: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 2952: 		     "while attempting store\n", $userinput);
 2953: 	}
 2954:     } else {
 2955: 	&Failure($client, "refused\n", $userinput);
 2956:     }
 2957: 
 2958:     return 1;
 2959: }
 2960: &register_handler("store", \&store_handler, 0, 1, 0);
 2961: 
 2962: #  Modify a set of key=value pairs associated with a versioned name.
 2963: #
 2964: #  Parameters:
 2965: #    $cmd                - Request command keyword.
 2966: #    $tail               - Tail of the request.  This is a colon
 2967: #                          separated list containing:
 2968: #                          domain/user - User and authentication domain.
 2969: #                          namespace   - Name of the database being modified
 2970: #                          rid         - Resource keyword to modify.
 2971: #                          v           - Version item to modify
 2972: #                          what        - new value associated with rid.
 2973: #
 2974: #    $client             - Socket open on the client.
 2975: #
 2976: #
 2977: #  Returns:
 2978: #      1 (keep on processing).
 2979: #  Side-Effects:
 2980: #    Writes to the client
 2981: sub putstore_handler {
 2982:     my ($cmd, $tail, $client) = @_;
 2983:  
 2984:     my $userinput = "$cmd:$tail";
 2985: 
 2986:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
 2987:     if ($namespace ne 'roles') {
 2988: 
 2989: 	chomp($what);
 2990: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
 2991: 				       &GDBM_WRCREAT(), "M",
 2992: 				       "$rid:$v:$what");
 2993: 	if ($hashref) {
 2994: 	    my $now = time;
 2995: 	    my %data = &hash_extract($what);
 2996: 	    my @allkeys;
 2997: 	    while (my($key,$value) = each(%data)) {
 2998: 		push(@allkeys,$key);
 2999: 		$hashref->{"$v:$rid:$key"} = $value;
 3000: 	    }
 3001: 	    my $allkeys = join(':',@allkeys);
 3002: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
 3003: 
 3004: 	    if (&untie_user_hash($hashref)) {
 3005: 		&Reply($client, "ok\n", $userinput);
 3006: 	    } else {
 3007: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3008: 			"while attempting store\n", $userinput);
 3009: 	    }
 3010: 	} else {
 3011: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3012: 		     "while attempting store\n", $userinput);
 3013: 	}
 3014:     } else {
 3015: 	&Failure($client, "refused\n", $userinput);
 3016:     }
 3017: 
 3018:     return 1;
 3019: }
 3020: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
 3021: 
 3022: sub hash_extract {
 3023:     my ($str)=@_;
 3024:     my %hash;
 3025:     foreach my $pair (split(/\&/,$str)) {
 3026: 	my ($key,$value)=split(/=/,$pair);
 3027: 	$hash{$key}=$value;
 3028:     }
 3029:     return (%hash);
 3030: }
 3031: sub hash_to_str {
 3032:     my ($hash_ref)=@_;
 3033:     my $str;
 3034:     foreach my $key (keys(%$hash_ref)) {
 3035: 	$str.=$key.'='.$hash_ref->{$key}.'&';
 3036:     }
 3037:     $str=~s/\&$//;
 3038:     return $str;
 3039: }
 3040: 
 3041: #
 3042: #  Dump out all versions of a resource that has key=value pairs associated
 3043: # with it for each version.  These resources are built up via the store
 3044: # command.
 3045: #
 3046: #  Parameters:
 3047: #     $cmd               - Command keyword.
 3048: #     $tail              - Remainder of the request which consists of:
 3049: #                          domain/user   - User and auth. domain.
 3050: #                          namespace     - name of resource database.
 3051: #                          rid           - Resource id.
 3052: #    $client             - socket open on the client.
 3053: #
 3054: # Returns:
 3055: #      1  indicating the caller should not yet exit.
 3056: # Side-effects:
 3057: #   Writes a reply to the client.
 3058: #   The reply is a string of the following shape:
 3059: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
 3060: #    Where the 1 above represents version 1.
 3061: #    this continues for all pairs of keys in all versions.
 3062: #
 3063: #
 3064: #    
 3065: #
 3066: sub restore_handler {
 3067:     my ($cmd, $tail, $client) = @_;
 3068: 
 3069:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
 3070:     my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
 3071:     $namespace=~s/\//\_/g;
 3072:     $namespace = &LONCAPA::clean_username($namespace);
 3073: 
 3074:     chomp($rid);
 3075:     my $qresult='';
 3076:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
 3077:     if ($hashref) {
 3078: 	my $version=$hashref->{"version:$rid"};
 3079: 	$qresult.="version=$version&";
 3080: 	my $scope;
 3081: 	for ($scope=1;$scope<=$version;$scope++) {
 3082: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
 3083: 	    my @keys=split(/:/,$vkeys);
 3084: 	    my $key;
 3085: 	    $qresult.="$scope:keys=$vkeys&";
 3086: 	    foreach $key (@keys) {
 3087: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
 3088: 	    }                                  
 3089: 	}
 3090: 	if (&untie_user_hash($hashref)) {
 3091: 	    $qresult=~s/\&$//;
 3092: 	    &Reply( $client, \$qresult, $userinput);
 3093: 	} else {
 3094: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3095: 		    "while attempting restore\n", $userinput);
 3096: 	}
 3097:     } else {
 3098: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3099: 		"while attempting restore\n", $userinput);
 3100:     }
 3101:   
 3102:     return 1;
 3103: 
 3104: 
 3105: }
 3106: &register_handler("restore", \&restore_handler, 0,1,0);
 3107: 
 3108: #
 3109: #   Add a chat message to a synchronous discussion board.
 3110: #
 3111: # Parameters:
 3112: #    $cmd                - Request keyword.
 3113: #    $tail               - Tail of the command. A colon separated list
 3114: #                          containing:
 3115: #                          cdom    - Domain on which the chat board lives
 3116: #                          cnum    - Course containing the chat board.
 3117: #                          newpost - Body of the posting.
 3118: #                          group   - Optional group, if chat board is only 
 3119: #                                    accessible in a group within the course 
 3120: #   $client              - Socket open on the client.
 3121: # Returns:
 3122: #   1    - Indicating caller should keep on processing.
 3123: #
 3124: # Side-effects:
 3125: #   writes a reply to the client.
 3126: #
 3127: #
 3128: sub send_chat_handler {
 3129:     my ($cmd, $tail, $client) = @_;
 3130: 
 3131:     
 3132:     my $userinput = "$cmd:$tail";
 3133: 
 3134:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
 3135:     &chat_add($cdom,$cnum,$newpost,$group);
 3136:     &Reply($client, "ok\n", $userinput);
 3137: 
 3138:     return 1;
 3139: }
 3140: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
 3141: 
 3142: #
 3143: #   Retrieve the set of chat messages from a discussion board.
 3144: #
 3145: #  Parameters:
 3146: #    $cmd             - Command keyword that initiated the request.
 3147: #    $tail            - Remainder of the request after the command
 3148: #                       keyword.  In this case a colon separated list of
 3149: #                       chat domain    - Which discussion board.
 3150: #                       chat id        - Discussion thread(?)
 3151: #                       domain/user    - Authentication domain and username
 3152: #                                        of the requesting person.
 3153: #                       group          - Optional course group containing
 3154: #                                        the board.      
 3155: #   $client           - Socket open on the client program.
 3156: # Returns:
 3157: #    1     - continue processing
 3158: # Side effects:
 3159: #    Response is written to the client.
 3160: #
 3161: sub retrieve_chat_handler {
 3162:     my ($cmd, $tail, $client) = @_;
 3163: 
 3164: 
 3165:     my $userinput = "$cmd:$tail";
 3166: 
 3167:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
 3168:     my $reply='';
 3169:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
 3170: 	$reply.=&escape($_).':';
 3171:     }
 3172:     $reply=~s/\:$//;
 3173:     &Reply($client, \$reply, $userinput);
 3174: 
 3175: 
 3176:     return 1;
 3177: }
 3178: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
 3179: 
 3180: #
 3181: #  Initiate a query of an sql database.  SQL query repsonses get put in
 3182: #  a file for later retrieval.  This prevents sql query results from
 3183: #  bottlenecking the system.  Note that with loncnew, perhaps this is
 3184: #  less of an issue since multiple outstanding requests can be concurrently
 3185: #  serviced.
 3186: #
 3187: #  Parameters:
 3188: #     $cmd       - COmmand keyword that initiated the request.
 3189: #     $tail      - Remainder of the command after the keyword.
 3190: #                  For this function, this consists of a query and
 3191: #                  3 arguments that are self-documentingly labelled
 3192: #                  in the original arg1, arg2, arg3.
 3193: #     $client    - Socket open on the client.
 3194: # Return:
 3195: #    1   - Indicating processing should continue.
 3196: # Side-effects:
 3197: #    a reply is written to $client.
 3198: #
 3199: sub send_query_handler {
 3200:     my ($cmd, $tail, $client) = @_;
 3201: 
 3202: 
 3203:     my $userinput = "$cmd:$tail";
 3204: 
 3205:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
 3206:     $query=~s/\n*$//g;
 3207:     &Reply($client, "". &sql_reply("$clientname\&$query".
 3208: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
 3209: 	  $userinput);
 3210:     
 3211:     return 1;
 3212: }
 3213: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
 3214: 
 3215: #
 3216: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
 3217: #   The query is submitted via a "querysend" transaction.
 3218: #   There it is passed on to the lonsql daemon, queued and issued to
 3219: #   mysql.
 3220: #     This transaction is invoked when the sql transaction is complete
 3221: #   it stores the query results in flie and indicates query completion.
 3222: #   presumably local software then fetches this response... I'm guessing
 3223: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
 3224: #   lonsql on completion of the query interacts with the lond of our
 3225: #   client to do a query reply storing two files:
 3226: #    - id     - The results of the query.
 3227: #    - id.end - Indicating the transaction completed. 
 3228: #    NOTE: id is a unique id assigned to the query and querysend time.
 3229: # Parameters:
 3230: #    $cmd        - Command keyword that initiated this request.
 3231: #    $tail       - Remainder of the tail.  In this case that's a colon
 3232: #                  separated list containing the query Id and the 
 3233: #                  results of the query.
 3234: #    $client     - Socket open on the client.
 3235: # Return:
 3236: #    1           - Indicating that we should continue processing.
 3237: # Side effects:
 3238: #    ok written to the client.
 3239: #
 3240: sub reply_query_handler {
 3241:     my ($cmd, $tail, $client) = @_;
 3242: 
 3243: 
 3244:     my $userinput = "$cmd:$tail";
 3245: 
 3246:     my ($id,$reply)=split(/:/,$tail); 
 3247:     my $store;
 3248:     my $execdir=$perlvar{'lonDaemons'};
 3249:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
 3250: 	$reply=~s/\&/\n/g;
 3251: 	print $store $reply;
 3252: 	close $store;
 3253: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
 3254: 	print $store2 "done\n";
 3255: 	close $store2;
 3256: 	&Reply($client, "ok\n", $userinput);
 3257:     } else {
 3258: 	&Failure($client, "error: ".($!+0)
 3259: 		." IO::File->new Failed ".
 3260: 		"while attempting queryreply\n", $userinput);
 3261:     }
 3262:  
 3263: 
 3264:     return 1;
 3265: }
 3266: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
 3267: 
 3268: #
 3269: #  Process the courseidput request.  Not quite sure what this means
 3270: #  at the system level sense.  It appears a gdbm file in the 
 3271: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
 3272: #  a set of entries made in that database.
 3273: #
 3274: # Parameters:
 3275: #   $cmd      - The command keyword that initiated this request.
 3276: #   $tail     - Tail of the command.  In this case consists of a colon
 3277: #               separated list contaning the domain to apply this to and
 3278: #               an ampersand separated list of keyword=value pairs.
 3279: #               Each value is a colon separated list that includes:  
 3280: #               description, institutional code and course owner.
 3281: #               For backward compatibility with versions included
 3282: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
 3283: #               code and/or course owner are preserved from the existing 
 3284: #               record when writing a new record in response to 1.1 or 
 3285: #               1.2 implementations of lonnet::flushcourselogs().   
 3286: #                      
 3287: #   $client   - Socket open on the client.
 3288: # Returns:
 3289: #   1    - indicating that processing should continue
 3290: #
 3291: # Side effects:
 3292: #   reply is written to the client.
 3293: #
 3294: sub put_course_id_handler {
 3295:     my ($cmd, $tail, $client) = @_;
 3296: 
 3297: 
 3298:     my $userinput = "$cmd:$tail";
 3299: 
 3300:     my ($udom, $what) = split(/:/, $tail,2);
 3301:     chomp($what);
 3302:     my $now=time;
 3303:     my @pairs=split(/\&/,$what);
 3304: 
 3305:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 3306:     if ($hashref) {
 3307: 	foreach my $pair (@pairs) {
 3308:             my ($key,$courseinfo) = split(/=/,$pair,2);
 3309:             $courseinfo =~ s/=/:/g;
 3310:             if (defined($hashref->{$key})) {
 3311:                 my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
 3312:                 if (ref($value) eq 'HASH') {
 3313:                     my @items = ('description','inst_code','owner','type');
 3314:                     my @new_items = split(/:/,$courseinfo,-1);
 3315:                     my %storehash; 
 3316:                     for (my $i=0; $i<@new_items; $i++) {
 3317:                         $storehash{$items[$i]} = &unescape($new_items[$i]);
 3318:                     }
 3319:                     $hashref->{$key} = 
 3320:                         &Apache::lonnet::freeze_escape(\%storehash);
 3321:                     my $unesc_key = &unescape($key);
 3322:                     $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
 3323:                     next;
 3324:                 }
 3325:             }
 3326:             my @current_items = split(/:/,$hashref->{$key},-1);
 3327:             shift(@current_items); # remove description
 3328:             pop(@current_items);   # remove last access
 3329:             my $numcurrent = scalar(@current_items);
 3330:             if ($numcurrent > 3) {
 3331:                 $numcurrent = 3;
 3332:             }
 3333:             my @new_items = split(/:/,$courseinfo,-1);
 3334:             my $numnew = scalar(@new_items);
 3335:             if ($numcurrent > 0) {
 3336:                 if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2 
 3337:                     for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
 3338:                         $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
 3339:                     }
 3340:                 }
 3341:             }
 3342:             $hashref->{$key}=$courseinfo.':'.$now;
 3343: 	}
 3344: 	if (&untie_domain_hash($hashref)) {
 3345: 	    &Reply( $client, "ok\n", $userinput);
 3346: 	} else {
 3347: 	    &Failure($client, "error: ".($!+0)
 3348: 		     ." untie(GDBM) Failed ".
 3349: 		     "while attempting courseidput\n", $userinput);
 3350: 	}
 3351:     } else {
 3352: 	&Failure($client, "error: ".($!+0)
 3353: 		 ." tie(GDBM) Failed ".
 3354: 		 "while attempting courseidput\n", $userinput);
 3355:     }
 3356: 
 3357:     return 1;
 3358: }
 3359: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
 3360: 
 3361: sub put_course_id_hash_handler {
 3362:     my ($cmd, $tail, $client) = @_;
 3363:     my $userinput = "$cmd:$tail";
 3364:     my ($udom,$mode,$what) = split(/:/, $tail,3);
 3365:     chomp($what);
 3366:     my $now=time;
 3367:     my @pairs=split(/\&/,$what);
 3368:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 3369:     if ($hashref) {
 3370:         foreach my $pair (@pairs) {
 3371:             my ($key,$value)=split(/=/,$pair);
 3372:             my $unesc_key = &unescape($key);
 3373:             if ($mode ne 'timeonly') {
 3374:                 if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
 3375:                     my $curritems = &Apache::lonnet::thaw_unescape($key); 
 3376:                     if (ref($curritems) ne 'HASH') {
 3377:                         my @current_items = split(/:/,$hashref->{$key},-1);
 3378:                         my $lasttime = pop(@current_items);
 3379:                         $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
 3380:                     } else {
 3381:                         $hashref->{&escape('lasttime:'.$unesc_key)} = '';
 3382:                     }
 3383:                 } 
 3384:                 $hashref->{$key} = $value;
 3385:             }
 3386:             if ($mode ne 'notime') {
 3387:                 $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
 3388:             }
 3389:         }
 3390:         if (&untie_domain_hash($hashref)) {
 3391:             &Reply($client, "ok\n", $userinput);
 3392:         } else {
 3393:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3394:                      "while attempting courseidputhash\n", $userinput);
 3395:         }
 3396:     } else {
 3397:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3398:                   "while attempting courseidputhash\n", $userinput);
 3399:     }
 3400:     return 1;
 3401: }
 3402: &register_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
 3403: 
 3404: #  Retrieves the value of a course id resource keyword pattern
 3405: #  defined since a starting date.  Both the starting date and the
 3406: #  keyword pattern are optional.  If the starting date is not supplied it
 3407: #  is treated as the beginning of time.  If the pattern is not found,
 3408: #  it is treatred as "." matching everything.
 3409: #
 3410: #  Parameters:
 3411: #     $cmd     - Command keyword that resulted in us being dispatched.
 3412: #     $tail    - The remainder of the command that, in this case, consists
 3413: #                of a colon separated list of:
 3414: #                 domain   - The domain in which the course database is 
 3415: #                            defined.
 3416: #                 since    - Optional parameter describing the minimum
 3417: #                            time of definition(?) of the resources that
 3418: #                            will match the dump.
 3419: #                 description - regular expression that is used to filter
 3420: #                            the dump.  Only keywords matching this regexp
 3421: #                            will be used.
 3422: #                 institutional code - optional supplied code to filter 
 3423: #                            the dump. Only courses with an institutional code 
 3424: #                            that match the supplied code will be returned.
 3425: #                 owner    - optional supplied username and domain of owner to
 3426: #                            filter the dump.  Only courses for which the course
 3427: #                            owner matches the supplied username and/or domain
 3428: #                            will be returned. Pre-2.2.0 legacy entries from 
 3429: #                            nohist_courseiddump will only contain usernames.
 3430: #                 type     - optional parameter for selection 
 3431: #                 regexp_ok - if true, allow the supplied institutional code
 3432: #                            filter to behave as a regular expression.  
 3433: #                 rtn_as_hash - whether to return the information available for
 3434: #                            each matched item as a frozen hash of all 
 3435: #                            key, value pairs in the item's hash, or as a 
 3436: #                            colon-separated list of (in order) description,
 3437: #                            institutional code, and course owner.
 3438: #    
 3439: #     $client  - The socket open on the client.
 3440: # Returns:
 3441: #    1     - Continue processing.
 3442: # Side Effects:
 3443: #   a reply is written to $client.
 3444: sub dump_course_id_handler {
 3445:     my ($cmd, $tail, $client) = @_;
 3446:     my $userinput = "$cmd:$tail";
 3447: 
 3448:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
 3449:         $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly) =split(/:/,$tail);
 3450:     my $now = time;
 3451:     if (defined($description)) {
 3452: 	$description=&unescape($description);
 3453:     } else {
 3454: 	$description='.';
 3455:     }
 3456:     if (defined($instcodefilter)) {
 3457:         $instcodefilter=&unescape($instcodefilter);
 3458:     } else {
 3459:         $instcodefilter='.';
 3460:     }
 3461:     my ($ownerunamefilter,$ownerdomfilter);
 3462:     if (defined($ownerfilter)) {
 3463:         $ownerfilter=&unescape($ownerfilter);
 3464:         if ($ownerfilter ne '.' && defined($ownerfilter)) {
 3465:             if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
 3466:                  $ownerunamefilter = $1;
 3467:                  $ownerdomfilter = $2;
 3468:             } else {
 3469:                 $ownerunamefilter = $ownerfilter;
 3470:                 $ownerdomfilter = '';
 3471:             }
 3472:         }
 3473:     } else {
 3474:         $ownerfilter='.';
 3475:     }
 3476: 
 3477:     if (defined($coursefilter)) {
 3478:         $coursefilter=&unescape($coursefilter);
 3479:     } else {
 3480:         $coursefilter='.';
 3481:     }
 3482:     if (defined($typefilter)) {
 3483:         $typefilter=&unescape($typefilter);
 3484:     } else {
 3485:         $typefilter='.';
 3486:     }
 3487:     if (defined($regexp_ok)) {
 3488:         $regexp_ok=&unescape($regexp_ok);
 3489:     }
 3490:     my $unpack = 1;
 3491:     if ($description eq '.' && $instcodefilter eq '.' && $coursefilter eq '.' && 
 3492:         $typefilter eq '.') {
 3493:         $unpack = 0;
 3494:     }
 3495:     if (!defined($since)) { $since=0; }
 3496:     my $qresult='';
 3497:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 3498:     if ($hashref) {
 3499: 	while (my ($key,$value) = each(%$hashref)) {
 3500:             my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
 3501:                 %unesc_val,$selfenroll_start,$selfenroll_end,
 3502:                 $selfenroll_types);
 3503:             $unesc_key = &unescape($key);
 3504:             if ($unesc_key =~ /^lasttime:/) {
 3505:                 next;
 3506:             } else {
 3507:                 $lasttime_key = &escape('lasttime:'.$unesc_key);
 3508:             }
 3509:             if ($hashref->{$lasttime_key} ne '') {
 3510:                 $lasttime = $hashref->{$lasttime_key};
 3511:                 next if ($lasttime<$since);
 3512:             }
 3513:             my $items = &Apache::lonnet::thaw_unescape($value);
 3514:             if (ref($items) eq 'HASH') {
 3515:                 $is_hash =  1;
 3516:                 if ($unpack || !$rtn_as_hash) {
 3517:                     $unesc_val{'descr'} = $items->{'description'};
 3518:                     $unesc_val{'inst_code'} = $items->{'inst_code'};
 3519:                     $unesc_val{'owner'} = $items->{'owner'};
 3520:                     $unesc_val{'type'} = $items->{'type'};
 3521:                     $selfenroll_types = $items->{'selfenroll_types'};
 3522:                     $selfenroll_start = $items->{'selfenroll_start_date'};
 3523:                     $selfenroll_end = $items->{'selfenroll_end_date'};
 3524:                     if ($selfenrollonly) {
 3525:                         next if (!$selfenroll_types);
 3526:                         if (($selfenroll_start > 0) && ($selfenroll_start > $now)) {
 3527:                             next;
 3528:                         }
 3529:                         if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
 3530:                             next;
 3531:                         }
 3532:                     }
 3533:                 }
 3534:             } else {
 3535:                 $is_hash =  0;
 3536:                 my @courseitems = split(/:/,$value);
 3537:                 $lasttime = pop(@courseitems);
 3538:                 next if ($lasttime<$since);
 3539: 	        ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
 3540:             }
 3541:             my $match = 1;
 3542: 	    if ($description ne '.') {
 3543:                 if (!$is_hash) {
 3544:                     $unesc_val{'descr'} = &unescape($val{'descr'});
 3545:                 }
 3546:                 if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
 3547:                     $match = 0;
 3548:                 }
 3549:             }
 3550:             if ($instcodefilter ne '.') {
 3551:                 if (!$is_hash) {
 3552:                     $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
 3553:                 }
 3554:                 if ($regexp_ok) {
 3555:                     if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
 3556:                         $match = 0;
 3557:                     }
 3558:                 } else {
 3559:                     if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
 3560:                         $match = 0;
 3561:                     }
 3562:                 }
 3563: 	    }
 3564:             if ($ownerfilter ne '.') {
 3565:                 if (!$is_hash) {
 3566:                     $unesc_val{'owner'} = &unescape($val{'owner'});
 3567:                 }
 3568:                 if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
 3569:                     if ($unesc_val{'owner'} =~ /:/) {
 3570:                         if (eval{$unesc_val{'owner'} !~ 
 3571:                              /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
 3572:                             $match = 0;
 3573:                         } 
 3574:                     } else {
 3575:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
 3576:                             $match = 0;
 3577:                         }
 3578:                     }
 3579:                 } elsif ($ownerunamefilter ne '') {
 3580:                     if ($unesc_val{'owner'} =~ /:/) {
 3581:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
 3582:                              $match = 0;
 3583:                         }
 3584:                     } else {
 3585:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
 3586:                             $match = 0;
 3587:                         }
 3588:                     }
 3589:                 } elsif ($ownerdomfilter ne '') {
 3590:                     if ($unesc_val{'owner'} =~ /:/) {
 3591:                         if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
 3592:                              $match = 0;
 3593:                         }
 3594:                     } else {
 3595:                         if ($ownerdomfilter ne $udom) {
 3596:                             $match = 0;
 3597:                         }
 3598:                     }
 3599:                 }
 3600:             }
 3601:             if ($coursefilter ne '.') {
 3602:                 if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
 3603:                     $match = 0;
 3604:                 }
 3605:             }
 3606:             if ($typefilter ne '.') {
 3607:                 if (!$is_hash) {
 3608:                     $unesc_val{'type'} = &unescape($val{'type'});
 3609:                 }
 3610:                 if ($unesc_val{'type'} eq '') {
 3611:                     if ($typefilter ne 'Course') {
 3612:                         $match = 0;
 3613:                     }
 3614:                 } else {
 3615:                     if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
 3616:                         $match = 0;
 3617:                     }
 3618:                 }
 3619:             }
 3620:             if ($match == 1) {
 3621:                 if ($rtn_as_hash) {
 3622:                     if ($is_hash) {
 3623:                         $qresult.=$key.'='.$value.'&';
 3624:                     } else {
 3625:                         my %rtnhash = ( 'description' => &unescape($val{'descr'}),
 3626:                                         'inst_code' => &unescape($val{'inst_code'}),
 3627:                                         'owner'     => &unescape($val{'owner'}),
 3628:                                         'type'      => &unescape($val{'type'}),
 3629:                                       );
 3630:                         my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
 3631:                         $qresult.=$key.'='.$items.'&';
 3632:                     }
 3633:                 } else {
 3634:                     if ($is_hash) {
 3635:                         $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
 3636:                                     &escape($unesc_val{'inst_code'}).':'.
 3637:                                     &escape($unesc_val{'owner'}).'&';
 3638:                     } else {
 3639:                         $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
 3640:                                     ':'.$val{'owner'}.'&';
 3641:                     }
 3642:                 }
 3643:             }
 3644: 	}
 3645: 	if (&untie_domain_hash($hashref)) {
 3646: 	    chop($qresult);
 3647: 	    &Reply($client, \$qresult, $userinput);
 3648: 	} else {
 3649: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3650: 		    "while attempting courseiddump\n", $userinput);
 3651: 	}
 3652:     } else {
 3653: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3654: 		"while attempting courseiddump\n", $userinput);
 3655:     }
 3656:     return 1;
 3657: }
 3658: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
 3659: 
 3660: #
 3661: # Puts an unencrypted entry in a namespace db file at the domain level 
 3662: #
 3663: # Parameters:
 3664: #    $cmd      - The command that got us here.
 3665: #    $tail     - Tail of the command (remaining parameters).
 3666: #    $client   - File descriptor connected to client.
 3667: # Returns
 3668: #     0        - Requested to exit, caller should shut down.
 3669: #     1        - Continue processing.
 3670: #  Side effects:
 3671: #     reply is written to $client.
 3672: #
 3673: sub put_domain_handler {
 3674:     my ($cmd,$tail,$client) = @_;
 3675: 
 3676:     my $userinput = "$cmd:$tail";
 3677: 
 3678:     my ($udom,$namespace,$what) =split(/:/,$tail,3);
 3679:     chomp($what);
 3680:     my @pairs=split(/\&/,$what);
 3681:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
 3682:                                    "P", $what);
 3683:     if ($hashref) {
 3684:         foreach my $pair (@pairs) {
 3685:             my ($key,$value)=split(/=/,$pair);
 3686:             $hashref->{$key}=$value;
 3687:         }
 3688:         if (&untie_domain_hash($hashref)) {
 3689:             &Reply($client, "ok\n", $userinput);
 3690:         } else {
 3691:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3692:                      "while attempting putdom\n", $userinput);
 3693:         }
 3694:     } else {
 3695:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3696:                   "while attempting putdom\n", $userinput);
 3697:     }
 3698: 
 3699:     return 1;
 3700: }
 3701: &register_handler("putdom", \&put_domain_handler, 0, 1, 0);
 3702: 
 3703: # Unencrypted get from the namespace database file at the domain level.
 3704: # This function retrieves a keyed item from a specific named database in the
 3705: # domain directory.
 3706: #
 3707: # Parameters:
 3708: #   $cmd             - Command request keyword (get).
 3709: #   $tail            - Tail of the command.  This is a colon separated list
 3710: #                      consisting of the domain and the 'namespace' 
 3711: #                      which selects the gdbm file to do the lookup in,
 3712: #                      & separated list of keys to lookup.  Note that
 3713: #                      the values are returned as an & separated list too.
 3714: #   $client          - File descriptor open on the client.
 3715: # Returns:
 3716: #   1       - Continue processing.
 3717: #   0       - Exit.
 3718: #  Side effects:
 3719: #     reply is written to $client.
 3720: #
 3721: 
 3722: sub get_domain_handler {
 3723:     my ($cmd, $tail, $client) = @_;
 3724: 
 3725:     my $userinput = "$client:$tail";
 3726: 
 3727:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
 3728:     chomp($what);
 3729:     my @queries=split(/\&/,$what);
 3730:     my $qresult='';
 3731:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
 3732:     if ($hashref) {
 3733:         for (my $i=0;$i<=$#queries;$i++) {
 3734:             $qresult.="$hashref->{$queries[$i]}&";
 3735:         }
 3736:         if (&untie_domain_hash($hashref)) {
 3737:             $qresult=~s/\&$//;
 3738:             &Reply($client, \$qresult, $userinput);
 3739:         } else {
 3740:             &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 3741:                       "while attempting getdom\n",$userinput);
 3742:         }
 3743:     } else {
 3744:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3745:                  "while attempting getdom\n",$userinput);
 3746:     }
 3747: 
 3748:     return 1;
 3749: }
 3750: &register_handler("getdom", \&get_domain_handler, 0, 1, 0);
 3751: 
 3752: 
 3753: #
 3754: #  Puts an id to a domains id database. 
 3755: #
 3756: #  Parameters:
 3757: #   $cmd     - The command that triggered us.
 3758: #   $tail    - Remainder of the request other than the command. This is a 
 3759: #              colon separated list containing:
 3760: #              $domain  - The domain for which we are writing the id.
 3761: #              $pairs  - The id info to write... this is and & separated list
 3762: #                        of keyword=value.
 3763: #   $client  - Socket open on the client.
 3764: #  Returns:
 3765: #    1   - Continue processing.
 3766: #  Side effects:
 3767: #     reply is written to $client.
 3768: #
 3769: sub put_id_handler {
 3770:     my ($cmd,$tail,$client) = @_;
 3771: 
 3772: 
 3773:     my $userinput = "$cmd:$tail";
 3774: 
 3775:     my ($udom,$what)=split(/:/,$tail);
 3776:     chomp($what);
 3777:     my @pairs=split(/\&/,$what);
 3778:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
 3779: 				   "P", $what);
 3780:     if ($hashref) {
 3781: 	foreach my $pair (@pairs) {
 3782: 	    my ($key,$value)=split(/=/,$pair);
 3783: 	    $hashref->{$key}=$value;
 3784: 	}
 3785: 	if (&untie_domain_hash($hashref)) {
 3786: 	    &Reply($client, "ok\n", $userinput);
 3787: 	} else {
 3788: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3789: 		     "while attempting idput\n", $userinput);
 3790: 	}
 3791:     } else {
 3792: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3793: 		  "while attempting idput\n", $userinput);
 3794:     }
 3795: 
 3796:     return 1;
 3797: }
 3798: &register_handler("idput", \&put_id_handler, 0, 1, 0);
 3799: 
 3800: #
 3801: #  Retrieves a set of id values from the id database.
 3802: #  Returns an & separated list of results, one for each requested id to the
 3803: #  client.
 3804: #
 3805: # Parameters:
 3806: #   $cmd       - Command keyword that caused us to be dispatched.
 3807: #   $tail      - Tail of the command.  Consists of a colon separated:
 3808: #               domain - the domain whose id table we dump
 3809: #               ids      Consists of an & separated list of
 3810: #                        id keywords whose values will be fetched.
 3811: #                        nonexisting keywords will have an empty value.
 3812: #   $client    - Socket open on the client.
 3813: #
 3814: # Returns:
 3815: #    1 - indicating processing should continue.
 3816: # Side effects:
 3817: #   An & separated list of results is written to $client.
 3818: #
 3819: sub get_id_handler {
 3820:     my ($cmd, $tail, $client) = @_;
 3821: 
 3822:     
 3823:     my $userinput = "$client:$tail";
 3824:     
 3825:     my ($udom,$what)=split(/:/,$tail);
 3826:     chomp($what);
 3827:     my @queries=split(/\&/,$what);
 3828:     my $qresult='';
 3829:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
 3830:     if ($hashref) {
 3831: 	for (my $i=0;$i<=$#queries;$i++) {
 3832: 	    $qresult.="$hashref->{$queries[$i]}&";
 3833: 	}
 3834: 	if (&untie_domain_hash($hashref)) {
 3835: 	    $qresult=~s/\&$//;
 3836: 	    &Reply($client, \$qresult, $userinput);
 3837: 	} else {
 3838: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 3839: 		      "while attempting idget\n",$userinput);
 3840: 	}
 3841:     } else {
 3842: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3843: 		 "while attempting idget\n",$userinput);
 3844:     }
 3845:     
 3846:     return 1;
 3847: }
 3848: &register_handler("idget", \&get_id_handler, 0, 1, 0);
 3849: 
 3850: #
 3851: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
 3852: #
 3853: # Parameters
 3854: #   $cmd       - Command keyword that caused us to be dispatched.
 3855: #   $tail      - Tail of the command.  Consists of a colon separated:
 3856: #               domain - the domain whose dcmail we are recording
 3857: #               email    Consists of key=value pair 
 3858: #                        where key is unique msgid
 3859: #                        and value is message (in XML)
 3860: #   $client    - Socket open on the client.
 3861: #
 3862: # Returns:
 3863: #    1 - indicating processing should continue.
 3864: # Side effects
 3865: #     reply is written to $client.
 3866: #
 3867: sub put_dcmail_handler {
 3868:     my ($cmd,$tail,$client) = @_;
 3869:     my $userinput = "$cmd:$tail";
 3870:                                                                                 
 3871:     my ($udom,$what)=split(/:/,$tail);
 3872:     chomp($what);
 3873:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
 3874:     if ($hashref) {
 3875:         my ($key,$value)=split(/=/,$what);
 3876:         $hashref->{$key}=$value;
 3877:     }
 3878:     if (&untie_domain_hash($hashref)) {
 3879:         &Reply($client, "ok\n", $userinput);
 3880:     } else {
 3881:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3882:                  "while attempting dcmailput\n", $userinput);
 3883:     }
 3884:     return 1;
 3885: }
 3886: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
 3887: 
 3888: #
 3889: # Retrieves broadcast e-mail from nohist_dcmail database
 3890: # Returns to client an & separated list of key=value pairs,
 3891: # where key is msgid and value is message information.
 3892: #
 3893: # Parameters
 3894: #   $cmd       - Command keyword that caused us to be dispatched.
 3895: #   $tail      - Tail of the command.  Consists of a colon separated:
 3896: #               domain - the domain whose dcmail table we dump
 3897: #               startfilter - beginning of time window 
 3898: #               endfilter - end of time window
 3899: #               sendersfilter - & separated list of username:domain 
 3900: #                 for senders to search for.
 3901: #   $client    - Socket open on the client.
 3902: #
 3903: # Returns:
 3904: #    1 - indicating processing should continue.
 3905: # Side effects
 3906: #     reply (& separated list of msgid=messageinfo pairs) is 
 3907: #     written to $client.
 3908: #
 3909: sub dump_dcmail_handler {
 3910:     my ($cmd, $tail, $client) = @_;
 3911:                                                                                 
 3912:     my $userinput = "$cmd:$tail";
 3913:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
 3914:     chomp($sendersfilter);
 3915:     my @senders = ();
 3916:     if (defined($startfilter)) {
 3917:         $startfilter=&unescape($startfilter);
 3918:     } else {
 3919:         $startfilter='.';
 3920:     }
 3921:     if (defined($endfilter)) {
 3922:         $endfilter=&unescape($endfilter);
 3923:     } else {
 3924:         $endfilter='.';
 3925:     }
 3926:     if (defined($sendersfilter)) {
 3927:         $sendersfilter=&unescape($sendersfilter);
 3928: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
 3929:     }
 3930: 
 3931:     my $qresult='';
 3932:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
 3933:     if ($hashref) {
 3934:         while (my ($key,$value) = each(%$hashref)) {
 3935:             my $match = 1;
 3936:             my ($timestamp,$subj,$uname,$udom) = 
 3937: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
 3938:             $subj = &unescape($subj);
 3939:             unless ($startfilter eq '.' || !defined($startfilter)) {
 3940:                 if ($timestamp < $startfilter) {
 3941:                     $match = 0;
 3942:                 }
 3943:             }
 3944:             unless ($endfilter eq '.' || !defined($endfilter)) {
 3945:                 if ($timestamp > $endfilter) {
 3946:                     $match = 0;
 3947:                 }
 3948:             }
 3949:             unless (@senders < 1) {
 3950:                 unless (grep/^$uname:$udom$/,@senders) {
 3951:                     $match = 0;
 3952:                 }
 3953:             }
 3954:             if ($match == 1) {
 3955:                 $qresult.=$key.'='.$value.'&';
 3956:             }
 3957:         }
 3958:         if (&untie_domain_hash($hashref)) {
 3959:             chop($qresult);
 3960:             &Reply($client, \$qresult, $userinput);
 3961:         } else {
 3962:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3963:                     "while attempting dcmaildump\n", $userinput);
 3964:         }
 3965:     } else {
 3966:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3967:                 "while attempting dcmaildump\n", $userinput);
 3968:     }
 3969:     return 1;
 3970: }
 3971: 
 3972: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
 3973: 
 3974: #
 3975: # Puts domain roles in nohist_domainroles database
 3976: #
 3977: # Parameters
 3978: #   $cmd       - Command keyword that caused us to be dispatched.
 3979: #   $tail      - Tail of the command.  Consists of a colon separated:
 3980: #               domain - the domain whose roles we are recording  
 3981: #               role -   Consists of key=value pair
 3982: #                        where key is unique role
 3983: #                        and value is start/end date information
 3984: #   $client    - Socket open on the client.
 3985: #
 3986: # Returns:
 3987: #    1 - indicating processing should continue.
 3988: # Side effects
 3989: #     reply is written to $client.
 3990: #
 3991: 
 3992: sub put_domainroles_handler {
 3993:     my ($cmd,$tail,$client) = @_;
 3994: 
 3995:     my $userinput = "$cmd:$tail";
 3996:     my ($udom,$what)=split(/:/,$tail);
 3997:     chomp($what);
 3998:     my @pairs=split(/\&/,$what);
 3999:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
 4000:     if ($hashref) {
 4001:         foreach my $pair (@pairs) {
 4002:             my ($key,$value)=split(/=/,$pair);
 4003:             $hashref->{$key}=$value;
 4004:         }
 4005:         if (&untie_domain_hash($hashref)) {
 4006:             &Reply($client, "ok\n", $userinput);
 4007:         } else {
 4008:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4009:                      "while attempting domroleput\n", $userinput);
 4010:         }
 4011:     } else {
 4012:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 4013:                   "while attempting domroleput\n", $userinput);
 4014:     }
 4015:                                                                                   
 4016:     return 1;
 4017: }
 4018: 
 4019: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
 4020: 
 4021: #
 4022: # Retrieves domain roles from nohist_domainroles database
 4023: # Returns to client an & separated list of key=value pairs,
 4024: # where key is role and value is start and end date information.
 4025: #
 4026: # Parameters
 4027: #   $cmd       - Command keyword that caused us to be dispatched.
 4028: #   $tail      - Tail of the command.  Consists of a colon separated:
 4029: #               domain - the domain whose domain roles table we dump
 4030: #   $client    - Socket open on the client.
 4031: #
 4032: # Returns:
 4033: #    1 - indicating processing should continue.
 4034: # Side effects
 4035: #     reply (& separated list of role=start/end info pairs) is
 4036: #     written to $client.
 4037: #
 4038: sub dump_domainroles_handler {
 4039:     my ($cmd, $tail, $client) = @_;
 4040:                                                                                            
 4041:     my $userinput = "$cmd:$tail";
 4042:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
 4043:     chomp($rolesfilter);
 4044:     my @roles = ();
 4045:     if (defined($startfilter)) {
 4046:         $startfilter=&unescape($startfilter);
 4047:     } else {
 4048:         $startfilter='.';
 4049:     }
 4050:     if (defined($endfilter)) {
 4051:         $endfilter=&unescape($endfilter);
 4052:     } else {
 4053:         $endfilter='.';
 4054:     }
 4055:     if (defined($rolesfilter)) {
 4056:         $rolesfilter=&unescape($rolesfilter);
 4057: 	@roles = split(/\&/,$rolesfilter);
 4058:     }
 4059:                                                                                            
 4060:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
 4061:     if ($hashref) {
 4062:         my $qresult = '';
 4063:         while (my ($key,$value) = each(%$hashref)) {
 4064:             my $match = 1;
 4065:             my ($start,$end) = split(/:/,&unescape($value));
 4066:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
 4067:             unless ($startfilter eq '.' || !defined($startfilter)) {
 4068:                 if ($start >= $startfilter) {
 4069:                     $match = 0;
 4070:                 }
 4071:             }
 4072:             unless ($endfilter eq '.' || !defined($endfilter)) {
 4073:                 if ($end <= $endfilter) {
 4074:                     $match = 0;
 4075:                 }
 4076:             }
 4077:             unless (@roles < 1) {
 4078:                 unless (grep/^\Q$trole\E$/,@roles) {
 4079:                     $match = 0;
 4080:                 }
 4081:             }
 4082:             if ($match == 1) {
 4083:                 $qresult.=$key.'='.$value.'&';
 4084:             }
 4085:         }
 4086:         if (&untie_domain_hash($hashref)) {
 4087:             chop($qresult);
 4088:             &Reply($client, \$qresult, $userinput);
 4089:         } else {
 4090:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4091:                     "while attempting domrolesdump\n", $userinput);
 4092:         }
 4093:     } else {
 4094:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 4095:                 "while attempting domrolesdump\n", $userinput);
 4096:     }
 4097:     return 1;
 4098: }
 4099: 
 4100: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
 4101: 
 4102: 
 4103: #  Process the tmpput command I'm not sure what this does.. Seems to
 4104: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
 4105: # where Id is the client's ip concatenated with a sequence number.
 4106: # The file will contain some value that is passed in.  Is this e.g.
 4107: # a login token?
 4108: #
 4109: # Parameters:
 4110: #    $cmd     - The command that got us dispatched.
 4111: #    $tail    - The remainder of the request following $cmd:
 4112: #               In this case this will be the contents of the file.
 4113: #    $client  - Socket connected to the client.
 4114: # Returns:
 4115: #    1 indicating processing can continue.
 4116: # Side effects:
 4117: #   A file is created in the local filesystem.
 4118: #   A reply is sent to the client.
 4119: sub tmp_put_handler {
 4120:     my ($cmd, $what, $client) = @_;
 4121: 
 4122:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
 4123: 
 4124:     my ($record,$context) = split(/:/,$what);
 4125:     if ($context ne '') {
 4126:         chomp($context);
 4127:         $context = &unescape($context);
 4128:     }
 4129:     my ($id,$store);
 4130:     $tmpsnum++;
 4131:     if ($context eq 'resetpw') {
 4132:         $id = &md5_hex(&md5_hex(time.{}.rand().$$));
 4133:     } else {
 4134:         $id = $$.'_'.$clientip.'_'.$tmpsnum;
 4135:     }
 4136:     $id=~s/\W/\_/g;
 4137:     $record=~s/\n//g;
 4138:     my $execdir=$perlvar{'lonDaemons'};
 4139:     if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
 4140: 	print $store $record;
 4141: 	close $store;
 4142: 	&Reply($client, \$id, $userinput);
 4143:     } else {
 4144: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
 4145: 		  "while attempting tmpput\n", $userinput);
 4146:     }
 4147:     return 1;
 4148:   
 4149: }
 4150: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
 4151: 
 4152: #   Processes the tmpget command.  This command returns the contents
 4153: #  of a temporary resource file(?) created via tmpput.
 4154: #
 4155: # Paramters:
 4156: #    $cmd      - Command that got us dispatched.
 4157: #    $id       - Tail of the command, contain the id of the resource
 4158: #                we want to fetch.
 4159: #    $client   - socket open on the client.
 4160: # Return:
 4161: #    1         - Inidcating processing can continue.
 4162: # Side effects:
 4163: #   A reply is sent to the client.
 4164: #
 4165: sub tmp_get_handler {
 4166:     my ($cmd, $id, $client) = @_;
 4167: 
 4168:     my $userinput = "$cmd:$id"; 
 4169:     
 4170: 
 4171:     $id=~s/\W/\_/g;
 4172:     my $store;
 4173:     my $execdir=$perlvar{'lonDaemons'};
 4174:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
 4175: 	my $reply=<$store>;
 4176: 	&Reply( $client, \$reply, $userinput);
 4177: 	close $store;
 4178:     } else {
 4179: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
 4180: 		  "while attempting tmpget\n", $userinput);
 4181:     }
 4182: 
 4183:     return 1;
 4184: }
 4185: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
 4186: 
 4187: #
 4188: #  Process the tmpdel command.  This command deletes a temp resource
 4189: #  created by the tmpput command.
 4190: #
 4191: # Parameters:
 4192: #   $cmd      - Command that got us here.
 4193: #   $id       - Id of the temporary resource created.
 4194: #   $client   - socket open on the client process.
 4195: #
 4196: # Returns:
 4197: #   1     - Indicating processing should continue.
 4198: # Side Effects:
 4199: #   A file is deleted
 4200: #   A reply is sent to the client.
 4201: sub tmp_del_handler {
 4202:     my ($cmd, $id, $client) = @_;
 4203:     
 4204:     my $userinput= "$cmd:$id";
 4205:     
 4206:     chomp($id);
 4207:     $id=~s/\W/\_/g;
 4208:     my $execdir=$perlvar{'lonDaemons'};
 4209:     if (unlink("$execdir/tmp/$id.tmp")) {
 4210: 	&Reply($client, "ok\n", $userinput);
 4211:     } else {
 4212: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
 4213: 		  "while attempting tmpdel\n", $userinput);
 4214:     }
 4215:     
 4216:     return 1;
 4217: 
 4218: }
 4219: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
 4220: 
 4221: #
 4222: #   Processes the setannounce command.  This command
 4223: #   creates a file named announce.txt in the top directory of
 4224: #   the documentn root and sets its contents.  The announce.txt file is
 4225: #   printed in its entirety at the LonCAPA login page.  Note:
 4226: #   once the announcement.txt fileis created it cannot be deleted.
 4227: #   However, setting the contents of the file to empty removes the
 4228: #   announcement from the login page of loncapa so who cares.
 4229: #
 4230: # Parameters:
 4231: #    $cmd          - The command that got us dispatched.
 4232: #    $announcement - The text of the announcement.
 4233: #    $client       - Socket open on the client process.
 4234: # Retunrns:
 4235: #   1             - Indicating request processing should continue
 4236: # Side Effects:
 4237: #   The file {DocRoot}/announcement.txt is created.
 4238: #   A reply is sent to $client.
 4239: #
 4240: sub set_announce_handler {
 4241:     my ($cmd, $announcement, $client) = @_;
 4242:   
 4243:     my $userinput    = "$cmd:$announcement";
 4244: 
 4245:     chomp($announcement);
 4246:     $announcement=&unescape($announcement);
 4247:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
 4248: 				'/announcement.txt')) {
 4249: 	print $store $announcement;
 4250: 	close $store;
 4251: 	&Reply($client, "ok\n", $userinput);
 4252:     } else {
 4253: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
 4254:     }
 4255: 
 4256:     return 1;
 4257: }
 4258: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
 4259: 
 4260: #
 4261: #  Return the version of the daemon.  This can be used to determine
 4262: #  the compatibility of cross version installations or, alternatively to
 4263: #  simply know who's out of date and who isn't.  Note that the version
 4264: #  is returned concatenated with the tail.
 4265: # Parameters:
 4266: #   $cmd        - the request that dispatched to us.
 4267: #   $tail       - Tail of the request (client's version?).
 4268: #   $client     - Socket open on the client.
 4269: #Returns:
 4270: #   1 - continue processing requests.
 4271: # Side Effects:
 4272: #   Replies with version to $client.
 4273: sub get_version_handler {
 4274:     my ($cmd, $tail, $client) = @_;
 4275: 
 4276:     my $userinput  = $cmd.$tail;
 4277:     
 4278:     &Reply($client, &version($userinput)."\n", $userinput);
 4279: 
 4280: 
 4281:     return 1;
 4282: }
 4283: &register_handler("version", \&get_version_handler, 0, 1, 0);
 4284: 
 4285: #  Set the current host and domain.  This is used to support
 4286: #  multihomed systems.  Each IP of the system, or even separate daemons
 4287: #  on the same IP can be treated as handling a separate lonCAPA virtual
 4288: #  machine.  This command selects the virtual lonCAPA.  The client always
 4289: #  knows the right one since it is lonc and it is selecting the domain/system
 4290: #  from the hosts.tab file.
 4291: # Parameters:
 4292: #    $cmd      - Command that dispatched us.
 4293: #    $tail     - Tail of the command (domain/host requested).
 4294: #    $socket   - Socket open on the client.
 4295: #
 4296: # Returns:
 4297: #     1   - Indicates the program should continue to process requests.
 4298: # Side-effects:
 4299: #     The default domain/system context is modified for this daemon.
 4300: #     a reply is sent to the client.
 4301: #
 4302: sub set_virtual_host_handler {
 4303:     my ($cmd, $tail, $socket) = @_;
 4304:   
 4305:     my $userinput  ="$cmd:$tail";
 4306: 
 4307:     &Reply($client, &sethost($userinput)."\n", $userinput);
 4308: 
 4309: 
 4310:     return 1;
 4311: }
 4312: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
 4313: 
 4314: #  Process a request to exit:
 4315: #   - "bye" is sent to the client.
 4316: #   - The client socket is shutdown and closed.
 4317: #   - We indicate to the caller that we should exit.
 4318: # Formal Parameters:
 4319: #   $cmd                - The command that got us here.
 4320: #   $tail               - Tail of the command (empty).
 4321: #   $client             - Socket open on the tail.
 4322: # Returns:
 4323: #   0      - Indicating the program should exit!!
 4324: #
 4325: sub exit_handler {
 4326:     my ($cmd, $tail, $client) = @_;
 4327: 
 4328:     my $userinput = "$cmd:$tail";
 4329: 
 4330:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
 4331:     &Reply($client, "bye\n", $userinput);
 4332:     $client->shutdown(2);        # shutdown the socket forcibly.
 4333:     $client->close();
 4334: 
 4335:     return 0;
 4336: }
 4337: &register_handler("exit", \&exit_handler, 0,1,1);
 4338: &register_handler("init", \&exit_handler, 0,1,1);
 4339: &register_handler("quit", \&exit_handler, 0,1,1);
 4340: 
 4341: #  Determine if auto-enrollment is enabled.
 4342: #  Note that the original had what I believe to be a defect.
 4343: #  The original returned 0 if the requestor was not a registerd client.
 4344: #  It should return "refused".
 4345: # Formal Parameters:
 4346: #   $cmd       - The command that invoked us.
 4347: #   $tail      - The tail of the command (Extra command parameters.
 4348: #   $client    - The socket open on the client that issued the request.
 4349: # Returns:
 4350: #    1         - Indicating processing should continue.
 4351: #
 4352: sub enrollment_enabled_handler {
 4353:     my ($cmd, $tail, $client) = @_;
 4354:     my $userinput = $cmd.":".$tail; # For logging purposes.
 4355: 
 4356:     
 4357:     my ($cdom) = split(/:/, $tail, 2);   # Domain we're asking about.
 4358: 
 4359:     my $outcome  = &localenroll::run($cdom);
 4360:     &Reply($client, \$outcome, $userinput);
 4361: 
 4362:     return 1;
 4363: }
 4364: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
 4365: 
 4366: #   Get the official sections for which auto-enrollment is possible.
 4367: #   Since the admin people won't know about 'unofficial sections' 
 4368: #   we cannot auto-enroll on them.
 4369: # Formal Parameters:
 4370: #    $cmd     - The command request that got us dispatched here.
 4371: #    $tail    - The remainder of the request.  In our case this
 4372: #               will be split into:
 4373: #               $coursecode   - The course name from the admin point of view.
 4374: #               $cdom         - The course's domain(?).
 4375: #    $client  - Socket open on the client.
 4376: # Returns:
 4377: #    1    - Indiciting processing should continue.
 4378: #
 4379: sub get_sections_handler {
 4380:     my ($cmd, $tail, $client) = @_;
 4381:     my $userinput = "$cmd:$tail";
 4382: 
 4383:     my ($coursecode, $cdom) = split(/:/, $tail);
 4384:     my @secs = &localenroll::get_sections($coursecode,$cdom);
 4385:     my $seclist = &escape(join(':',@secs));
 4386: 
 4387:     &Reply($client, \$seclist, $userinput);
 4388:     
 4389: 
 4390:     return 1;
 4391: }
 4392: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
 4393: 
 4394: #   Validate the owner of a new course section.  
 4395: #
 4396: # Formal Parameters:
 4397: #   $cmd      - Command that got us dispatched.
 4398: #   $tail     - the remainder of the command.  For us this consists of a
 4399: #               colon separated string containing:
 4400: #                  $inst    - Course Id from the institutions point of view.
 4401: #                  $owner   - Proposed owner of the course.
 4402: #                  $cdom    - Domain of the course (from the institutions
 4403: #                             point of view?)..
 4404: #   $client   - Socket open on the client.
 4405: #
 4406: # Returns:
 4407: #   1        - Processing should continue.
 4408: #
 4409: sub validate_course_owner_handler {
 4410:     my ($cmd, $tail, $client)  = @_;
 4411:     my $userinput = "$cmd:$tail";
 4412:     my ($inst_course_id, $owner, $cdom) = split(/:/, $tail);
 4413: 
 4414:     $owner = &unescape($owner);
 4415:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom);
 4416:     &Reply($client, \$outcome, $userinput);
 4417: 
 4418: 
 4419: 
 4420:     return 1;
 4421: }
 4422: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
 4423: 
 4424: #
 4425: #   Validate a course section in the official schedule of classes
 4426: #   from the institutions point of view (part of autoenrollment).
 4427: #
 4428: # Formal Parameters:
 4429: #   $cmd          - The command request that got us dispatched.
 4430: #   $tail         - The tail of the command.  In this case,
 4431: #                   this is a colon separated set of words that will be split
 4432: #                   into:
 4433: #                        $inst_course_id - The course/section id from the
 4434: #                                          institutions point of view.
 4435: #                        $cdom           - The domain from the institutions
 4436: #                                          point of view.
 4437: #   $client       - Socket open on the client.
 4438: # Returns:
 4439: #    1           - Indicating processing should continue.
 4440: #
 4441: sub validate_course_section_handler {
 4442:     my ($cmd, $tail, $client) = @_;
 4443:     my $userinput = "$cmd:$tail";
 4444:     my ($inst_course_id, $cdom) = split(/:/, $tail);
 4445: 
 4446:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
 4447:     &Reply($client, \$outcome, $userinput);
 4448: 
 4449: 
 4450:     return 1;
 4451: }
 4452: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
 4453: 
 4454: #
 4455: #   Validate course owner's access to enrollment data for specific class section. 
 4456: #   
 4457: #
 4458: # Formal Parameters:
 4459: #    $cmd     - The command request that got us dispatched.
 4460: #    $tail    - The tail of the command.   In this case this is a colon separated
 4461: #               set of words that will be split into:
 4462: #               $inst_class  - Institutional code for the specific class section   
 4463: #               $courseowner - The escaped username:domain of the course owner 
 4464: #               $cdom        - The domain of the course from the institution's
 4465: #                              point of view.
 4466: #    $client  - The socket open on the client.
 4467: # Returns:
 4468: #    1 - continue processing.
 4469: #
 4470: 
 4471: sub validate_class_access_handler {
 4472:     my ($cmd, $tail, $client) = @_;
 4473:     my $userinput = "$cmd:$tail";
 4474:     my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
 4475:     my $owners = &unescape($ownerlist);
 4476:     my $outcome;
 4477:     eval {
 4478: 	local($SIG{__DIE__})='DEFAULT';
 4479: 	$outcome=&localenroll::check_section($inst_class,$owners,$cdom);
 4480:     };
 4481:     &Reply($client,\$outcome, $userinput);
 4482: 
 4483:     return 1;
 4484: }
 4485: &register_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
 4486: 
 4487: #
 4488: #   Create a password for a new LON-CAPA user added by auto-enrollment.
 4489: #   Only used for case where authentication method for new user is localauth
 4490: #
 4491: # Formal Parameters:
 4492: #    $cmd     - The command request that got us dispatched.
 4493: #    $tail    - The tail of the command.   In this case this is a colon separated
 4494: #               set of words that will be split into:
 4495: #               $authparam - An authentication parameter (localauth parameter).
 4496: #               $cdom      - The domain of the course from the institution's
 4497: #                            point of view.
 4498: #    $client  - The socket open on the client.
 4499: # Returns:
 4500: #    1 - continue processing.
 4501: #
 4502: sub create_auto_enroll_password_handler {
 4503:     my ($cmd, $tail, $client) = @_;
 4504:     my $userinput = "$cmd:$tail";
 4505: 
 4506:     my ($authparam, $cdom) = split(/:/, $userinput);
 4507: 
 4508:     my ($create_passwd,$authchk);
 4509:     ($authparam,
 4510:      $create_passwd,
 4511:      $authchk) = &localenroll::create_password($authparam,$cdom);
 4512: 
 4513:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
 4514: 	   $userinput);
 4515: 
 4516: 
 4517:     return 1;
 4518: }
 4519: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
 4520: 		  0, 1, 0);
 4521: 
 4522: #   Retrieve and remove temporary files created by/during autoenrollment.
 4523: #
 4524: # Formal Parameters:
 4525: #    $cmd      - The command that got us dispatched.
 4526: #    $tail     - The tail of the command.  In our case this is a colon 
 4527: #                separated list that will be split into:
 4528: #                $filename - The name of the file to remove.
 4529: #                            The filename is given as a path relative to
 4530: #                            the LonCAPA temp file directory.
 4531: #    $client   - Socket open on the client.
 4532: #
 4533: # Returns:
 4534: #   1     - Continue processing.
 4535: sub retrieve_auto_file_handler {
 4536:     my ($cmd, $tail, $client)    = @_;
 4537:     my $userinput                = "cmd:$tail";
 4538: 
 4539:     my ($filename)   = split(/:/, $tail);
 4540: 
 4541:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
 4542:     if ( (-e $source) && ($filename ne '') ) {
 4543: 	my $reply = '';
 4544: 	if (open(my $fh,$source)) {
 4545: 	    while (<$fh>) {
 4546: 		chomp($_);
 4547: 		$_ =~ s/^\s+//g;
 4548: 		$_ =~ s/\s+$//g;
 4549: 		$reply .= $_;
 4550: 	    }
 4551: 	    close($fh);
 4552: 	    &Reply($client, &escape($reply)."\n", $userinput);
 4553: 
 4554: #   Does this have to be uncommented??!?  (RF).
 4555: #
 4556: #                                unlink($source);
 4557: 	} else {
 4558: 	    &Failure($client, "error\n", $userinput);
 4559: 	}
 4560:     } else {
 4561: 	&Failure($client, "error\n", $userinput);
 4562:     }
 4563:     
 4564: 
 4565:     return 1;
 4566: }
 4567: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
 4568: 
 4569: #
 4570: #   Read and retrieve institutional code format (for support form).
 4571: # Formal Parameters:
 4572: #    $cmd        - Command that dispatched us.
 4573: #    $tail       - Tail of the command.  In this case it conatins 
 4574: #                  the course domain and the coursename.
 4575: #    $client     - Socket open on the client.
 4576: # Returns:
 4577: #    1     - Continue processing.
 4578: #
 4579: sub get_institutional_code_format_handler {
 4580:     my ($cmd, $tail, $client)   = @_;
 4581:     my $userinput               = "$cmd:$tail";
 4582: 
 4583:     my $reply;
 4584:     my($cdom,$course) = split(/:/,$tail);
 4585:     my @pairs = split/\&/,$course;
 4586:     my %instcodes = ();
 4587:     my %codes = ();
 4588:     my @codetitles = ();
 4589:     my %cat_titles = ();
 4590:     my %cat_order = ();
 4591:     foreach (@pairs) {
 4592: 	my ($key,$value) = split/=/,$_;
 4593: 	$instcodes{&unescape($key)} = &unescape($value);
 4594:     }
 4595:     my $formatreply = &localenroll::instcode_format($cdom,
 4596: 						    \%instcodes,
 4597: 						    \%codes,
 4598: 						    \@codetitles,
 4599: 						    \%cat_titles,
 4600: 						    \%cat_order);
 4601:     if ($formatreply eq 'ok') {
 4602: 	my $codes_str = &Apache::lonnet::hash2str(%codes);
 4603: 	my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
 4604: 	my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
 4605: 	my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
 4606: 	&Reply($client,
 4607: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
 4608: 	       .$cat_order_str."\n",
 4609: 	       $userinput);
 4610:     } else {
 4611: 	# this else branch added by RF since if not ok, lonc will
 4612: 	# hang waiting on reply until timeout.
 4613: 	#
 4614: 	&Reply($client, "format_error\n", $userinput);
 4615:     }
 4616:     
 4617:     return 1;
 4618: }
 4619: &register_handler("autoinstcodeformat",
 4620: 		  \&get_institutional_code_format_handler,0,1,0);
 4621: 
 4622: sub get_institutional_defaults_handler {
 4623:     my ($cmd, $tail, $client)   = @_;
 4624:     my $userinput               = "$cmd:$tail";
 4625: 
 4626:     my $dom = $tail;
 4627:     my %defaults_hash;
 4628:     my @code_order;
 4629:     my $outcome;
 4630:     eval {
 4631:         local($SIG{__DIE__})='DEFAULT';
 4632:         $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
 4633:                                                    \@code_order);
 4634:     };
 4635:     if (!$@) {
 4636:         if ($outcome eq 'ok') {
 4637:             my $result='';
 4638:             while (my ($key,$value) = each(%defaults_hash)) {
 4639:                 $result.=&escape($key).'='.&escape($value).'&';
 4640:             }
 4641:             $result .= 'code_order='.&escape(join('&',@code_order));
 4642:             &Reply($client,\$result,$userinput);
 4643:         } else {
 4644:             &Reply($client,"error\n", $userinput);
 4645:         }
 4646:     } else {
 4647:         &Failure($client,"unknown_cmd\n",$userinput);
 4648:     }
 4649: }
 4650: &register_handler("autoinstcodedefaults",
 4651:                   \&get_institutional_defaults_handler,0,1,0);
 4652: 
 4653: sub get_institutional_user_rules {
 4654:     my ($cmd, $tail, $client)   = @_;
 4655:     my $userinput               = "$cmd:$tail";
 4656:     my $dom = &unescape($tail);
 4657:     my (%rules_hash,@rules_order);
 4658:     my $outcome;
 4659:     eval {
 4660:         local($SIG{__DIE__})='DEFAULT';
 4661:         $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
 4662:     };
 4663:     if (!$@) {
 4664:         if ($outcome eq 'ok') {
 4665:             my $result;
 4666:             foreach my $key (keys(%rules_hash)) {
 4667:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
 4668:             }
 4669:             $result =~ s/\&$//;
 4670:             $result .= ':';
 4671:             if (@rules_order > 0) {
 4672:                 foreach my $item (@rules_order) {
 4673:                     $result .= &escape($item).'&';
 4674:                 }
 4675:             }
 4676:             $result =~ s/\&$//;
 4677:             &Reply($client,\$result,$userinput);
 4678:         } else {
 4679:             &Reply($client,"error\n", $userinput);
 4680:         }
 4681:     } else {
 4682:         &Failure($client,"unknown_cmd\n",$userinput);
 4683:     }
 4684: }
 4685: &register_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
 4686: 
 4687: sub get_institutional_id_rules {
 4688:     my ($cmd, $tail, $client)   = @_;
 4689:     my $userinput               = "$cmd:$tail";
 4690:     my $dom = &unescape($tail);
 4691:     my (%rules_hash,@rules_order);
 4692:     my $outcome;
 4693:     eval {
 4694:         local($SIG{__DIE__})='DEFAULT';
 4695:         $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
 4696:     };
 4697:     if (!$@) {
 4698:         if ($outcome eq 'ok') {
 4699:             my $result;
 4700:             foreach my $key (keys(%rules_hash)) {
 4701:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
 4702:             }
 4703:             $result =~ s/\&$//;
 4704:             $result .= ':';
 4705:             if (@rules_order > 0) {
 4706:                 foreach my $item (@rules_order) {
 4707:                     $result .= &escape($item).'&';
 4708:                 }
 4709:             }
 4710:             $result =~ s/\&$//;
 4711:             &Reply($client,\$result,$userinput);
 4712:         } else {
 4713:             &Reply($client,"error\n", $userinput);
 4714:         }
 4715:     } else {
 4716:         &Failure($client,"unknown_cmd\n",$userinput);
 4717:     }
 4718: }
 4719: &register_handler("instidrules",\&get_institutional_id_rules,0,1,0);
 4720: 
 4721: sub get_institutional_selfcreate_rules {
 4722:     my ($cmd, $tail, $client)   = @_;
 4723:     my $userinput               = "$cmd:$tail";
 4724:     my $dom = &unescape($tail);
 4725:     my (%rules_hash,@rules_order);
 4726:     my $outcome;
 4727:     eval {
 4728:         local($SIG{__DIE__})='DEFAULT';
 4729:         $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
 4730:     };
 4731:     if (!$@) {
 4732:         if ($outcome eq 'ok') {
 4733:             my $result;
 4734:             foreach my $key (keys(%rules_hash)) {
 4735:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
 4736:             }
 4737:             $result =~ s/\&$//;
 4738:             $result .= ':';
 4739:             if (@rules_order > 0) {
 4740:                 foreach my $item (@rules_order) {
 4741:                     $result .= &escape($item).'&';
 4742:                 }
 4743:             }
 4744:             $result =~ s/\&$//;
 4745:             &Reply($client,\$result,$userinput);
 4746:         } else {
 4747:             &Reply($client,"error\n", $userinput);
 4748:         }
 4749:     } else {
 4750:         &Failure($client,"unknown_cmd\n",$userinput);
 4751:     }
 4752: }
 4753: &register_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
 4754: 
 4755: 
 4756: sub institutional_username_check {
 4757:     my ($cmd, $tail, $client)   = @_;
 4758:     my $userinput               = "$cmd:$tail";
 4759:     my %rulecheck;
 4760:     my $outcome;
 4761:     my ($udom,$uname,@rules) = split(/:/,$tail);
 4762:     $udom = &unescape($udom);
 4763:     $uname = &unescape($uname);
 4764:     @rules = map {&unescape($_);} (@rules);
 4765:     eval {
 4766:         local($SIG{__DIE__})='DEFAULT';
 4767:         $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
 4768:     };
 4769:     if (!$@) {
 4770:         if ($outcome eq 'ok') {
 4771:             my $result='';
 4772:             foreach my $key (keys(%rulecheck)) {
 4773:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
 4774:             }
 4775:             &Reply($client,\$result,$userinput);
 4776:         } else {
 4777:             &Reply($client,"error\n", $userinput);
 4778:         }
 4779:     } else {
 4780:         &Failure($client,"unknown_cmd\n",$userinput);
 4781:     }
 4782: }
 4783: &register_handler("instrulecheck",\&institutional_username_check,0,1,0);
 4784: 
 4785: sub institutional_id_check {
 4786:     my ($cmd, $tail, $client)   = @_;
 4787:     my $userinput               = "$cmd:$tail";
 4788:     my %rulecheck;
 4789:     my $outcome;
 4790:     my ($udom,$id,@rules) = split(/:/,$tail);
 4791:     $udom = &unescape($udom);
 4792:     $id = &unescape($id);
 4793:     @rules = map {&unescape($_);} (@rules);
 4794:     eval {
 4795:         local($SIG{__DIE__})='DEFAULT';
 4796:         $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
 4797:     };
 4798:     if (!$@) {
 4799:         if ($outcome eq 'ok') {
 4800:             my $result='';
 4801:             foreach my $key (keys(%rulecheck)) {
 4802:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
 4803:             }
 4804:             &Reply($client,\$result,$userinput);
 4805:         } else {
 4806:             &Reply($client,"error\n", $userinput);
 4807:         }
 4808:     } else {
 4809:         &Failure($client,"unknown_cmd\n",$userinput);
 4810:     }
 4811: }
 4812: &register_handler("instidrulecheck",\&institutional_id_check,0,1,0);
 4813: 
 4814: sub institutional_selfcreate_check {
 4815:     my ($cmd, $tail, $client)   = @_;
 4816:     my $userinput               = "$cmd:$tail";
 4817:     my %rulecheck;
 4818:     my $outcome;
 4819:     my ($udom,$email,@rules) = split(/:/,$tail);
 4820:     $udom = &unescape($udom);
 4821:     $email = &unescape($email);
 4822:     @rules = map {&unescape($_);} (@rules);
 4823:     eval {
 4824:         local($SIG{__DIE__})='DEFAULT';
 4825:         $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
 4826:     };
 4827:     if (!$@) {
 4828:         if ($outcome eq 'ok') {
 4829:             my $result='';
 4830:             foreach my $key (keys(%rulecheck)) {
 4831:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
 4832:             }
 4833:             &Reply($client,\$result,$userinput);
 4834:         } else {
 4835:             &Reply($client,"error\n", $userinput);
 4836:         }
 4837:     } else {
 4838:         &Failure($client,"unknown_cmd\n",$userinput);
 4839:     }
 4840: }
 4841: &register_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
 4842: 
 4843: # Get domain specific conditions for import of student photographs to a course
 4844: #
 4845: # Retrieves information from photo_permission subroutine in localenroll.
 4846: # Returns outcome (ok) if no processing errors, and whether course owner is 
 4847: # required to accept conditions of use (yes/no).
 4848: #
 4849: #    
 4850: sub photo_permission_handler {
 4851:     my ($cmd, $tail, $client)   = @_;
 4852:     my $userinput               = "$cmd:$tail";
 4853:     my $cdom = $tail;
 4854:     my ($perm_reqd,$conditions);
 4855:     my $outcome;
 4856:     eval {
 4857: 	local($SIG{__DIE__})='DEFAULT';
 4858: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
 4859: 						  \$conditions);
 4860:     };
 4861:     if (!$@) {
 4862: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
 4863: 	       $userinput);
 4864:     } else {
 4865: 	&Failure($client,"unknown_cmd\n",$userinput);
 4866:     }
 4867:     return 1;
 4868: }
 4869: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
 4870: 
 4871: #
 4872: # Checks if student photo is available for a user in the domain, in the user's
 4873: # directory (in /userfiles/internal/studentphoto.jpg).
 4874: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
 4875: # the student's photo.   
 4876: 
 4877: sub photo_check_handler {
 4878:     my ($cmd, $tail, $client)   = @_;
 4879:     my $userinput               = "$cmd:$tail";
 4880:     my ($udom,$uname,$pid) = split(/:/,$tail);
 4881:     $udom = &unescape($udom);
 4882:     $uname = &unescape($uname);
 4883:     $pid = &unescape($pid);
 4884:     my $path=&propath($udom,$uname).'/userfiles/internal/';
 4885:     if (!-e $path) {
 4886:         &mkpath($path);
 4887:     }
 4888:     my $response;
 4889:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
 4890:     $result .= ':'.$response;
 4891:     &Reply($client, &escape($result)."\n",$userinput);
 4892:     return 1;
 4893: }
 4894: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
 4895: 
 4896: #
 4897: # Retrieve information from localenroll about whether to provide a button     
 4898: # for users who have enbled import of student photos to initiate an 
 4899: # update of photo files for registered students. Also include 
 4900: # comment to display alongside button.  
 4901: 
 4902: sub photo_choice_handler {
 4903:     my ($cmd, $tail, $client) = @_;
 4904:     my $userinput             = "$cmd:$tail";
 4905:     my $cdom                  = &unescape($tail);
 4906:     my ($update,$comment);
 4907:     eval {
 4908: 	local($SIG{__DIE__})='DEFAULT';
 4909: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
 4910:     };
 4911:     if (!$@) {
 4912: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
 4913:     } else {
 4914: 	&Failure($client,"unknown_cmd\n",$userinput);
 4915:     }
 4916:     return 1;
 4917: }
 4918: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
 4919: 
 4920: #
 4921: # Gets a student's photo to exist (in the correct image type) in the user's 
 4922: # directory.
 4923: # Formal Parameters:
 4924: #    $cmd     - The command request that got us dispatched.
 4925: #    $tail    - A colon separated set of words that will be split into:
 4926: #               $domain - student's domain
 4927: #               $uname  - student username
 4928: #               $type   - image type desired
 4929: #    $client  - The socket open on the client.
 4930: # Returns:
 4931: #    1 - continue processing.
 4932: 
 4933: sub student_photo_handler {
 4934:     my ($cmd, $tail, $client) = @_;
 4935:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
 4936: 
 4937:     my $path=&propath($domain,$uname). '/userfiles/internal/';
 4938:     my $filename = 'studentphoto.'.$ext;
 4939:     if ($type eq 'thumbnail') {
 4940:         $filename = 'studentphoto_tn.'.$ext;
 4941:     }
 4942:     if (-e $path.$filename) {
 4943: 	&Reply($client,"ok\n","$cmd:$tail");
 4944: 	return 1;
 4945:     }
 4946:     &mkpath($path);
 4947:     my $file;
 4948:     if ($type eq 'thumbnail') {
 4949: 	eval {
 4950: 	    local($SIG{__DIE__})='DEFAULT';
 4951: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
 4952: 	};
 4953:     } else {
 4954:         $file=&localstudentphoto::fetch($domain,$uname);
 4955:     }
 4956:     if (!$file) {
 4957: 	&Failure($client,"unavailable\n","$cmd:$tail");
 4958: 	return 1;
 4959:     }
 4960:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
 4961:     if (-e $path.$filename) {
 4962: 	&Reply($client,"ok\n","$cmd:$tail");
 4963: 	return 1;
 4964:     }
 4965:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
 4966:     return 1;
 4967: }
 4968: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
 4969: 
 4970: sub inst_usertypes_handler {
 4971:     my ($cmd, $domain, $client) = @_;
 4972:     my $res;
 4973:     my $userinput = $cmd.":".$domain; # For logging purposes.
 4974:     my (%typeshash,@order,$result);
 4975:     eval {
 4976: 	local($SIG{__DIE__})='DEFAULT';
 4977: 	$result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
 4978:     };
 4979:     if ($result eq 'ok') {
 4980:         if (keys(%typeshash) > 0) {
 4981:             foreach my $key (keys(%typeshash)) {
 4982:                 $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
 4983:             }
 4984:         }
 4985:         $res=~s/\&$//;
 4986:         $res .= ':';
 4987:         if (@order > 0) {
 4988:             foreach my $item (@order) {
 4989:                 $res .= &escape($item).'&';
 4990:             }
 4991:         }
 4992:         $res=~s/\&$//;
 4993:     }
 4994:     &Reply($client, \$res, $userinput);
 4995:     return 1;
 4996: }
 4997: &register_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
 4998: 
 4999: # mkpath makes all directories for a file, expects an absolute path with a
 5000: # file or a trailing / if just a dir is passed
 5001: # returns 1 on success 0 on failure
 5002: sub mkpath {
 5003:     my ($file)=@_;
 5004:     my @parts=split(/\//,$file,-1);
 5005:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
 5006:     for (my $i=3;$i<= ($#parts-1);$i++) {
 5007: 	$now.='/'.$parts[$i]; 
 5008: 	if (!-e $now) {
 5009: 	    if  (!mkdir($now,0770)) { return 0; }
 5010: 	}
 5011:     }
 5012:     return 1;
 5013: }
 5014: 
 5015: #---------------------------------------------------------------
 5016: #
 5017: #   Getting, decoding and dispatching requests:
 5018: #
 5019: #
 5020: #   Get a Request:
 5021: #   Gets a Request message from the client.  The transaction
 5022: #   is defined as a 'line' of text.  We remove the new line
 5023: #   from the text line.  
 5024: #
 5025: sub get_request {
 5026:     my $input = <$client>;
 5027:     chomp($input);
 5028: 
 5029:     &Debug("get_request: Request = $input\n");
 5030: 
 5031:     &status('Processing '.$clientname.':'.$input);
 5032: 
 5033:     return $input;
 5034: }
 5035: #---------------------------------------------------------------
 5036: #
 5037: #  Process a request.  This sub should shrink as each action
 5038: #  gets farmed out into a separat sub that is registered 
 5039: #  with the dispatch hash.  
 5040: #
 5041: # Parameters:
 5042: #    user_input   - The request received from the client (lonc).
 5043: # Returns:
 5044: #    true to keep processing, false if caller should exit.
 5045: #
 5046: sub process_request {
 5047:     my ($userinput) = @_;      # Easier for now to break style than to
 5048:                                 # fix all the userinput -> user_input.
 5049:     my $wasenc    = 0;		# True if request was encrypted.
 5050: # ------------------------------------------------------------ See if encrypted
 5051:     # for command
 5052:     # sethost:<server>
 5053:     # <command>:<args>
 5054:     #   we just send it to the processor
 5055:     # for
 5056:     # sethost:<server>:<command>:<args>
 5057:     #  we do the implict set host and then do the command
 5058:     if ($userinput =~ /^sethost:/) {
 5059: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
 5060: 	if (defined($userinput)) {
 5061: 	    &sethost("$cmd:$newid");
 5062: 	} else {
 5063: 	    $userinput = "$cmd:$newid";
 5064: 	}
 5065:     }
 5066: 
 5067:     if ($userinput =~ /^enc/) {
 5068: 	$userinput = decipher($userinput);
 5069: 	$wasenc=1;
 5070: 	if(!$userinput) {	# Cipher not defined.
 5071: 	    &Failure($client, "error: Encrypted data without negotated key\n");
 5072: 	    return 0;
 5073: 	}
 5074:     }
 5075:     Debug("process_request: $userinput\n");
 5076:     
 5077:     #  
 5078:     #   The 'correct way' to add a command to lond is now to
 5079:     #   write a sub to execute it and Add it to the command dispatch
 5080:     #   hash via a call to register_handler..  The comments to that
 5081:     #   sub should give you enough to go on to show how to do this
 5082:     #   along with the examples that are building up as this code
 5083:     #   is getting refactored.   Until all branches of the
 5084:     #   if/elseif monster below have been factored out into
 5085:     #   separate procesor subs, if the dispatch hash is missing
 5086:     #   the command keyword, we will fall through to the remainder
 5087:     #   of the if/else chain below in order to keep this thing in 
 5088:     #   working order throughout the transmogrification.
 5089: 
 5090:     my ($command, $tail) = split(/:/, $userinput, 2);
 5091:     chomp($command);
 5092:     chomp($tail);
 5093:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
 5094:     $command =~ s/(\r)//;	# And this too for parameterless commands.
 5095:     if(!$tail) {
 5096: 	$tail ="";		# defined but blank.
 5097:     }
 5098: 
 5099:     &Debug("Command received: $command, encoded = $wasenc");
 5100: 
 5101:     if(defined $Dispatcher{$command}) {
 5102: 
 5103: 	my $dispatch_info = $Dispatcher{$command};
 5104: 	my $handler       = $$dispatch_info[0];
 5105: 	my $need_encode   = $$dispatch_info[1];
 5106: 	my $client_types  = $$dispatch_info[2];
 5107: 	Debug("Matched dispatch hash: mustencode: $need_encode "
 5108: 	      ."ClientType $client_types");
 5109:       
 5110: 	#  Validate the request:
 5111:       
 5112: 	my $ok = 1;
 5113: 	my $requesterprivs = 0;
 5114: 	if(&isClient()) {
 5115: 	    $requesterprivs |= $CLIENT_OK;
 5116: 	}
 5117: 	if(&isManager()) {
 5118: 	    $requesterprivs |= $MANAGER_OK;
 5119: 	}
 5120: 	if($need_encode && (!$wasenc)) {
 5121: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
 5122: 	    $ok = 0;
 5123: 	}
 5124: 	if(($client_types & $requesterprivs) == 0) {
 5125: 	    Debug("Client not privileged to do this operation");
 5126: 	    $ok = 0;
 5127: 	}
 5128: 
 5129: 	if($ok) {
 5130: 	    Debug("Dispatching to handler $command $tail");
 5131: 	    my $keep_going = &$handler($command, $tail, $client);
 5132: 	    return $keep_going;
 5133: 	} else {
 5134: 	    Debug("Refusing to dispatch because client did not match requirements");
 5135: 	    Failure($client, "refused\n", $userinput);
 5136: 	    return 1;
 5137: 	}
 5138: 
 5139:     }    
 5140: 
 5141:     print $client "unknown_cmd\n";
 5142: # -------------------------------------------------------------------- complete
 5143:     Debug("process_request - returning 1");
 5144:     return 1;
 5145: }
 5146: #
 5147: #   Decipher encoded traffic
 5148: #  Parameters:
 5149: #     input      - Encoded data.
 5150: #  Returns:
 5151: #     Decoded data or undef if encryption key was not yet negotiated.
 5152: #  Implicit input:
 5153: #     cipher  - This global holds the negotiated encryption key.
 5154: #
 5155: sub decipher {
 5156:     my ($input)  = @_;
 5157:     my $output = '';
 5158:     
 5159:     
 5160:     if($cipher) {
 5161: 	my($enc, $enclength, $encinput) = split(/:/, $input);
 5162: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
 5163: 	    $output .= 
 5164: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
 5165: 	}
 5166: 	return substr($output, 0, $enclength);
 5167:     } else {
 5168: 	return undef;
 5169:     }
 5170: }
 5171: 
 5172: #
 5173: #   Register a command processor.  This function is invoked to register a sub
 5174: #   to process a request.  Once registered, the ProcessRequest sub can automatically
 5175: #   dispatch requests to an appropriate sub, and do the top level validity checking
 5176: #   as well:
 5177: #    - Is the keyword recognized.
 5178: #    - Is the proper client type attempting the request.
 5179: #    - Is the request encrypted if it has to be.
 5180: #   Parameters:
 5181: #    $request_name         - Name of the request being registered.
 5182: #                           This is the command request that will match
 5183: #                           against the hash keywords to lookup the information
 5184: #                           associated with the dispatch information.
 5185: #    $procedure           - Reference to a sub to call to process the request.
 5186: #                           All subs get called as follows:
 5187: #                             Procedure($cmd, $tail, $replyfd, $key)
 5188: #                             $cmd    - the actual keyword that invoked us.
 5189: #                             $tail   - the tail of the request that invoked us.
 5190: #                             $replyfd- File descriptor connected to the client
 5191: #    $must_encode          - True if the request must be encoded to be good.
 5192: #    $client_ok            - True if it's ok for a client to request this.
 5193: #    $manager_ok           - True if it's ok for a manager to request this.
 5194: # Side effects:
 5195: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
 5196: #      - On failure, the program will die as it's a bad internal bug to try to 
 5197: #        register a duplicate command handler.
 5198: #
 5199: sub register_handler {
 5200:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
 5201: 
 5202:     #  Don't allow duplication#
 5203:    
 5204:     if (defined $Dispatcher{$request_name}) {
 5205: 	die "Attempting to define a duplicate request handler for $request_name\n";
 5206:     }
 5207:     #   Build the client type mask:
 5208:     
 5209:     my $client_type_mask = 0;
 5210:     if($client_ok) {
 5211: 	$client_type_mask  |= $CLIENT_OK;
 5212:     }
 5213:     if($manager_ok) {
 5214: 	$client_type_mask  |= $MANAGER_OK;
 5215:     }
 5216:    
 5217:     #  Enter the hash:
 5218:       
 5219:     my @entry = ($procedure, $must_encode, $client_type_mask);
 5220:    
 5221:     $Dispatcher{$request_name} = \@entry;
 5222:    
 5223: }
 5224: 
 5225: 
 5226: #------------------------------------------------------------------
 5227: 
 5228: 
 5229: 
 5230: 
 5231: #
 5232: #  Convert an error return code from lcpasswd to a string value.
 5233: #
 5234: sub lcpasswdstrerror {
 5235:     my $ErrorCode = shift;
 5236:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
 5237: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
 5238:     } else {
 5239: 	return $passwderrors[$ErrorCode];
 5240:     }
 5241: }
 5242: 
 5243: #
 5244: # Convert an error return code from lcuseradd to a string value:
 5245: #
 5246: sub lcuseraddstrerror {
 5247:     my $ErrorCode = shift;
 5248:     if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
 5249: 	return "lcuseradd - Unrecognized error code: ".$ErrorCode;
 5250:     } else {
 5251: 	return $adderrors[$ErrorCode];
 5252:     }
 5253: }
 5254: 
 5255: # grabs exception and records it to log before exiting
 5256: sub catchexception {
 5257:     my ($error)=@_;
 5258:     $SIG{'QUIT'}='DEFAULT';
 5259:     $SIG{__DIE__}='DEFAULT';
 5260:     &status("Catching exception");
 5261:     &logthis("<font color='red'>CRITICAL: "
 5262:      ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
 5263:      ."a crash with this error msg->[$error]</font>");
 5264:     &logthis('Famous last words: '.$status.' - '.$lastlog);
 5265:     if ($client) { print $client "error: $error\n"; }
 5266:     $server->close();
 5267:     die($error);
 5268: }
 5269: sub timeout {
 5270:     &status("Handling Timeout");
 5271:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
 5272:     &catchexception('Timeout');
 5273: }
 5274: # -------------------------------- Set signal handlers to record abnormal exits
 5275: 
 5276: 
 5277: $SIG{'QUIT'}=\&catchexception;
 5278: $SIG{__DIE__}=\&catchexception;
 5279: 
 5280: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
 5281: &status("Read loncapa.conf and loncapa_apache.conf");
 5282: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
 5283: %perlvar=%{$perlvarref};
 5284: undef $perlvarref;
 5285: 
 5286: # ----------------------------- Make sure this process is running from user=www
 5287: my $wwwid=getpwnam('www');
 5288: if ($wwwid!=$<) {
 5289:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
 5290:    my $subj="LON: $currenthostid User ID mismatch";
 5291:    system("echo 'User ID mismatch.  lond must be run as user www.' |\
 5292:  mailto $emailto -s '$subj' > /dev/null");
 5293:    exit 1;
 5294: }
 5295: 
 5296: # --------------------------------------------- Check if other instance running
 5297: 
 5298: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
 5299: 
 5300: if (-e $pidfile) {
 5301:    my $lfh=IO::File->new("$pidfile");
 5302:    my $pide=<$lfh>;
 5303:    chomp($pide);
 5304:    if (kill 0 => $pide) { die "already running"; }
 5305: }
 5306: 
 5307: # ------------------------------------------------------------- Read hosts file
 5308: 
 5309: 
 5310: 
 5311: # establish SERVER socket, bind and listen.
 5312: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
 5313:                                 Type      => SOCK_STREAM,
 5314:                                 Proto     => 'tcp',
 5315:                                 Reuse     => 1,
 5316:                                 Listen    => 10 )
 5317:   or die "making socket: $@\n";
 5318: 
 5319: # --------------------------------------------------------- Do global variables
 5320: 
 5321: # global variables
 5322: 
 5323: my %children               = ();       # keys are current child process IDs
 5324: 
 5325: sub REAPER {                        # takes care of dead children
 5326:     $SIG{CHLD} = \&REAPER;
 5327:     &status("Handling child death");
 5328:     my $pid;
 5329:     do {
 5330: 	$pid = waitpid(-1,&WNOHANG());
 5331: 	if (defined($children{$pid})) {
 5332: 	    &logthis("Child $pid died");
 5333: 	    delete($children{$pid});
 5334: 	} elsif ($pid > 0) {
 5335: 	    &logthis("Unknown Child $pid died");
 5336: 	}
 5337:     } while ( $pid > 0 );
 5338:     foreach my $child (keys(%children)) {
 5339: 	$pid = waitpid($child,&WNOHANG());
 5340: 	if ($pid > 0) {
 5341: 	    &logthis("Child $child - $pid looks like we missed it's death");
 5342: 	    delete($children{$pid});
 5343: 	}
 5344:     }
 5345:     &status("Finished Handling child death");
 5346: }
 5347: 
 5348: sub HUNTSMAN {                      # signal handler for SIGINT
 5349:     &status("Killing children (INT)");
 5350:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
 5351:     kill 'INT' => keys %children;
 5352:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
 5353:     my $execdir=$perlvar{'lonDaemons'};
 5354:     unlink("$execdir/logs/lond.pid");
 5355:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
 5356:     &status("Done killing children");
 5357:     exit;                           # clean up with dignity
 5358: }
 5359: 
 5360: sub HUPSMAN {                      # signal handler for SIGHUP
 5361:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
 5362:     &status("Killing children for restart (HUP)");
 5363:     kill 'INT' => keys %children;
 5364:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
 5365:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
 5366:     my $execdir=$perlvar{'lonDaemons'};
 5367:     unlink("$execdir/logs/lond.pid");
 5368:     &status("Restarting self (HUP)");
 5369:     exec("$execdir/lond");         # here we go again
 5370: }
 5371: 
 5372: #
 5373: #  Reload the Apache daemon's state.
 5374: #  This is done by invoking /home/httpd/perl/apachereload
 5375: #  a setuid perl script that can be root for us to do this job.
 5376: #
 5377: sub ReloadApache {
 5378:     my $execdir = $perlvar{'lonDaemons'};
 5379:     my $script  = $execdir."/apachereload";
 5380:     system($script);
 5381: }
 5382: 
 5383: #
 5384: #   Called in response to a USR2 signal.
 5385: #   - Reread hosts.tab
 5386: #   - All children connected to hosts that were removed from hosts.tab
 5387: #     are killed via SIGINT
 5388: #   - All children connected to previously existing hosts are sent SIGUSR1
 5389: #   - Our internal hosts hash is updated to reflect the new contents of
 5390: #     hosts.tab causing connections from hosts added to hosts.tab to
 5391: #     now be honored.
 5392: #
 5393: sub UpdateHosts {
 5394:     &status("Reload hosts.tab");
 5395:     logthis('<font color="blue"> Updating connections </font>');
 5396:     #
 5397:     #  The %children hash has the set of IP's we currently have children
 5398:     #  on.  These need to be matched against records in the hosts.tab
 5399:     #  Any ip's no longer in the table get killed off they correspond to
 5400:     #  either dropped or changed hosts.  Note that the re-read of the table
 5401:     #  will take care of new and changed hosts as connections come into being.
 5402: 
 5403:     &Apache::lonnet::reset_hosts_info();
 5404: 
 5405:     foreach my $child (keys(%children)) {
 5406: 	my $childip = $children{$child};
 5407: 	if ($childip ne '127.0.0.1'
 5408: 	    && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
 5409: 	    logthis('<font color="blue"> UpdateHosts killing child '
 5410: 		    ." $child for ip $childip </font>");
 5411: 	    kill('INT', $child);
 5412: 	} else {
 5413: 	    logthis('<font color="green"> keeping child for ip '
 5414: 		    ." $childip (pid=$child) </font>");
 5415: 	}
 5416:     }
 5417:     ReloadApache;
 5418:     &status("Finished reloading hosts.tab");
 5419: }
 5420: 
 5421: 
 5422: sub checkchildren {
 5423:     &status("Checking on the children (sending signals)");
 5424:     &initnewstatus();
 5425:     &logstatus();
 5426:     &logthis('Going to check on the children');
 5427:     my $docdir=$perlvar{'lonDocRoot'};
 5428:     foreach (sort keys %children) {
 5429: 	#sleep 1;
 5430:         unless (kill 'USR1' => $_) {
 5431: 	    &logthis ('Child '.$_.' is dead');
 5432:             &logstatus($$.' is dead');
 5433: 	    delete($children{$_});
 5434:         } 
 5435:     }
 5436:     sleep 5;
 5437:     $SIG{ALRM} = sub { Debug("timeout"); 
 5438: 		       die "timeout";  };
 5439:     $SIG{__DIE__} = 'DEFAULT';
 5440:     &status("Checking on the children (waiting for reports)");
 5441:     foreach (sort keys %children) {
 5442:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
 5443:           eval {
 5444:             alarm(300);
 5445: 	    &logthis('Child '.$_.' did not respond');
 5446: 	    kill 9 => $_;
 5447: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
 5448: 	    #$subj="LON: $currenthostid killed lond process $_";
 5449: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
 5450: 	    #$execdir=$perlvar{'lonDaemons'};
 5451: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
 5452: 	    delete($children{$_});
 5453: 	    alarm(0);
 5454: 	  }
 5455:         }
 5456:     }
 5457:     $SIG{ALRM} = 'DEFAULT';
 5458:     $SIG{__DIE__} = \&catchexception;
 5459:     &status("Finished checking children");
 5460:     &logthis('Finished Checking children');
 5461: }
 5462: 
 5463: # --------------------------------------------------------------------- Logging
 5464: 
 5465: sub logthis {
 5466:     my $message=shift;
 5467:     my $execdir=$perlvar{'lonDaemons'};
 5468:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
 5469:     my $now=time;
 5470:     my $local=localtime($now);
 5471:     $lastlog=$local.': '.$message;
 5472:     print $fh "$local ($$): $message\n";
 5473: }
 5474: 
 5475: # ------------------------- Conditional log if $DEBUG true.
 5476: sub Debug {
 5477:     my $message = shift;
 5478:     if($DEBUG) {
 5479: 	&logthis($message);
 5480:     }
 5481: }
 5482: 
 5483: #
 5484: #   Sub to do replies to client.. this gives a hook for some
 5485: #   debug tracing too:
 5486: #  Parameters:
 5487: #     fd      - File open on client.
 5488: #     reply   - Text to send to client.
 5489: #     request - Original request from client.
 5490: #
 5491: sub Reply {
 5492:     my ($fd, $reply, $request) = @_;
 5493:     if (ref($reply)) {
 5494: 	print $fd $$reply;
 5495: 	print $fd "\n";
 5496: 	if ($DEBUG) { Debug("Request was $request  Reply was $$reply"); }
 5497:     } else {
 5498: 	print $fd $reply;
 5499: 	if ($DEBUG) { Debug("Request was $request  Reply was $reply"); }
 5500:     }
 5501:     $Transactions++;
 5502: }
 5503: 
 5504: 
 5505: #
 5506: #    Sub to report a failure.
 5507: #    This function:
 5508: #     -   Increments the failure statistic counters.
 5509: #     -   Invokes Reply to send the error message to the client.
 5510: # Parameters:
 5511: #    fd       - File descriptor open on the client
 5512: #    reply    - Reply text to emit.
 5513: #    request  - The original request message (used by Reply
 5514: #               to debug if that's enabled.
 5515: # Implicit outputs:
 5516: #    $Failures- The number of failures is incremented.
 5517: #    Reply (invoked here) sends a message to the 
 5518: #    client:
 5519: #
 5520: sub Failure {
 5521:     my $fd      = shift;
 5522:     my $reply   = shift;
 5523:     my $request = shift;
 5524:    
 5525:     $Failures++;
 5526:     Reply($fd, $reply, $request);      # That's simple eh?
 5527: }
 5528: # ------------------------------------------------------------------ Log status
 5529: 
 5530: sub logstatus {
 5531:     &status("Doing logging");
 5532:     my $docdir=$perlvar{'lonDocRoot'};
 5533:     {
 5534: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
 5535:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
 5536:         $fh->close();
 5537:     }
 5538:     &status("Finished $$.txt");
 5539:     {
 5540: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
 5541: 	flock(LOG,LOCK_EX);
 5542: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
 5543: 	    .$status."\t".$lastlog."\t $keymode\n";
 5544: 	flock(LOG,LOCK_UN);
 5545: 	close(LOG);
 5546:     }
 5547:     &status("Finished logging");
 5548: }
 5549: 
 5550: sub initnewstatus {
 5551:     my $docdir=$perlvar{'lonDocRoot'};
 5552:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
 5553:     my $now=time;
 5554:     my $local=localtime($now);
 5555:     print $fh "LOND status $local - parent $$\n\n";
 5556:     opendir(DIR,"$docdir/lon-status/londchld");
 5557:     while (my $filename=readdir(DIR)) {
 5558:         unlink("$docdir/lon-status/londchld/$filename");
 5559:     }
 5560:     closedir(DIR);
 5561: }
 5562: 
 5563: # -------------------------------------------------------------- Status setting
 5564: 
 5565: sub status {
 5566:     my $what=shift;
 5567:     my $now=time;
 5568:     my $local=localtime($now);
 5569:     $status=$local.': '.$what;
 5570:     $0='lond: '.$what.' '.$local;
 5571: }
 5572: 
 5573: # -------------------------------------------------------------- Talk to lonsql
 5574: 
 5575: sub sql_reply {
 5576:     my ($cmd)=@_;
 5577:     my $answer=&sub_sql_reply($cmd);
 5578:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
 5579:     return $answer;
 5580: }
 5581: 
 5582: sub sub_sql_reply {
 5583:     my ($cmd)=@_;
 5584:     my $unixsock="mysqlsock";
 5585:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
 5586:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
 5587:                                       Type    => SOCK_STREAM,
 5588:                                       Timeout => 10)
 5589:        or return "con_lost";
 5590:     print $sclient "$cmd:$currentdomainid\n";
 5591:     my $answer=<$sclient>;
 5592:     chomp($answer);
 5593:     if (!$answer) { $answer="con_lost"; }
 5594:     return $answer;
 5595: }
 5596: 
 5597: # --------------------------------------- Is this the home server of an author?
 5598: 
 5599: sub ishome {
 5600:     my $author=shift;
 5601:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 5602:     my ($udom,$uname)=split(/\//,$author);
 5603:     my $proname=propath($udom,$uname);
 5604:     if (-e $proname) {
 5605: 	return 'owner';
 5606:     } else {
 5607:         return 'not_owner';
 5608:     }
 5609: }
 5610: 
 5611: # ======================================================= Continue main program
 5612: # ---------------------------------------------------- Fork once and dissociate
 5613: 
 5614: my $fpid=fork;
 5615: exit if $fpid;
 5616: die "Couldn't fork: $!" unless defined ($fpid);
 5617: 
 5618: POSIX::setsid() or die "Can't start new session: $!";
 5619: 
 5620: # ------------------------------------------------------- Write our PID on disk
 5621: 
 5622: my $execdir=$perlvar{'lonDaemons'};
 5623: open (PIDSAVE,">$execdir/logs/lond.pid");
 5624: print PIDSAVE "$$\n";
 5625: close(PIDSAVE);
 5626: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
 5627: &status('Starting');
 5628: 
 5629: 
 5630: 
 5631: # ----------------------------------------------------- Install signal handlers
 5632: 
 5633: 
 5634: $SIG{CHLD} = \&REAPER;
 5635: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 5636: $SIG{HUP}  = \&HUPSMAN;
 5637: $SIG{USR1} = \&checkchildren;
 5638: $SIG{USR2} = \&UpdateHosts;
 5639: 
 5640: #  Read the host hashes:
 5641: &Apache::lonnet::load_hosts_tab();
 5642: 
 5643: my $dist=`$perlvar{'lonDaemons'}/distprobe`;
 5644: 
 5645: # --------------------------------------------------------------
 5646: #   Accept connections.  When a connection comes in, it is validated
 5647: #   and if good, a child process is created to process transactions
 5648: #   along the connection.
 5649: 
 5650: while (1) {
 5651:     &status('Starting accept');
 5652:     $client = $server->accept() or next;
 5653:     &status('Accepted '.$client.' off to spawn');
 5654:     make_new_child($client);
 5655:     &status('Finished spawning');
 5656: }
 5657: 
 5658: sub make_new_child {
 5659:     my $pid;
 5660: #    my $cipher;     # Now global
 5661:     my $sigset;
 5662: 
 5663:     $client = shift;
 5664:     &status('Starting new child '.$client);
 5665:     &logthis('<font color="green"> Attempting to start child ('.$client.
 5666: 	     ")</font>");    
 5667:     # block signal for fork
 5668:     $sigset = POSIX::SigSet->new(SIGINT);
 5669:     sigprocmask(SIG_BLOCK, $sigset)
 5670:         or die "Can't block SIGINT for fork: $!\n";
 5671: 
 5672:     die "fork: $!" unless defined ($pid = fork);
 5673: 
 5674:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
 5675: 	                               # connection liveness.
 5676: 
 5677:     #
 5678:     #  Figure out who we're talking to so we can record the peer in 
 5679:     #  the pid hash.
 5680:     #
 5681:     my $caller = getpeername($client);
 5682:     my ($port,$iaddr);
 5683:     if (defined($caller) && length($caller) > 0) {
 5684: 	($port,$iaddr)=unpack_sockaddr_in($caller);
 5685:     } else {
 5686: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
 5687:     }
 5688:     if (defined($iaddr)) {
 5689: 	$clientip  = inet_ntoa($iaddr);
 5690: 	Debug("Connected with $clientip");
 5691:     } else {
 5692: 	&logthis("Unable to determine clientip");
 5693: 	$clientip='Unavailable';
 5694:     }
 5695:     
 5696:     if ($pid) {
 5697:         # Parent records the child's birth and returns.
 5698:         sigprocmask(SIG_UNBLOCK, $sigset)
 5699:             or die "Can't unblock SIGINT for fork: $!\n";
 5700:         $children{$pid} = $clientip;
 5701:         &status('Started child '.$pid);
 5702:         return;
 5703:     } else {
 5704:         # Child can *not* return from this subroutine.
 5705:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
 5706:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
 5707:                                 #don't get intercepted
 5708:         $SIG{USR1}= \&logstatus;
 5709:         $SIG{ALRM}= \&timeout;
 5710:         $lastlog='Forked ';
 5711:         $status='Forked';
 5712: 
 5713:         # unblock signals
 5714:         sigprocmask(SIG_UNBLOCK, $sigset)
 5715:             or die "Can't unblock SIGINT for fork: $!\n";
 5716: 
 5717: #        my $tmpsnum=0;            # Now global
 5718: #---------------------------------------------------- kerberos 5 initialization
 5719:         &Authen::Krb5::init_context();
 5720: 	unless (($dist eq 'fedora5') || ($dist eq 'fedora4') ||  
 5721: 		($dist eq 'fedora6') || ($dist eq 'suse9.3')) {
 5722: 	    &Authen::Krb5::init_ets();
 5723: 	}
 5724: 
 5725: 	&status('Accepted connection');
 5726: # =============================================================================
 5727:             # do something with the connection
 5728: # -----------------------------------------------------------------------------
 5729: 	# see if we know client and 'check' for spoof IP by ineffective challenge
 5730: 
 5731: 	my $outsideip=$clientip;
 5732: 	if ($clientip eq '127.0.0.1') {
 5733: 	    $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
 5734: 	}
 5735: 
 5736: 	my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
 5737: 	my $ismanager=($managers{$outsideip}    ne undef);
 5738: 	$clientname  = "[unknonwn]";
 5739: 	if($clientrec) {	# Establish client type.
 5740: 	    $ConnectionType = "client";
 5741: 	    $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
 5742: 	    if($ismanager) {
 5743: 		$ConnectionType = "both";
 5744: 	    }
 5745: 	} else {
 5746: 	    $ConnectionType = "manager";
 5747: 	    $clientname = $managers{$outsideip};
 5748: 	}
 5749: 	my $clientok;
 5750: 
 5751: 	if ($clientrec || $ismanager) {
 5752: 	    &status("Waiting for init from $clientip $clientname");
 5753: 	    &logthis('<font color="yellow">INFO: Connection, '.
 5754: 		     $clientip.
 5755: 		  " ($clientname) connection type = $ConnectionType </font>" );
 5756: 	    &status("Connecting $clientip  ($clientname))"); 
 5757: 	    my $remotereq=<$client>;
 5758: 	    chomp($remotereq);
 5759: 	    Debug("Got init: $remotereq");
 5760: 
 5761: 	    if ($remotereq =~ /^init/) {
 5762: 		&sethost("sethost:$perlvar{'lonHostID'}");
 5763: 		#
 5764: 		#  If the remote is attempting a local init... give that a try:
 5765: 		#
 5766: 		my ($i, $inittype) = split(/:/, $remotereq);
 5767: 
 5768: 		# If the connection type is ssl, but I didn't get my
 5769: 		# certificate files yet, then I'll drop  back to 
 5770: 		# insecure (if allowed).
 5771: 		
 5772: 		if($inittype eq "ssl") {
 5773: 		    my ($ca, $cert) = lonssl::CertificateFile;
 5774: 		    my $kfile       = lonssl::KeyFile;
 5775: 		    if((!$ca)   || 
 5776: 		       (!$cert) || 
 5777: 		       (!$kfile)) {
 5778: 			$inittype = ""; # This forces insecure attempt.
 5779: 			&logthis("<font color=\"blue\"> Certificates not "
 5780: 				 ."installed -- trying insecure auth</font>");
 5781: 		    } else {	# SSL certificates are in place so
 5782: 		    }		# Leave the inittype alone.
 5783: 		}
 5784: 
 5785: 		if($inittype eq "local") {
 5786: 		    my $key = LocalConnection($client, $remotereq);
 5787: 		    if($key) {
 5788: 			Debug("Got local key $key");
 5789: 			$clientok     = 1;
 5790: 			my $cipherkey = pack("H32", $key);
 5791: 			$cipher       = new IDEA($cipherkey);
 5792: 			print $client "ok:local\n";
 5793: 			&logthis('<font color="green"'
 5794: 				 . "Successful local authentication </font>");
 5795: 			$keymode = "local"
 5796: 		    } else {
 5797: 			Debug("Failed to get local key");
 5798: 			$clientok = 0;
 5799: 			shutdown($client, 3);
 5800: 			close $client;
 5801: 		    }
 5802: 		} elsif ($inittype eq "ssl") {
 5803: 		    my $key = SSLConnection($client);
 5804: 		    if ($key) {
 5805: 			$clientok = 1;
 5806: 			my $cipherkey = pack("H32", $key);
 5807: 			$cipher       = new IDEA($cipherkey);
 5808: 			&logthis('<font color="green">'
 5809: 				 ."Successfull ssl authentication with $clientname </font>");
 5810: 			$keymode = "ssl";
 5811: 	     
 5812: 		    } else {
 5813: 			$clientok = 0;
 5814: 			close $client;
 5815: 		    }
 5816: 	   
 5817: 		} else {
 5818: 		    my $ok = InsecureConnection($client);
 5819: 		    if($ok) {
 5820: 			$clientok = 1;
 5821: 			&logthis('<font color="green">'
 5822: 				 ."Successful insecure authentication with $clientname </font>");
 5823: 			print $client "ok\n";
 5824: 			$keymode = "insecure";
 5825: 		    } else {
 5826: 			&logthis('<font color="yellow">'
 5827: 				  ."Attempted insecure connection disallowed </font>");
 5828: 			close $client;
 5829: 			$clientok = 0;
 5830: 			
 5831: 		    }
 5832: 		}
 5833: 	    } else {
 5834: 		&logthis(
 5835: 			 "<font color='blue'>WARNING: "
 5836: 			 ."$clientip failed to initialize: >$remotereq< </font>");
 5837: 		&status('No init '.$clientip);
 5838: 	    }
 5839: 	    
 5840: 	} else {
 5841: 	    &logthis(
 5842: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
 5843: 	    &status('Hung up on '.$clientip);
 5844: 	}
 5845:  
 5846: 	if ($clientok) {
 5847: # ---------------- New known client connecting, could mean machine online again
 5848: 	    if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip 
 5849: 		&& $clientip ne '127.0.0.1') {
 5850: 		&Apache::lonnet::reconlonc($clientname);
 5851: 	    }
 5852: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
 5853: 	    &status('Will listen to '.$clientname);
 5854: # ------------------------------------------------------------ Process requests
 5855: 	    my $keep_going = 1;
 5856: 	    my $user_input;
 5857: 	    while(($user_input = get_request) && $keep_going) {
 5858: 		alarm(120);
 5859: 		Debug("Main: Got $user_input\n");
 5860: 		$keep_going = &process_request($user_input);
 5861: 		alarm(0);
 5862: 		&status('Listening to '.$clientname." ($keymode)");	   
 5863: 	    }
 5864: 
 5865: # --------------------------------------------- client unknown or fishy, refuse
 5866: 	}  else {
 5867: 	    print $client "refused\n";
 5868: 	    $client->close();
 5869: 	    &logthis("<font color='blue'>WARNING: "
 5870: 		     ."Rejected client $clientip, closing connection</font>");
 5871: 	}
 5872:     }            
 5873:     
 5874: # =============================================================================
 5875:     
 5876:     &logthis("<font color='red'>CRITICAL: "
 5877: 	     ."Disconnect from $clientip ($clientname)</font>");    
 5878:     
 5879:     
 5880:     # this exit is VERY important, otherwise the child will become
 5881:     # a producer of more and more children, forking yourself into
 5882:     # process death.
 5883:     exit;
 5884:     
 5885: }
 5886: #
 5887: #   Determine if a user is an author for the indicated domain.
 5888: #
 5889: # Parameters:
 5890: #    domain          - domain to check in .
 5891: #    user            - Name of user to check.
 5892: #
 5893: # Return:
 5894: #     1             - User is an author for domain.
 5895: #     0             - User is not an author for domain.
 5896: sub is_author {
 5897:     my ($domain, $user) = @_;
 5898: 
 5899:     &Debug("is_author: $user @ $domain");
 5900: 
 5901:     my $hashref = &tie_user_hash($domain, $user, "roles",
 5902: 				 &GDBM_READER());
 5903: 
 5904:     #  Author role should show up as a key /domain/_au
 5905: 
 5906:     my $key    = "/$domain/_au";
 5907:     my $value;
 5908:     if (defined($hashref)) {
 5909: 	$value = $hashref->{$key};
 5910:     }
 5911: 
 5912:     if(defined($value)) {
 5913: 	&Debug("$user @ $domain is an author");
 5914:     }
 5915: 
 5916:     return defined($value);
 5917: }
 5918: #
 5919: #   Checks to see if the input roleput request was to set
 5920: # an author role.  If so, invokes the lchtmldir script to set
 5921: # up a correct public_html 
 5922: # Parameters:
 5923: #    request   - The request sent to the rolesput subchunk.
 5924: #                We're looking for  /domain/_au
 5925: #    domain    - The domain in which the user is having roles doctored.
 5926: #    user      - Name of the user for which the role is being put.
 5927: #    authtype  - The authentication type associated with the user.
 5928: #
 5929: sub manage_permissions {
 5930:     my ($request, $domain, $user, $authtype) = @_;
 5931: 
 5932:     &Debug("manage_permissions: $request $domain $user $authtype");
 5933: 
 5934:     # See if the request is of the form /$domain/_au
 5935:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
 5936: 	my $execdir = $perlvar{'lonDaemons'};
 5937: 	my $userhome= "/home/$user" ;
 5938: 	&logthis("system $execdir/lchtmldir $userhome $user $authtype");
 5939: 	&Debug("Setting homedir permissions for $userhome");
 5940: 	system("$execdir/lchtmldir $userhome $user $authtype");
 5941:     }
 5942: }
 5943: 
 5944: 
 5945: #
 5946: #  Return the full path of a user password file, whether it exists or not.
 5947: # Parameters:
 5948: #   domain     - Domain in which the password file lives.
 5949: #   user       - name of the user.
 5950: # Returns:
 5951: #    Full passwd path:
 5952: #
 5953: sub password_path {
 5954:     my ($domain, $user) = @_;
 5955:     return &propath($domain, $user).'/passwd';
 5956: }
 5957: 
 5958: #   Password Filename
 5959: #   Returns the path to a passwd file given domain and user... only if
 5960: #  it exists.
 5961: # Parameters:
 5962: #   domain    - Domain in which to search.
 5963: #   user      - username.
 5964: # Returns:
 5965: #   - If the password file exists returns its path.
 5966: #   - If the password file does not exist, returns undefined.
 5967: #
 5968: sub password_filename {
 5969:     my ($domain, $user) = @_;
 5970: 
 5971:     Debug ("PasswordFilename called: dom = $domain user = $user");
 5972: 
 5973:     my $path  = &password_path($domain, $user);
 5974:     Debug("PasswordFilename got path: $path");
 5975:     if(-e $path) {
 5976: 	return $path;
 5977:     } else {
 5978: 	return undef;
 5979:     }
 5980: }
 5981: 
 5982: #
 5983: #   Rewrite the contents of the user's passwd file.
 5984: #  Parameters:
 5985: #    domain    - domain of the user.
 5986: #    name      - User's name.
 5987: #    contents  - New contents of the file.
 5988: # Returns:
 5989: #   0    - Failed.
 5990: #   1    - Success.
 5991: #
 5992: sub rewrite_password_file {
 5993:     my ($domain, $user, $contents) = @_;
 5994: 
 5995:     my $file = &password_filename($domain, $user);
 5996:     if (defined $file) {
 5997: 	my $pf = IO::File->new(">$file");
 5998: 	if($pf) {
 5999: 	    print $pf "$contents\n";
 6000: 	    return 1;
 6001: 	} else {
 6002: 	    return 0;
 6003: 	}
 6004:     } else {
 6005: 	return 0;
 6006:     }
 6007: 
 6008: }
 6009: 
 6010: #
 6011: #   get_auth_type - Determines the authorization type of a user in a domain.
 6012: 
 6013: #     Returns the authorization type or nouser if there is no such user.
 6014: #
 6015: sub get_auth_type 
 6016: {
 6017: 
 6018:     my ($domain, $user)  = @_;
 6019: 
 6020:     Debug("get_auth_type( $domain, $user ) \n");
 6021:     my $proname    = &propath($domain, $user); 
 6022:     my $passwdfile = "$proname/passwd";
 6023:     if( -e $passwdfile ) {
 6024: 	my $pf = IO::File->new($passwdfile);
 6025: 	my $realpassword = <$pf>;
 6026: 	chomp($realpassword);
 6027: 	Debug("Password info = $realpassword\n");
 6028: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
 6029: 	Debug("Authtype = $authtype, content = $contentpwd\n");
 6030: 	return "$authtype:$contentpwd";     
 6031:     } else {
 6032: 	Debug("Returning nouser");
 6033: 	return "nouser";
 6034:     }
 6035: }
 6036: 
 6037: #
 6038: #  Validate a user given their domain, name and password.  This utility
 6039: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
 6040: #  to validate the login credentials of a user.
 6041: # Parameters:
 6042: #    $domain    - The domain being logged into (this is required due to
 6043: #                 the capability for multihomed systems.
 6044: #    $user      - The name of the user being validated.
 6045: #    $password  - The user's propoposed password.
 6046: #
 6047: # Returns:
 6048: #     1        - The domain,user,pasword triplet corresponds to a valid
 6049: #                user.
 6050: #     0        - The domain,user,password triplet is not a valid user.
 6051: #
 6052: sub validate_user {
 6053:     my ($domain, $user, $password, $checkdefauth) = @_;
 6054: 
 6055:     # Why negative ~pi you may well ask?  Well this function is about
 6056:     # authentication, and therefore very important to get right.
 6057:     # I've initialized the flag that determines whether or not I've 
 6058:     # validated correctly to a value it's not supposed to get.
 6059:     # At the end of this function. I'll ensure that it's not still that
 6060:     # value so we don't just wind up returning some accidental value
 6061:     # as a result of executing an unforseen code path that
 6062:     # did not set $validated.  At the end of valid execution paths,
 6063:     # validated shoule be 1 for success or 0 for failuer.
 6064: 
 6065:     my $validated = -3.14159;
 6066: 
 6067:     #  How we authenticate is determined by the type of authentication
 6068:     #  the user has been assigned.  If the authentication type is
 6069:     #  "nouser", the user does not exist so we will return 0.
 6070: 
 6071:     my $contents = &get_auth_type($domain, $user);
 6072:     my ($howpwd, $contentpwd) = split(/:/, $contents);
 6073: 
 6074:     my $null = pack("C",0);	# Used by kerberos auth types.
 6075: 
 6076:     if ($howpwd eq 'nouser') {
 6077:         if ($checkdefauth) {
 6078:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 6079:             if ($domdefaults{'auth_def'} eq 'localauth') {
 6080:                 $howpwd = $domdefaults{'auth_def'};
 6081:                 $contentpwd = $domdefaults{'auth_arg_def'};
 6082:             } elsif ((($domdefaults{'auth_def'} eq 'krb4') || 
 6083:                       ($domdefaults{'auth_def'} eq 'krb5')) &&
 6084:                      ($domdefaults{'auth_arg_def'} ne '')) {
 6085:                 $howpwd = $domdefaults{'auth_def'};
 6086:                 $contentpwd = $domdefaults{'auth_arg_def'}; 
 6087:             }
 6088:         }
 6089:     } 
 6090:     if ($howpwd ne 'nouser') {
 6091: 	if($howpwd eq "internal") { # Encrypted is in local password file.
 6092: 	    $validated = (crypt($password, $contentpwd) eq $contentpwd);
 6093: 	}
 6094: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
 6095: 	    $contentpwd = (getpwnam($user))[1];
 6096: 	    if($contentpwd) {
 6097: 		if($contentpwd eq 'x') { # Shadow password file...
 6098: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
 6099: 		    open PWAUTH,  "|$pwauth_path" or
 6100: 			die "Cannot invoke authentication";
 6101: 		    print PWAUTH "$user\n$password\n";
 6102: 		    close PWAUTH;
 6103: 		    $validated = ! $?;
 6104: 
 6105: 		} else { 	         # Passwords in /etc/passwd. 
 6106: 		    $validated = (crypt($password,
 6107: 					$contentpwd) eq $contentpwd);
 6108: 		}
 6109: 	    } else {
 6110: 		$validated = 0;
 6111: 	    }
 6112: 	}
 6113: 	elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
 6114: 	    if(! ($password =~ /$null/) ) {
 6115: 		my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
 6116: 							   "",
 6117: 							   $contentpwd,,
 6118: 							   'krbtgt',
 6119: 							   $contentpwd,
 6120: 							   1,
 6121: 							   $password);
 6122: 		if(!$k4error) {
 6123: 		    $validated = 1;
 6124: 		} else {
 6125: 		    $validated = 0;
 6126: 		    &logthis('krb4: '.$user.', '.$contentpwd.', '.
 6127: 			     &Authen::Krb4::get_err_txt($Authen::Krb4::error));
 6128: 		}
 6129: 	    } else {
 6130: 		$validated = 0; # Password has a match with null.
 6131: 	    }
 6132: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
 6133: 	    if(!($password =~ /$null/)) { # Null password not allowed.
 6134: 		my $krbclient = &Authen::Krb5::parse_name($user.'@'
 6135: 							  .$contentpwd);
 6136: 		my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
 6137: 		my $krbserver  = &Authen::Krb5::parse_name($krbservice);
 6138: 		my $credentials= &Authen::Krb5::cc_default();
 6139: 		$credentials->initialize(&Authen::Krb5::parse_name($user.'@'
 6140:                                                                  .$contentpwd));
 6141:                 my $krbreturn;
 6142:                 if (exists(&Authen::Krb5::get_init_creds_password)) {
 6143:                     $krbreturn = 
 6144:                         &Authen::Krb5::get_init_creds_password($krbclient,$password,
 6145:                                                                $krbservice);
 6146:                     $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
 6147:                 } else {
 6148: 		    $krbreturn  = 
 6149:                         &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
 6150: 		 						$password,$credentials);
 6151: 		    $validated = ($krbreturn == 1);
 6152:                 }
 6153: 		if (!$validated) {
 6154: 		    &logthis('krb5: '.$user.', '.$contentpwd.', '.
 6155: 			     &Authen::Krb5::error());
 6156: 		}
 6157: 	    } else {
 6158: 		$validated = 0;
 6159: 	    }
 6160: 	} elsif ($howpwd eq "localauth") { 
 6161: 	    #  Authenticate via installation specific authentcation method:
 6162: 	    $validated = &localauth::localauth($user, 
 6163: 					       $password, 
 6164: 					       $contentpwd,
 6165: 					       $domain);
 6166: 	    if ($validated < 0) {
 6167: 		&logthis("localauth for $contentpwd $user:$domain returned a $validated");
 6168: 		$validated = 0;
 6169: 	    }
 6170: 	} else {			# Unrecognized auth is also bad.
 6171: 	    $validated = 0;
 6172: 	}
 6173:     } else {
 6174: 	$validated = 0;
 6175:     }
 6176:     #
 6177:     #  $validated has the correct stat of the authentication:
 6178:     #
 6179: 
 6180:     unless ($validated != -3.14159) {
 6181: 	#  I >really really< want to know if this happens.
 6182: 	#  since it indicates that user authentication is badly
 6183: 	#  broken in some code path.
 6184:         #
 6185: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
 6186:     }
 6187:     return $validated;
 6188: }
 6189: 
 6190: 
 6191: sub addline {
 6192:     my ($fname,$hostid,$ip,$newline)=@_;
 6193:     my $contents;
 6194:     my $found=0;
 6195:     my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
 6196:     my $sh;
 6197:     if ($sh=IO::File->new("$fname.subscription")) {
 6198: 	while (my $subline=<$sh>) {
 6199: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
 6200: 	}
 6201: 	$sh->close();
 6202:     }
 6203:     $sh=IO::File->new(">$fname.subscription");
 6204:     if ($contents) { print $sh $contents; }
 6205:     if ($newline) { print $sh $newline; }
 6206:     $sh->close();
 6207:     return $found;
 6208: }
 6209: 
 6210: sub get_chat {
 6211:     my ($cdom,$cname,$udom,$uname,$group)=@_;
 6212: 
 6213:     my @entries=();
 6214:     my $namespace = 'nohist_chatroom';
 6215:     my $namespace_inroom = 'nohist_inchatroom';
 6216:     if ($group ne '') {
 6217:         $namespace .= '_'.$group;
 6218:         $namespace_inroom .= '_'.$group;
 6219:     }
 6220:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
 6221: 				 &GDBM_READER());
 6222:     if ($hashref) {
 6223: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
 6224: 	&untie_user_hash($hashref);
 6225:     }
 6226:     my @participants=();
 6227:     my $cutoff=time-60;
 6228:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
 6229: 			      &GDBM_WRCREAT());
 6230:     if ($hashref) {
 6231:         $hashref->{$uname.':'.$udom}=time;
 6232:         foreach my $user (sort(keys(%$hashref))) {
 6233: 	    if ($hashref->{$user}>$cutoff) {
 6234: 		push(@participants, 'active_participant:'.$user);
 6235:             }
 6236:         }
 6237:         &untie_user_hash($hashref);
 6238:     }
 6239:     return (@participants,@entries);
 6240: }
 6241: 
 6242: sub chat_add {
 6243:     my ($cdom,$cname,$newchat,$group)=@_;
 6244:     my @entries=();
 6245:     my $time=time;
 6246:     my $namespace = 'nohist_chatroom';
 6247:     my $logfile = 'chatroom.log';
 6248:     if ($group ne '') {
 6249:         $namespace .= '_'.$group;
 6250:         $logfile = 'chatroom_'.$group.'.log';
 6251:     }
 6252:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
 6253: 				 &GDBM_WRCREAT());
 6254:     if ($hashref) {
 6255: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
 6256: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
 6257: 	my ($thentime,$idnum)=split(/\_/,$lastid);
 6258: 	my $newid=$time.'_000000';
 6259: 	if ($thentime==$time) {
 6260: 	    $idnum=~s/^0+//;
 6261: 	    $idnum++;
 6262: 	    $idnum=substr('000000'.$idnum,-6,6);
 6263: 	    $newid=$time.'_'.$idnum;
 6264: 	}
 6265: 	$hashref->{$newid}=$newchat;
 6266: 	my $expired=$time-3600;
 6267: 	foreach my $comment (keys(%$hashref)) {
 6268: 	    my ($thistime) = ($comment=~/(\d+)\_/);
 6269: 	    if ($thistime<$expired) {
 6270: 		delete $hashref->{$comment};
 6271: 	    }
 6272: 	}
 6273: 	{
 6274: 	    my $proname=&propath($cdom,$cname);
 6275: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
 6276: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
 6277: 	    }
 6278: 	    close(CHATLOG);
 6279: 	}
 6280: 	&untie_user_hash($hashref);
 6281:     }
 6282: }
 6283: 
 6284: sub unsub {
 6285:     my ($fname,$clientip)=@_;
 6286:     my $result;
 6287:     my $unsubs = 0;		# Number of successful unsubscribes:
 6288: 
 6289: 
 6290:     # An old way subscriptions were handled was to have a 
 6291:     # subscription marker file:
 6292: 
 6293:     Debug("Attempting unlink of $fname.$clientname");
 6294:     if (unlink("$fname.$clientname")) {
 6295: 	$unsubs++;		# Successful unsub via marker file.
 6296:     } 
 6297: 
 6298:     # The more modern way to do it is to have a subscription list
 6299:     # file:
 6300: 
 6301:     if (-e "$fname.subscription") {
 6302: 	my $found=&addline($fname,$clientname,$clientip,'');
 6303: 	if ($found) { 
 6304: 	    $unsubs++;
 6305: 	}
 6306:     } 
 6307: 
 6308:     #  If either or both of these mechanisms succeeded in unsubscribing a 
 6309:     #  resource we can return ok:
 6310: 
 6311:     if($unsubs) {
 6312: 	$result = "ok\n";
 6313:     } else {
 6314: 	$result = "not_subscribed\n";
 6315:     }
 6316: 
 6317:     return $result;
 6318: }
 6319: 
 6320: sub currentversion {
 6321:     my $fname=shift;
 6322:     my $version=-1;
 6323:     my $ulsdir='';
 6324:     if ($fname=~/^(.+)\/[^\/]+$/) {
 6325:        $ulsdir=$1;
 6326:     }
 6327:     my ($fnamere1,$fnamere2);
 6328:     # remove version if already specified
 6329:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
 6330:     # get the bits that go before and after the version number
 6331:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
 6332: 	$fnamere1=$1;
 6333: 	$fnamere2='.'.$2;
 6334:     }
 6335:     if (-e $fname) { $version=1; }
 6336:     if (-e $ulsdir) {
 6337: 	if(-d $ulsdir) {
 6338: 	    if (opendir(LSDIR,$ulsdir)) {
 6339: 		my $ulsfn;
 6340: 		while ($ulsfn=readdir(LSDIR)) {
 6341: # see if this is a regular file (ignore links produced earlier)
 6342: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
 6343: 		    unless (-l $thisfile) {
 6344: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
 6345: 			    if ($1>$version) { $version=$1; }
 6346: 			}
 6347: 		    }
 6348: 		}
 6349: 		closedir(LSDIR);
 6350: 		$version++;
 6351: 	    }
 6352: 	}
 6353:     }
 6354:     return $version;
 6355: }
 6356: 
 6357: sub thisversion {
 6358:     my $fname=shift;
 6359:     my $version=-1;
 6360:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
 6361: 	$version=$1;
 6362:     }
 6363:     return $version;
 6364: }
 6365: 
 6366: sub subscribe {
 6367:     my ($userinput,$clientip)=@_;
 6368:     my $result;
 6369:     my ($cmd,$fname)=split(/:/,$userinput,2);
 6370:     my $ownership=&ishome($fname);
 6371:     if ($ownership eq 'owner') {
 6372: # explitly asking for the current version?
 6373:         unless (-e $fname) {
 6374:             my $currentversion=&currentversion($fname);
 6375: 	    if (&thisversion($fname)==$currentversion) {
 6376:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
 6377: 		    my $root=$1;
 6378:                     my $extension=$2;
 6379:                     symlink($root.'.'.$extension,
 6380:                             $root.'.'.$currentversion.'.'.$extension);
 6381:                     unless ($extension=~/\.meta$/) {
 6382:                        symlink($root.'.'.$extension.'.meta',
 6383:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
 6384: 		    }
 6385:                 }
 6386:             }
 6387:         }
 6388: 	if (-e $fname) {
 6389: 	    if (-d $fname) {
 6390: 		$result="directory\n";
 6391: 	    } else {
 6392: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
 6393: 		my $now=time;
 6394: 		my $found=&addline($fname,$clientname,$clientip,
 6395: 				   "$clientname:$clientip:$now\n");
 6396: 		if ($found) { $result="$fname\n"; }
 6397: 		# if they were subscribed to only meta data, delete that
 6398:                 # subscription, when you subscribe to a file you also get
 6399:                 # the metadata
 6400: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
 6401: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
 6402: 		$fname="http://".&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
 6403: 		$result="$fname\n";
 6404: 	    }
 6405: 	} else {
 6406: 	    $result="not_found\n";
 6407: 	}
 6408:     } else {
 6409: 	$result="rejected\n";
 6410:     }
 6411:     return $result;
 6412: }
 6413: #  Change the passwd of a unix user.  The caller must have
 6414: #  first verified that the user is a loncapa user.
 6415: #
 6416: # Parameters:
 6417: #    user      - Unix user name to change.
 6418: #    pass      - New password for the user.
 6419: # Returns:
 6420: #    ok    - if success
 6421: #    other - Some meaningfule error message string.
 6422: # NOTE:
 6423: #    invokes a setuid script to change the passwd.
 6424: sub change_unix_password {
 6425:     my ($user, $pass) = @_;
 6426: 
 6427:     &Debug("change_unix_password");
 6428:     my $execdir=$perlvar{'lonDaemons'};
 6429:     &Debug("Opening lcpasswd pipeline");
 6430:     my $pf = IO::File->new("|$execdir/lcpasswd > "
 6431: 			   ."$perlvar{'lonDaemons'}"
 6432: 			   ."/logs/lcpasswd.log");
 6433:     print $pf "$user\n$pass\n$pass\n";
 6434:     close $pf;
 6435:     my $err = $?;
 6436:     return ($err < @passwderrors) ? $passwderrors[$err] : 
 6437: 	"pwchange_falure - unknown error";
 6438: 
 6439:     
 6440: }
 6441: 
 6442: 
 6443: sub make_passwd_file {
 6444:     my ($uname, $umode,$npass,$passfilename)=@_;
 6445:     my $result="ok";
 6446:     if ($umode eq 'krb4' or $umode eq 'krb5') {
 6447: 	{
 6448: 	    my $pf = IO::File->new(">$passfilename");
 6449: 	    if ($pf) {
 6450: 		print $pf "$umode:$npass\n";
 6451: 	    } else {
 6452: 		$result = "pass_file_failed_error";
 6453: 	    }
 6454: 	}
 6455:     } elsif ($umode eq 'internal') {
 6456: 	my $salt=time;
 6457: 	$salt=substr($salt,6,2);
 6458: 	my $ncpass=crypt($npass,$salt);
 6459: 	{
 6460: 	    &Debug("Creating internal auth");
 6461: 	    my $pf = IO::File->new(">$passfilename");
 6462: 	    if($pf) {
 6463: 		print $pf "internal:$ncpass\n"; 
 6464: 	    } else {
 6465: 		$result = "pass_file_failed_error";
 6466: 	    }
 6467: 	}
 6468:     } elsif ($umode eq 'localauth') {
 6469: 	{
 6470: 	    my $pf = IO::File->new(">$passfilename");
 6471: 	    if($pf) {
 6472: 		print $pf "localauth:$npass\n";
 6473: 	    } else {
 6474: 		$result = "pass_file_failed_error";
 6475: 	    }
 6476: 	}
 6477:     } elsif ($umode eq 'unix') {
 6478: 	{
 6479: 	    #
 6480: 	    #  Don't allow the creation of privileged accounts!!! that would
 6481: 	    #  be real bad!!!
 6482: 	    #
 6483: 	    my $uid = getpwnam($uname);
 6484: 	    if((defined $uid) && ($uid == 0)) {
 6485: 		&logthis(">>>Attempted to create privilged account blocked");
 6486: 		return "no_priv_account_error\n";
 6487: 	    }
 6488: 
 6489: 	    my $execpath       ="$perlvar{'lonDaemons'}/"."lcuseradd";
 6490: 
 6491: 	    my $lc_error_file  = $execdir."/tmp/lcuseradd".$$.".status";
 6492: 	    {
 6493: 		&Debug("Executing external: ".$execpath);
 6494: 		&Debug("user  = ".$uname.", Password =". $npass);
 6495: 		my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
 6496: 		print $se "$uname\n";
 6497: 		print $se "$npass\n";
 6498: 		print $se "$npass\n";
 6499: 		print $se "$lc_error_file\n"; # Status -> unique file.
 6500: 	    }
 6501: 	    if (-r $lc_error_file) {
 6502: 		&Debug("Opening error file: $lc_error_file");
 6503: 		my $error = IO::File->new("< $lc_error_file");
 6504: 		my $useraddok = <$error>;
 6505: 		$error->close;
 6506: 		unlink($lc_error_file);
 6507: 		
 6508: 		chomp $useraddok;
 6509: 	
 6510: 		if($useraddok > 0) {
 6511: 		    my $error_text = &lcuseraddstrerror($useraddok);
 6512: 		    &logthis("Failed lcuseradd: $error_text");
 6513: 		    $result = "lcuseradd_failed:$error_text";
 6514: 		}  else {
 6515: 		    my $pf = IO::File->new(">$passfilename");
 6516: 		    if($pf) {
 6517: 			print $pf "unix:\n";
 6518: 		    } else {
 6519: 			$result = "pass_file_failed_error";
 6520: 		    }
 6521: 		}
 6522: 	    }  else {
 6523: 		&Debug("Could not locate lcuseradd error: $lc_error_file");
 6524: 		$result="bug_lcuseradd_no_output_file";
 6525: 	    }
 6526: 	}
 6527:     } elsif ($umode eq 'none') {
 6528: 	{
 6529: 	    my $pf = IO::File->new("> $passfilename");
 6530: 	    if($pf) {
 6531: 		print $pf "none:\n";
 6532: 	    } else {
 6533: 		$result = "pass_file_failed_error";
 6534: 	    }
 6535: 	}
 6536:     } else {
 6537: 	$result="auth_mode_error";
 6538:     }
 6539:     return $result;
 6540: }
 6541: 
 6542: sub convert_photo {
 6543:     my ($start,$dest)=@_;
 6544:     system("convert $start $dest");
 6545: }
 6546: 
 6547: sub sethost {
 6548:     my ($remotereq) = @_;
 6549:     my (undef,$hostid)=split(/:/,$remotereq);
 6550:     # ignore sethost if we are already correct
 6551:     if ($hostid eq $currenthostid) {
 6552: 	return 'ok';
 6553:     }
 6554: 
 6555:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
 6556:     if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'}) 
 6557: 	eq &Apache::lonnet::get_host_ip($hostid)) {
 6558: 	$currenthostid  =$hostid;
 6559: 	$currentdomainid=&Apache::lonnet::host_domain($hostid);
 6560: 	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
 6561:     } else {
 6562: 	&logthis("Requested host id $hostid not an alias of ".
 6563: 		 $perlvar{'lonHostID'}." refusing connection");
 6564: 	return 'unable_to_set';
 6565:     }
 6566:     return 'ok';
 6567: }
 6568: 
 6569: sub version {
 6570:     my ($userinput)=@_;
 6571:     $remoteVERSION=(split(/:/,$userinput))[1];
 6572:     return "version:$VERSION";
 6573: }
 6574: 
 6575: 
 6576: # ----------------------------------- POD (plain old documentation, CPAN style)
 6577: 
 6578: =head1 NAME
 6579: 
 6580: lond - "LON Daemon" Server (port "LOND" 5663)
 6581: 
 6582: =head1 SYNOPSIS
 6583: 
 6584: Usage: B<lond>
 6585: 
 6586: Should only be run as user=www.  This is a command-line script which
 6587: is invoked by B<loncron>.  There is no expectation that a typical user
 6588: will manually start B<lond> from the command-line.  (In other words,
 6589: DO NOT START B<lond> YOURSELF.)
 6590: 
 6591: =head1 DESCRIPTION
 6592: 
 6593: There are two characteristics associated with the running of B<lond>,
 6594: PROCESS MANAGEMENT (starting, stopping, handling child processes)
 6595: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
 6596: subscriptions, etc).  These are described in two large
 6597: sections below.
 6598: 
 6599: B<PROCESS MANAGEMENT>
 6600: 
 6601: Preforker - server who forks first. Runs as a daemon. HUPs.
 6602: Uses IDEA encryption
 6603: 
 6604: B<lond> forks off children processes that correspond to the other servers
 6605: in the network.  Management of these processes can be done at the
 6606: parent process level or the child process level.
 6607: 
 6608: B<logs/lond.log> is the location of log messages.
 6609: 
 6610: The process management is now explained in terms of linux shell commands,
 6611: subroutines internal to this code, and signal assignments:
 6612: 
 6613: =over 4
 6614: 
 6615: =item *
 6616: 
 6617: PID is stored in B<logs/lond.pid>
 6618: 
 6619: This is the process id number of the parent B<lond> process.
 6620: 
 6621: =item *
 6622: 
 6623: SIGTERM and SIGINT
 6624: 
 6625: Parent signal assignment:
 6626:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 6627: 
 6628: Child signal assignment:
 6629:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
 6630: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
 6631:  to restart a new child.)
 6632: 
 6633: Command-line invocations:
 6634:  B<kill> B<-s> SIGTERM I<PID>
 6635:  B<kill> B<-s> SIGINT I<PID>
 6636: 
 6637: Subroutine B<HUNTSMAN>:
 6638:  This is only invoked for the B<lond> parent I<PID>.
 6639: This kills all the children, and then the parent.
 6640: The B<lonc.pid> file is cleared.
 6641: 
 6642: =item *
 6643: 
 6644: SIGHUP
 6645: 
 6646: Current bug:
 6647:  This signal can only be processed the first time
 6648: on the parent process.  Subsequent SIGHUP signals
 6649: have no effect.
 6650: 
 6651: Parent signal assignment:
 6652:  $SIG{HUP}  = \&HUPSMAN;
 6653: 
 6654: Child signal assignment:
 6655:  none (nothing happens)
 6656: 
 6657: Command-line invocations:
 6658:  B<kill> B<-s> SIGHUP I<PID>
 6659: 
 6660: Subroutine B<HUPSMAN>:
 6661:  This is only invoked for the B<lond> parent I<PID>,
 6662: This kills all the children, and then the parent.
 6663: The B<lond.pid> file is cleared.
 6664: 
 6665: =item *
 6666: 
 6667: SIGUSR1
 6668: 
 6669: Parent signal assignment:
 6670:  $SIG{USR1} = \&USRMAN;
 6671: 
 6672: Child signal assignment:
 6673:  $SIG{USR1}= \&logstatus;
 6674: 
 6675: Command-line invocations:
 6676:  B<kill> B<-s> SIGUSR1 I<PID>
 6677: 
 6678: Subroutine B<USRMAN>:
 6679:  When invoked for the B<lond> parent I<PID>,
 6680: SIGUSR1 is sent to all the children, and the status of
 6681: each connection is logged.
 6682: 
 6683: =item *
 6684: 
 6685: SIGUSR2
 6686: 
 6687: Parent Signal assignment:
 6688:     $SIG{USR2} = \&UpdateHosts
 6689: 
 6690: Child signal assignment:
 6691:     NONE
 6692: 
 6693: 
 6694: =item *
 6695: 
 6696: SIGCHLD
 6697: 
 6698: Parent signal assignment:
 6699:  $SIG{CHLD} = \&REAPER;
 6700: 
 6701: Child signal assignment:
 6702:  none
 6703: 
 6704: Command-line invocations:
 6705:  B<kill> B<-s> SIGCHLD I<PID>
 6706: 
 6707: Subroutine B<REAPER>:
 6708:  This is only invoked for the B<lond> parent I<PID>.
 6709: Information pertaining to the child is removed.
 6710: The socket port is cleaned up.
 6711: 
 6712: =back
 6713: 
 6714: B<SERVER-SIDE ACTIVITIES>
 6715: 
 6716: Server-side information can be accepted in an encrypted or non-encrypted
 6717: method.
 6718: 
 6719: =over 4
 6720: 
 6721: =item ping
 6722: 
 6723: Query a client in the hosts.tab table; "Are you there?"
 6724: 
 6725: =item pong
 6726: 
 6727: Respond to a ping query.
 6728: 
 6729: =item ekey
 6730: 
 6731: Read in encrypted key, make cipher.  Respond with a buildkey.
 6732: 
 6733: =item load
 6734: 
 6735: Respond with CPU load based on a computation upon /proc/loadavg.
 6736: 
 6737: =item currentauth
 6738: 
 6739: Reply with current authentication information (only over an
 6740: encrypted channel).
 6741: 
 6742: =item auth
 6743: 
 6744: Only over an encrypted channel, reply as to whether a user's
 6745: authentication information can be validated.
 6746: 
 6747: =item passwd
 6748: 
 6749: Allow for a password to be set.
 6750: 
 6751: =item makeuser
 6752: 
 6753: Make a user.
 6754: 
 6755: =item passwd
 6756: 
 6757: Allow for authentication mechanism and password to be changed.
 6758: 
 6759: =item home
 6760: 
 6761: Respond to a question "are you the home for a given user?"
 6762: 
 6763: =item update
 6764: 
 6765: Update contents of a subscribed resource.
 6766: 
 6767: =item unsubscribe
 6768: 
 6769: The server is unsubscribing from a resource.
 6770: 
 6771: =item subscribe
 6772: 
 6773: The server is subscribing to a resource.
 6774: 
 6775: =item log
 6776: 
 6777: Place in B<logs/lond.log>
 6778: 
 6779: =item put
 6780: 
 6781: stores hash in namespace
 6782: 
 6783: =item rolesputy
 6784: 
 6785: put a role into a user's environment
 6786: 
 6787: =item get
 6788: 
 6789: returns hash with keys from array
 6790: reference filled in from namespace
 6791: 
 6792: =item eget
 6793: 
 6794: returns hash with keys from array
 6795: reference filled in from namesp (encrypts the return communication)
 6796: 
 6797: =item rolesget
 6798: 
 6799: get a role from a user's environment
 6800: 
 6801: =item del
 6802: 
 6803: deletes keys out of array from namespace
 6804: 
 6805: =item keys
 6806: 
 6807: returns namespace keys
 6808: 
 6809: =item dump
 6810: 
 6811: dumps the complete (or key matching regexp) namespace into a hash
 6812: 
 6813: =item store
 6814: 
 6815: stores hash permanently
 6816: for this url; hashref needs to be given and should be a \%hashname; the
 6817: remaining args aren't required and if they aren't passed or are '' they will
 6818: be derived from the ENV
 6819: 
 6820: =item restore
 6821: 
 6822: returns a hash for a given url
 6823: 
 6824: =item querysend
 6825: 
 6826: Tells client about the lonsql process that has been launched in response
 6827: to a sent query.
 6828: 
 6829: =item queryreply
 6830: 
 6831: Accept information from lonsql and make appropriate storage in temporary
 6832: file space.
 6833: 
 6834: =item idput
 6835: 
 6836: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
 6837: for each student, defined perhaps by the institutional Registrar.)
 6838: 
 6839: =item idget
 6840: 
 6841: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
 6842: for each student, defined perhaps by the institutional Registrar.)
 6843: 
 6844: =item tmpput
 6845: 
 6846: Accept and store information in temporary space.
 6847: 
 6848: =item tmpget
 6849: 
 6850: Send along temporarily stored information.
 6851: 
 6852: =item ls
 6853: 
 6854: List part of a user's directory.
 6855: 
 6856: =item pushtable
 6857: 
 6858: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
 6859: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
 6860: must be restored manually in case of a problem with the new table file.
 6861: pushtable requires that the request be encrypted and validated via
 6862: ValidateManager.  The form of the command is:
 6863: enc:pushtable tablename <tablecontents> \n
 6864: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
 6865: cleartext newline.
 6866: 
 6867: =item Hanging up (exit or init)
 6868: 
 6869: What to do when a client tells the server that they (the client)
 6870: are leaving the network.
 6871: 
 6872: =item unknown command
 6873: 
 6874: If B<lond> is sent an unknown command (not in the list above),
 6875: it replys to the client "unknown_cmd".
 6876: 
 6877: 
 6878: =item UNKNOWN CLIENT
 6879: 
 6880: If the anti-spoofing algorithm cannot verify the client,
 6881: the client is rejected (with a "refused" message sent
 6882: to the client, and the connection is closed.
 6883: 
 6884: =back
 6885: 
 6886: =head1 PREREQUISITES
 6887: 
 6888: IO::Socket
 6889: IO::File
 6890: Apache::File
 6891: POSIX
 6892: Crypt::IDEA
 6893: LWP::UserAgent()
 6894: GDBM_File
 6895: Authen::Krb4
 6896: Authen::Krb5
 6897: 
 6898: =head1 COREQUISITES
 6899: 
 6900: =head1 OSNAMES
 6901: 
 6902: linux
 6903: 
 6904: =head1 SCRIPT CATEGORIES
 6905: 
 6906: Server/Process
 6907: 
 6908: =cut

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