Annotation of loncom/lond, revision 1.408

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

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