Annotation of loncom/lond, revision 1.395

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

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