Annotation of loncom/lond, revision 1.522

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

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