File:  [LON-CAPA] / loncom / lond
Revision 1.454: download - view: text, annotated - select for diffs
Sun Aug 22 19:28:26 2010 UTC (13 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_10_0_RC1, HEAD
- Change the way tokens are named.

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

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