Annotation of loncom/lond, revision 1.250

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

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