Annotation of loncom/lond, revision 1.489.2.27

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