Annotation of loncom/lond, revision 1.306

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

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