Annotation of loncom/lond, revision 1.328

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

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