File:  [LON-CAPA] / loncom / lond
Revision 1.373: download - view: text, annotated - select for diffs
Tue Apr 10 23:11:30 2007 UTC (17 years ago) by albertel
Branches: MAIN
CVS tags: version_2_3_99_0, HEAD
- eliminate a unneeded global

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

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