Annotation of loncom/lond, revision 1.459

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

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>
500 Internal Server Error

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator at root@localhost to inform them of the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log.