File:  [LON-CAPA] / loncom / lond
Revision 1.415: download - view: text, annotated - select for diffs
Fri May 8 12:02:39 2009 UTC (14 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD, BZ5434-fox
dump_domainroles_handler:
 start and end need to defined for roles to be filtered out  based on start date and/or end date.

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

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