Annotation of loncom/lond, revision 1.301

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

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