Annotation of loncom/lond, revision 1.519

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

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