Annotation of loncom/lond, revision 1.467

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