Annotation of loncom/lond, revision 1.329

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

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