Annotation of loncom/lond, revision 1.356

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

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