File:  [LON-CAPA] / loncom / lond
Revision 1.508: download - view: text, annotated - select for diffs
Wed Apr 16 14:39:59 2014 UTC (10 years ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Course requests for unofficial courses, textbook courses and communities
  can include validation.
  - lonrequestcourse.pm
    - New subroutine: pending_validation_form() generates web form used to
      proceed to validation (can be local script, or script on remote server)
    - Prepended new arg to args passed to: &print_request_outcome() and
      &process_request()  -- $lonhost (lonHostID of current server).
 - localenroll.pm
   - &validate_crsreq() accepts additional (optional) arg -- ref to hash of
     custominfo.
   - &crsreq_updates() supports additional action type ('prevalidate') which
     is used to generate form elements needed for validation of request.
 - lond
   - &validate_crsreq_handler() accepts additional -- $customdata
     which is a frozen hash of custominfo passed in from lonnet.pm
 - lonnet.pm
   - &auto_courserequest_validation() accepts additional arg -- ref to hash of
     custominfo (contains key => value for custm form elements retrieved from
     course request review page.

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

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