Annotation of loncom/lond, revision 1.330

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

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