File:  [LON-CAPA] / loncom / lond
Revision 1.525: download - view: text, annotated - select for diffs
Mon Sep 12 20:20:44 2016 UTC (7 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Domain Trust Settings

    1: #!/usr/bin/perl
    2: # The LearningOnline Network
    3: # lond "LON Daemon" Server (port "LOND" 5663)
    4: #
    5: # $Id: lond,v 1.525 2016/09/12 20:20:44 raeburn Exp $
    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
   13: # the Free Software Foundation; either version 2 of the License, or 
   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
   23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   24: #
   25: # /home/httpd/html/adm/gpl.txt
   26: #
   27: 
   28: 
   29: # http://www.lon-capa.org/
   30: #
   31: 
   32: use strict;
   33: use lib '/home/httpd/lib/perl/';
   34: use LONCAPA;
   35: use LONCAPA::Configuration;
   36: use LONCAPA::Lond;
   37: 
   38: use IO::Socket;
   39: use IO::File;
   40: #use Apache::File;
   41: use POSIX;
   42: use Crypt::IDEA;
   43: use HTTP::Request;
   44: use Digest::MD5 qw(md5_hex);
   45: use GDBM_File;
   46: use Authen::Krb5;
   47: use localauth;
   48: use localenroll;
   49: use localstudentphoto;
   50: use File::Copy;
   51: use File::Find;
   52: use LONCAPA::lonlocal;
   53: use LONCAPA::lonssl;
   54: use Fcntl qw(:flock);
   55: use Apache::lonnet;
   56: use Mail::Send;
   57: use Crypt::Eksblowfish::Bcrypt;
   58: use Digest::SHA;
   59: use Encode;
   60: use LONCAPA::LWPReq;
   61: 
   62: my $DEBUG = 0;		       # Non zero to enable debug log entries.
   63: 
   64: my $status='';
   65: my $lastlog='';
   66: 
   67: my $VERSION='$Revision: 1.525 $'; #' stupid emacs
   68: my $remoteVERSION;
   69: my $currenthostid="default";
   70: my $currentdomainid;
   71: 
   72: my $client;
   73: my $clientip;			# IP address of client.
   74: my $clientname;			# LonCAPA name of client.
   75: my $clientversion;              # LonCAPA version running on client.
   76: my $clienthomedom;              # LonCAPA domain of homeID for client. 
   77: my $clientintdom;               # LonCAPA "internet domain" for client.
   78: my $clientsameinst;             # LonCAPA "internet domain" same for 
   79:                                 # this host and client.
   80: my $clientremoteok;             # Client allowed to host domain's users.
   81:                                 # (version constraints ignored), not set
   82:                                 # if this host and client share "internet domain". 
   83: my %clientprohibited;           # Actions prohibited on client;
   84:  
   85: my $server;
   86: 
   87: my $keymode;
   88: 
   89: my $cipher;			# Cipher key negotiated with client
   90: my $tmpsnum = 0;		# Id of tmpputs.
   91: 
   92: # 
   93: #   Connection type is:
   94: #      client                   - All client actions are allowed
   95: #      manager                  - only management functions allowed.
   96: #      both                     - Both management and client actions are allowed
   97: #
   98: 
   99: my $ConnectionType;
  100: 
  101: my %managers;			# Ip -> manager names
  102: 
  103: my %perlvar;			# Will have the apache conf defined perl vars.
  104: 
  105: my $dist;
  106: 
  107: #
  108: #   The hash below is used for command dispatching, and is therefore keyed on the request keyword.
  109: #    Each element of the hash contains a reference to an array that contains:
  110: #          A reference to a sub that executes the request corresponding to the keyword.
  111: #          A flag that is true if the request must be encoded to be acceptable.
  112: #          A mask with bits as follows:
  113: #                      CLIENT_OK    - Set when the function is allowed by ordinary clients
  114: #                      MANAGER_OK   - Set when the function is allowed to manager clients.
  115: #
  116: my $CLIENT_OK  = 1;
  117: my $MANAGER_OK = 2;
  118: my %Dispatcher;
  119: 
  120: 
  121: #
  122: #  The array below are password error strings."
  123: #
  124: my $lastpwderror    = 13;		# Largest error number from lcpasswd.
  125: my @passwderrors = ("ok",
  126: 		   "pwchange_failure - lcpasswd must be run as user 'www'",
  127: 		   "pwchange_failure - lcpasswd got incorrect number of arguments",
  128: 		   "pwchange_failure - lcpasswd did not get the right nubmer of input text lines",
  129: 		   "pwchange_failure - lcpasswd too many simultaneous pwd changes in progress",
  130: 		   "pwchange_failure - lcpasswd User does not exist.",
  131: 		   "pwchange_failure - lcpasswd Incorrect current passwd",
  132: 		   "pwchange_failure - lcpasswd Unable to su to root.",
  133: 		   "pwchange_failure - lcpasswd Cannot set new passwd.",
  134: 		   "pwchange_failure - lcpasswd Username has invalid characters",
  135: 		   "pwchange_failure - lcpasswd Invalid characters in password",
  136: 		   "pwchange_failure - lcpasswd User already exists", 
  137:                    "pwchange_failure - lcpasswd Something went wrong with user addition.",
  138: 		   "pwchange_failure - lcpasswd Password mismatch",
  139: 		   "pwchange_failure - lcpasswd Error filename is invalid");
  140: 
  141: 
  142: # This array are the errors from lcinstallfile:
  143: 
  144: my @installerrors = ("ok",
  145: 		     "Initial user id of client not that of www",
  146: 		     "Usage error, not enough command line arguments",
  147: 		     "Source filename does not exist",
  148: 		     "Destination filename does not exist",
  149: 		     "Some file operation failed",
  150: 		     "Invalid table filename."
  151: 		     );
  152: 
  153: #
  154: # The %trust hash classifies commands according to type of trust 
  155: # required for execution of the command.
  156: #
  157: # When clients from a different institution request execution of a
  158: # particular command, the trust settings for that institution set
  159: # for this domain (or default domain for a multi-domain server) will
  160: # be checked to see if running the command is allowed.
  161: #
  162: # Trust types which depend on the "Trust" domain configuration
  163: # for the machine's default domain are:
  164: #
  165: # content   ("Access to this domain's content by others")
  166: # shared    ("Access to other domain's content by this domain")
  167: # enroll    ("Enrollment in this domain's courses by others")
  168: # coaurem   ("Co-author roles for this domain's users elsewhere")
  169: # domroles  ("Domain roles in this domain assignable to others")
  170: # catalog   ("Course Catalog for this domain displayed elsewhere")
  171: # reqcrs    ("Requests for creation of courses in this domain by others")
  172: # msg       ("Users in other domains can send messages to this domain")
  173: # 
  174: # Trust type which depends on the User Session Hosting (remote) 
  175: # domain configuration for machine's default domain is: "remote".
  176: #
  177: # Trust types which depend on contents of manager.tab in 
  178: # /home/httpd/lonTabs is: "manageronly".
  179: # 
  180: # Trust type which requires client to share the same LON-CAPA
  181: # "internet domain" (i.e., same institution as this server) is:
  182: # "institutiononly".
  183: #
  184: 
  185: my %trust = (
  186:                auth => {remote => 1},
  187:                autocreatepassword => {remote => 1},
  188:                autocrsreqchecks => {remote => 1, reqcrs => 1},
  189:                autocrsrequpdate => {remote => 1},
  190:                autocrsreqvalidation => {remote => 1},
  191:                autogetsections => {remote => 1},
  192:                autoinstcodedefaults => {remote => 1, catalog => 1},
  193:                autoinstcodeformat => {remote => 1, catalog => 1},
  194:                autonewcourse => {remote => 1, reqcrs => 1},
  195:                autophotocheck => {remote => 1, enroll => 1},
  196:                autophotochoice => {remote => 1},
  197:                autophotopermission => {remote => 1, enroll => 1},
  198:                autopossibleinstcodes => {remote => 1, reqcrs => 1},
  199:                autoretrieve => {remote => 1, enroll => 1, catalog => 1},
  200:                autorun => {remote => 1, enroll => 1, reqcrs => 1},
  201:                autovalidateclass_sec => {catalog => 1},
  202:                autovalidatecourse => {remote => 1, enroll => 1},
  203:                autovalidateinstcode => {domroles => 1, remote => 1, enroll => 1},
  204:                changeuserauth => {remote => 1, domroles => 1},
  205:                chatretr => {remote => 1, enroll => 1},
  206:                chatsend => {remote => 1, enroll => 1},
  207:                courseiddump => {remote => 1, domroles => 1, enroll => 1},
  208:                courseidput => {remote => 1, domroles => 1, enroll => 1},
  209:                courseidputhash => {remote => 1, domroles => 1, enroll => 1},
  210:                courselastaccess => {remote => 1, domroles => 1, enroll => 1},
  211:                currentauth => {remote => 1, domroles => 1, enroll => 1},
  212:                currentdump => {remote => 1, enroll => 1},
  213:                currentversion => {remote=> 1, content => 1},
  214:                dcmaildump => {remote => 1, domroles => 1},
  215:                dcmailput => {remote => 1, domroles => 1},
  216:                del => {remote => 1, domroles => 1, enroll => 1, content => 1},
  217:                deldom => {remote => 1, domroles => 1}, # not currently used
  218:                devalidatecache => {institutiononly => 1},
  219:                domroleput => {remote => 1, enroll => 1},
  220:                domrolesdump => {remote => 1, catalog => 1},
  221:                du => {remote => 1, enroll => 1},
  222:                du2 => {remote => 1, enroll => 1},
  223:                dump => {remote => 1, enroll => 1, domroles => 1},
  224:                edit => {institutiononly => 1},  #not used currently
  225:                eget => {remote => 1, domroles => 1, enroll => 1}, #not used currently
  226:                ekey => {}, #not used currently
  227:                exit => {anywhere => 1},
  228:                fetchuserfile => {remote => 1, enroll => 1},
  229:                get => {remote => 1, domroles => 1, enroll => 1},
  230:                getdom => {anywhere => 1},
  231:                home => {anywhere => 1},
  232:                iddel => {remote => 1, enroll => 1},
  233:                idget => {remote => 1, enroll => 1},
  234:                idput => {remote => 1, domroles => 1, enroll => 1},
  235:                inc => {remote => 1, enroll => 1},
  236:                init => {anywhere => 1},
  237:                inst_usertypes => {remote => 1, domroles => 1, enroll => 1},
  238:                instemailrules => {remote => 1, domroles => 1},
  239:                instidrulecheck => {remote => 1, domroles => 1,},
  240:                instidrules => {remote => 1, domroles => 1,},
  241:                instrulecheck => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
  242:                instselfcreatecheck => {institutiononly => 1},
  243:                instuserrules => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
  244:                keys => {remote => 1,},
  245:                load => {anywhere => 1},
  246:                log => {anywhere => 1},
  247:                ls => {remote => 1, enroll => 1, content => 1,},
  248:                ls2 => {remote => 1, enroll => 1, content => 1,},
  249:                ls3 => {remote => 1, enroll => 1, content => 1,},
  250:                makeuser => {remote => 1, enroll => 1, domroles => 1,},
  251:                mkdiruserfile => {remote => 1, enroll => 1,},
  252:                newput => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1,},
  253:                passwd => {remote => 1},
  254:                ping => {anywhere => 1},
  255:                pong => {anywhere => 1},
  256:                pushfile => {manageronly => 1},
  257:                put => {remote => 1, enroll => 1, domroles => 1, msg => 1, content => 1, shared => 1},
  258:                putdom => {remote => 1, domroles => 1,},
  259:                putstore => {remote => 1, enroll => 1},
  260:                queryreply => {anywhere => 1},
  261:                querysend => {anywhere => 1},
  262:                quit => {anywhere => 1},
  263:                readlonnetglobal => {institutiononly => 1},
  264:                reinit => {manageronly => 1}, #not used currently
  265:                removeuserfile => {remote => 1, enroll => 1},
  266:                renameuserfile => {remote => 1,},
  267:                restore => {remote => 1, enroll => 1, reqcrs => 1,},
  268:                rolesdel => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
  269:                rolesput => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
  270:                serverdistarch => {manageronly => 1},
  271:                serverhomeID => {anywhere => 1},
  272:                serverloncaparev => {anywhere => 1},
  273:                servertimezone => {remote => 1, enroll => 1},
  274:                setannounce => {remote => 1, domroles => 1},
  275:                sethost => {anywhere => 1},
  276:                store => {remote => 1, enroll => 1, reqcrs => 1,},
  277:                studentphoto => {remote => 1, enroll => 1},
  278:                sub => {content => 1,},
  279:                tmpdel => {anywhere => 1},
  280:                tmpget => {anywhere => 1},
  281:                tmpput => {anywhere => 1},
  282:                tokenauthuserfile => {anywhere => 1},
  283:                unsub => {content => 1,},
  284:                update => {shared => 1},
  285:                updateclickers => {remote => 1},
  286:                userhassession => {anywhere => 1},
  287:                userload => {anywhere => 1},
  288:                version => {anywhere => 1}, #not used
  289:             );
  290: 
  291: #
  292: #   Statistics that are maintained and dislayed in the status line.
  293: #
  294: my $Transactions = 0;		# Number of attempted transactions.
  295: my $Failures     = 0;		# Number of transcations failed.
  296: 
  297: #   ResetStatistics: 
  298: #      Resets the statistics counters:
  299: #
  300: sub ResetStatistics {
  301:     $Transactions = 0;
  302:     $Failures     = 0;
  303: }
  304: 
  305: #------------------------------------------------------------------------
  306: #
  307: #   LocalConnection
  308: #     Completes the formation of a locally authenticated connection.
  309: #     This function will ensure that the 'remote' client is really the
  310: #     local host.  If not, the connection is closed, and the function fails.
  311: #     If so, initcmd is parsed for the name of a file containing the
  312: #     IDEA session key.  The fie is opened, read, deleted and the session
  313: #     key returned to the caller.
  314: #
  315: # Parameters:
  316: #   $Socket      - Socket open on client.
  317: #   $initcmd     - The full text of the init command.
  318: #
  319: # Returns:
  320: #     IDEA session key on success.
  321: #     undef on failure.
  322: #
  323: sub LocalConnection {
  324:     my ($Socket, $initcmd) = @_;
  325:     Debug("Attempting local connection: $initcmd client: $clientip");
  326:     if($clientip ne "127.0.0.1") {
  327: 	&logthis('<font color="red"> LocalConnection rejecting non local: '
  328: 		 ."$clientip ne 127.0.0.1 </font>");
  329: 	close $Socket;
  330: 	return undef;
  331:     }  else {
  332: 	chomp($initcmd);	# Get rid of \n in filename.
  333: 	my ($init, $type, $name) = split(/:/, $initcmd);
  334: 	Debug(" Init command: $init $type $name ");
  335: 
  336: 	# Require that $init = init, and $type = local:  Otherwise
  337: 	# the caller is insane:
  338: 
  339: 	if(($init ne "init") && ($type ne "local")) {
  340: 	    &logthis('<font color = "red"> LocalConnection: caller is insane! '
  341: 		     ."init = $init, and type = $type </font>");
  342: 	    close($Socket);;
  343: 	    return undef;
  344: 		
  345: 	}
  346: 	#  Now get the key filename:
  347: 
  348: 	my $IDEAKey = lonlocal::ReadKeyFile($name);
  349: 	return $IDEAKey;
  350:     }
  351: }
  352: #------------------------------------------------------------------------------
  353: #
  354: #  SSLConnection
  355: #   Completes the formation of an ssh authenticated connection. The
  356: #   socket is promoted to an ssl socket.  If this promotion and the associated
  357: #   certificate exchange are successful, the IDEA key is generated and sent
  358: #   to the remote peer via the SSL tunnel. The IDEA key is also returned to
  359: #   the caller after the SSL tunnel is torn down.
  360: #
  361: # Parameters:
  362: #   Name              Type             Purpose
  363: #   $Socket          IO::Socket::INET  Plaintext socket.
  364: #
  365: # Returns:
  366: #    IDEA key on success.
  367: #    undef on failure.
  368: #
  369: sub SSLConnection {
  370:     my $Socket   = shift;
  371: 
  372:     Debug("SSLConnection: ");
  373:     my $KeyFile         = lonssl::KeyFile();
  374:     if(!$KeyFile) {
  375: 	my $err = lonssl::LastError();
  376: 	&logthis("<font color=\"red\"> CRITICAL"
  377: 		 ."Can't get key file $err </font>");
  378: 	return undef;
  379:     }
  380:     my ($CACertificate,
  381: 	$Certificate) = lonssl::CertificateFile();
  382: 
  383: 
  384:     # If any of the key, certificate or certificate authority 
  385:     # certificate filenames are not defined, this can't work.
  386: 
  387:     if((!$Certificate) || (!$CACertificate)) {
  388: 	my $err = lonssl::LastError();
  389: 	&logthis("<font color=\"red\"> CRITICAL"
  390: 		 ."Can't get certificates: $err </font>");
  391: 
  392: 	return undef;
  393:     }
  394:     Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
  395: 
  396:     # Indicate to our peer that we can procede with
  397:     # a transition to ssl authentication:
  398: 
  399:     print $Socket "ok:ssl\n";
  400: 
  401:     Debug("Approving promotion -> ssl");
  402:     #  And do so:
  403: 
  404:     my $SSLSocket = lonssl::PromoteServerSocket($Socket,
  405: 						$CACertificate,
  406: 						$Certificate,
  407: 						$KeyFile);
  408:     if(! ($SSLSocket) ) {	# SSL socket promotion failed.
  409: 	my $err = lonssl::LastError();
  410: 	&logthis("<font color=\"red\"> CRITICAL "
  411: 		 ."SSL Socket promotion failed: $err </font>");
  412: 	return undef;
  413:     }
  414:     Debug("SSL Promotion successful");
  415: 
  416:     # 
  417:     #  The only thing we'll use the socket for is to send the IDEA key
  418:     #  to the peer:
  419: 
  420:     my $Key = lonlocal::CreateCipherKey();
  421:     print $SSLSocket "$Key\n";
  422: 
  423:     lonssl::Close($SSLSocket); 
  424: 
  425:     Debug("Key exchange complete: $Key");
  426: 
  427:     return $Key;
  428: }
  429: #
  430: #     InsecureConnection: 
  431: #        If insecure connections are allowd,
  432: #        exchange a challenge with the client to 'validate' the
  433: #        client (not really, but that's the protocol):
  434: #        We produce a challenge string that's sent to the client.
  435: #        The client must then echo the challenge verbatim to us.
  436: #
  437: #  Parameter:
  438: #      Socket      - Socket open on the client.
  439: #  Returns:
  440: #      1           - success.
  441: #      0           - failure (e.g.mismatch or insecure not allowed).
  442: #
  443: sub InsecureConnection {
  444:     my $Socket  =  shift;
  445: 
  446:     #   Don't even start if insecure connections are not allowed.
  447: 
  448:     if(! $perlvar{londAllowInsecure}) {	# Insecure connections not allowed.
  449: 	return 0;
  450:     }
  451: 
  452:     #   Fabricate a challenge string and send it..
  453: 
  454:     my $challenge = "$$".time;	# pid + time.
  455:     print $Socket "$challenge\n";
  456:     &status("Waiting for challenge reply");
  457: 
  458:     my $answer = <$Socket>;
  459:     $answer    =~s/\W//g;
  460:     if($challenge eq $answer) {
  461: 	return 1;
  462:     } else {
  463: 	logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
  464: 	&status("No challenge reqply");
  465: 	return 0;
  466:     }
  467:     
  468: 
  469: }
  470: #
  471: #   Safely execute a command (as long as it's not a shel command and doesn
  472: #   not require/rely on shell escapes.   The function operates by doing a
  473: #   a pipe based fork and capturing stdout and stderr  from the pipe.
  474: #
  475: # Formal Parameters:
  476: #     $line                    - A line of text to be executed as a command.
  477: # Returns:
  478: #     The output from that command.  If the output is multiline the caller
  479: #     must know how to split up the output.
  480: #
  481: #
  482: sub execute_command {
  483:     my ($line)    = @_;
  484:     my @words     = split(/\s/, $line);	# Bust the command up into words.
  485:     my $output    = "";
  486: 
  487:     my $pid = open(CHILD, "-|");
  488:     
  489:     if($pid) {			# Parent process
  490: 	Debug("In parent process for execute_command");
  491: 	my @data = <CHILD>;	# Read the child's outupt...
  492: 	close CHILD;
  493: 	foreach my $output_line (@data) {
  494: 	    Debug("Adding $output_line");
  495: 	    $output .= $output_line; # Presumably has a \n on it.
  496: 	}
  497: 
  498:     } else {			# Child process
  499: 	close (STDERR);
  500: 	open  (STDERR, ">&STDOUT");# Combine stderr, and stdout...
  501: 	exec(@words);		# won't return.
  502:     }
  503:     return $output;
  504: }
  505: 
  506: 
  507: #   GetCertificate: Given a transaction that requires a certificate,
  508: #   this function will extract the certificate from the transaction
  509: #   request.  Note that at this point, the only concept of a certificate
  510: #   is the hostname to which we are connected.
  511: #
  512: #   Parameter:
  513: #      request   - The request sent by our client (this parameterization may
  514: #                  need to change when we really use a certificate granting
  515: #                  authority.
  516: #
  517: sub GetCertificate {
  518:     my $request = shift;
  519: 
  520:     return $clientip;
  521: }
  522: 
  523: #
  524: #   Return true if client is a manager.
  525: #
  526: sub isManager {
  527:     return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
  528: }
  529: #
  530: #   Return tru if client can do client functions
  531: #
  532: sub isClient {
  533:     return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
  534: }
  535: 
  536: 
  537: #
  538: #   ReadManagerTable: Reads in the current manager table. For now this is
  539: #                     done on each manager authentication because:
  540: #                     - These authentications are not frequent
  541: #                     - This allows dynamic changes to the manager table
  542: #                       without the need to signal to the lond.
  543: #
  544: sub ReadManagerTable {
  545: 
  546:     &Debug("Reading manager table");
  547:     #   Clean out the old table first..
  548: 
  549:    foreach my $key (keys %managers) {
  550:       delete $managers{$key};
  551:    }
  552: 
  553:    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
  554:    if (!open (MANAGERS, $tablename)) {
  555:        my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
  556:        if (&Apache::lonnet::is_LC_dns($hostname)) {
  557:            &logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
  558:        }
  559:        return;
  560:    }
  561:    while(my $host = <MANAGERS>) {
  562:       chomp($host);
  563:       if ($host =~ "^#") {                  # Comment line.
  564:          next;
  565:       }
  566:       if (!defined &Apache::lonnet::get_host_ip($host)) { # This is a non cluster member
  567: 	    #  The entry is of the form:
  568: 	    #    cluname:hostname
  569: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
  570: 	    #            the host key.
  571: 	    #  hostname- The dns name of the host.
  572: 	    #
  573:           my($cluname, $dnsname) = split(/:/, $host);
  574:           
  575:           my $ip = gethostbyname($dnsname);
  576:           if(defined($ip)) {                 # bad names don't deserve entry.
  577:             my $hostip = inet_ntoa($ip);
  578:             $managers{$hostip} = $cluname;
  579:             logthis('<font color="green"> registering manager '.
  580:                     "$dnsname as $cluname with $hostip </font>\n");
  581:          }
  582:       } else {
  583:          logthis('<font color="green"> existing host'." $host</font>\n");
  584:          $managers{&Apache::lonnet::get_host_ip($host)} = $host;  # Use info from cluster tab if cluster memeber
  585:       }
  586:    }
  587: }
  588: 
  589: #
  590: #  ValidManager: Determines if a given certificate represents a valid manager.
  591: #                in this primitive implementation, the 'certificate' is
  592: #                just the connecting loncapa client name.  This is checked
  593: #                against a valid client list in the configuration.
  594: #
  595: #                  
  596: sub ValidManager {
  597:     my $certificate = shift; 
  598: 
  599:     return isManager;
  600: }
  601: #
  602: #  CopyFile:  Called as part of the process of installing a 
  603: #             new configuration file.  This function copies an existing
  604: #             file to a backup file.
  605: # Parameters:
  606: #     oldfile  - Name of the file to backup.
  607: #     newfile  - Name of the backup file.
  608: # Return:
  609: #     0   - Failure (errno has failure reason).
  610: #     1   - Success.
  611: #
  612: sub CopyFile {
  613: 
  614:     my ($oldfile, $newfile) = @_;
  615: 
  616:     if (! copy($oldfile,$newfile)) {
  617:         return 0;
  618:     }
  619:     chmod(0660, $newfile);
  620:     return 1;
  621: }
  622: #
  623: #  Host files are passed out with externally visible host IPs.
  624: #  If, for example, we are behind a fire-wall or NAT host, our 
  625: #  internally visible IP may be different than the externally
  626: #  visible IP.  Therefore, we always adjust the contents of the
  627: #  host file so that the entry for ME is the IP that we believe
  628: #  we have.  At present, this is defined as the entry that
  629: #  DNS has for us.  If by some chance we are not able to get a
  630: #  DNS translation for us, then we assume that the host.tab file
  631: #  is correct.  
  632: #    BUGBUGBUG - in the future, we really should see if we can
  633: #       easily query the interface(s) instead.
  634: # Parameter(s):
  635: #     contents    - The contents of the host.tab to check.
  636: # Returns:
  637: #     newcontents - The adjusted contents.
  638: #
  639: #
  640: sub AdjustHostContents {
  641:     my $contents  = shift;
  642:     my $adjusted;
  643:     my $me        = $perlvar{'lonHostID'};
  644: 
  645:     foreach my $line (split(/\n/,$contents)) {
  646: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/) ||
  647:              ($line =~ /^\s*\^/))) {
  648: 	    chomp($line);
  649: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
  650: 	    if ($id eq $me) {
  651: 		my $ip = gethostbyname($name);
  652: 		my $ipnew = inet_ntoa($ip);
  653: 		$ip = $ipnew;
  654: 		#  Reconstruct the host line and append to adjusted:
  655: 		
  656: 		my $newline = "$id:$domain:$role:$name:$ip";
  657: 		if($maxcon ne "") { # Not all hosts have loncnew tuning params
  658: 		    $newline .= ":$maxcon:$idleto:$mincon";
  659: 		}
  660: 		$adjusted .= $newline."\n";
  661: 		
  662: 	    } else {		# Not me, pass unmodified.
  663: 		$adjusted .= $line."\n";
  664: 	    }
  665: 	} else {                  # Blank or comment never re-written.
  666: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
  667: 	}
  668:     }
  669:     return $adjusted;
  670: }
  671: #
  672: #   InstallFile: Called to install an administrative file:
  673: #       - The file is created int a temp directory called <name>.tmp
  674: #       - lcinstall file is called to install the file.
  675: #         since the web app has no direct write access to the table directory
  676: #
  677: #  Parameters:
  678: #       Name of the file
  679: #       File Contents.
  680: #  Return:
  681: #      nonzero - success.
  682: #      0       - failure and $! has an errno.
  683: # Assumptions:
  684: #    File installtion is a relatively infrequent
  685: #
  686: sub InstallFile {
  687: 
  688:     my ($Filename, $Contents) = @_;
  689: #     my $TempFile = $Filename.".tmp";
  690:     my $exedir = $perlvar{'lonDaemons'};
  691:     my $tmpdir = $exedir.'/tmp/';
  692:     my $TempFile = $tmpdir."TempTableFile.tmp";
  693: 
  694:     #  Open the file for write:
  695: 
  696:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
  697:     if(!(defined $fh)) {
  698: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
  699: 	return 0;
  700:     }
  701:     #  write the contents of the file:
  702: 
  703:     print $fh ($Contents); 
  704:     $fh->close;			# In case we ever have a filesystem w. locking
  705: 
  706:     chmod(0664, $TempFile);	# Everyone can write it.
  707: 
  708:     # Use lcinstall file to put the file in the table directory...
  709: 
  710:     &Debug("Opening pipe to $exedir/lcinstallfile $TempFile $Filename");
  711:     my $pf = IO::File->new("| $exedir/lcinstallfile   $TempFile $Filename > $exedir/logs/lcinstallfile.log");
  712:     close $pf;
  713:     my $err = $?;
  714:     &Debug("Status is $err");
  715:     if ($err != 0) {
  716: 	my $msg = $err;
  717: 	if ($err < @installerrors) {
  718: 	    $msg = $installerrors[$err];
  719: 	}
  720: 	&logthis("Install failed for table file $Filename : $msg");
  721: 	return 0;
  722:     }
  723: 
  724:     # Remove the temp file:
  725: 
  726:     unlink($TempFile);
  727: 
  728:     return 1;
  729: }
  730: 
  731: 
  732: #
  733: #   ConfigFileFromSelector: converts a configuration file selector
  734: #                 into a configuration file pathname.
  735: #                 Supports the following file selectors: 
  736: #                 hosts, domain, dns_hosts, dns_domain  
  737: #
  738: #
  739: #  Parameters:
  740: #      selector  - Configuration file selector.
  741: #  Returns:
  742: #      Full path to the file or undef if the selector is invalid.
  743: #
  744: sub ConfigFileFromSelector {
  745:     my $selector   = shift;
  746:     my $tablefile;
  747: 
  748:     my $tabledir = $perlvar{'lonTabDir'}.'/';
  749:     if (($selector eq "hosts") || ($selector eq "domain") || 
  750:         ($selector eq "dns_hosts") || ($selector eq "dns_domain")) {
  751: 	$tablefile =  $tabledir.$selector.'.tab';
  752:     }
  753:     return $tablefile;
  754: }
  755: #
  756: #   PushFile:  Called to do an administrative push of a file.
  757: #              - Ensure the file being pushed is one we support.
  758: #              - Backup the old file to <filename.saved>
  759: #              - Separate the contents of the new file out from the
  760: #                rest of the request.
  761: #              - Write the new file.
  762: #  Parameter:
  763: #     Request - The entire user request.  This consists of a : separated
  764: #               string pushfile:tablename:contents.
  765: #     NOTE:  The contents may have :'s in it as well making things a bit
  766: #            more interesting... but not much.
  767: #  Returns:
  768: #     String to send to client ("ok" or "refused" if bad file).
  769: #
  770: sub PushFile {
  771:     my $request = shift;
  772:     my ($command, $filename, $contents) = split(":", $request, 3);
  773:     &Debug("PushFile");
  774:     
  775:     #  At this point in time, pushes for only the following tables are
  776:     #  supported:
  777:     #   hosts.tab  ($filename eq host).
  778:     #   domain.tab ($filename eq domain).
  779:     #   dns_hosts.tab ($filename eq dns_host).
  780:     #   dns_domain.tab ($filename eq dns_domain). 
  781:     # Construct the destination filename or reject the request.
  782:     #
  783:     # lonManage is supposed to ensure this, however this session could be
  784:     # part of some elaborate spoof that managed somehow to authenticate.
  785:     #
  786: 
  787: 
  788:     my $tablefile = ConfigFileFromSelector($filename);
  789:     if(! (defined $tablefile)) {
  790: 	return "refused";
  791:     }
  792: 
  793:     #  If the file being pushed is the host file, we adjust the entry for ourself so that the
  794:     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
  795:     #  to conceive of conditions where we don't have a DNS entry locally.  This is possible in a 
  796:     #  network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
  797:     #  that possibilty.
  798: 
  799:     if($filename eq "host") {
  800: 	$contents = AdjustHostContents($contents);
  801:     } elsif ($filename eq 'dns_host' || $filename eq 'dns_domain') {
  802:         if ($contents eq '') {
  803:             &logthis('<font color="red"> Pushfile: unable to install '
  804:                     .$tablefile." - no data received from push. </font>");
  805:             return 'error: push had no data';
  806:         }
  807:         if (&Apache::lonnet::get_host_ip($clientname)) {
  808:             my $clienthost = &Apache::lonnet::hostname($clientname);
  809:             if ($managers{$clientip} eq $clientname) {
  810:                 my $clientprotocol = $Apache::lonnet::protocol{$clientname};
  811:                 $clientprotocol = 'http' if ($clientprotocol ne 'https');
  812:                 my $url = '/adm/'.$filename;
  813:                 $url =~ s{_}{/};
  814:                 my $request=new HTTP::Request('GET',"$clientprotocol://$clienthost$url");
  815:                 my $response = LONCAPA::LWPReq::makerequest($clientname,$request,'',\%perlvar,60,0);
  816:                 if ($response->is_error()) {
  817:                     &logthis('<font color="red"> Pushfile: unable to install '
  818:                             .$tablefile." - error attempting to pull data. </font>");
  819:                     return 'error: pull failed';
  820:                 } else {
  821:                     my $result = $response->content;
  822:                     chomp($result);
  823:                     unless ($result eq $contents) {
  824:                         &logthis('<font color="red"> Pushfile: unable to install '
  825:                                 .$tablefile." - pushed data and pulled data differ. </font>");
  826:                         my $pushleng = length($contents);
  827:                         my $pullleng = length($result);
  828:                         if ($pushleng != $pullleng) {
  829:                             return "error: $pushleng vs $pullleng bytes";
  830:                         } else {
  831:                             return "error: mismatch push and pull";
  832:                         }
  833:                     }
  834:                 }
  835:             }
  836:         }
  837:     }
  838: 
  839:     #  Install the new file:
  840: 
  841:     &logthis("Installing new $tablefile contents:\n$contents");
  842:     if(!InstallFile($tablefile, $contents)) {
  843: 	&logthis('<font color="red"> Pushfile: unable to install '
  844: 	 .$tablefile." $! </font>");
  845: 	return "error:$!";
  846:     } else {
  847: 	&logthis('<font color="green"> Installed new '.$tablefile
  848: 		 ." - transaction by: $clientname ($clientip)</font>");
  849:         my $adminmail = $perlvar{'lonAdmEMail'};
  850:         my $admindom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
  851:         if ($admindom ne '') {
  852:             my %domconfig =
  853:                 &Apache::lonnet::get_dom('configuration',['contacts'],$admindom);
  854:             if (ref($domconfig{'contacts'}) eq 'HASH') {
  855:                 if ($domconfig{'contacts'}{'adminemail'} ne '') {
  856:                     $adminmail = $domconfig{'contacts'}{'adminemail'};
  857:                 }
  858:             }
  859:         }
  860:         if ($adminmail =~ /^[^\@]+\@[^\@]+$/) {
  861:             my $msg = new Mail::Send;
  862:             $msg->to($adminmail);
  863:             $msg->subject('LON-CAPA DNS update on '.$perlvar{'lonHostID'});
  864:             $msg->add('Content-type','text/plain; charset=UTF-8');
  865:             if (my $fh = $msg->open()) {
  866:                 print $fh 'Update to '.$tablefile.' from Cluster Manager '.
  867:                           "$clientname ($clientip)\n";
  868:                 $fh->close;
  869:             }
  870:         }
  871:     }
  872: 
  873:     #  Indicate success:
  874:  
  875:     return "ok";
  876: 
  877: }
  878: 
  879: #
  880: #  Called to re-init either lonc or lond.
  881: #
  882: #  Parameters:
  883: #    request   - The full request by the client.  This is of the form
  884: #                reinit:<process>  
  885: #                where <process> is allowed to be either of 
  886: #                lonc or lond
  887: #
  888: #  Returns:
  889: #     The string to be sent back to the client either:
  890: #   ok         - Everything worked just fine.
  891: #   error:why  - There was a failure and why describes the reason.
  892: #
  893: #
  894: sub ReinitProcess {
  895:     my $request = shift;
  896: 
  897: 
  898:     # separate the request (reinit) from the process identifier and
  899:     # validate it producing the name of the .pid file for the process.
  900:     #
  901:     #
  902:     my ($junk, $process) = split(":", $request);
  903:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
  904:     if($process eq 'lonc') {
  905: 	$processpidfile = $processpidfile."lonc.pid";
  906: 	if (!open(PIDFILE, "< $processpidfile")) {
  907: 	    return "error:Open failed for $processpidfile";
  908: 	}
  909: 	my $loncpid = <PIDFILE>;
  910: 	close(PIDFILE);
  911: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
  912: 		."</font>");
  913: 	kill("USR2", $loncpid);
  914:     } elsif ($process eq 'lond') {
  915: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
  916: 	&UpdateHosts;			# Lond is us!!
  917:     } else {
  918: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
  919: 		 ."</font>");
  920: 	return "error:Invalid process identifier $process";
  921:     }
  922:     return 'ok';
  923: }
  924: #   Validate a line in a configuration file edit script:
  925: #   Validation includes:
  926: #     - Ensuring the command is valid.
  927: #     - Ensuring the command has sufficient parameters
  928: #   Parameters:
  929: #     scriptline - A line to validate (\n has been stripped for what it's worth).
  930: #
  931: #   Return:
  932: #      0     - Invalid scriptline.
  933: #      1     - Valid scriptline
  934: #  NOTE:
  935: #     Only the command syntax is checked, not the executability of the
  936: #     command.
  937: #
  938: sub isValidEditCommand {
  939:     my $scriptline = shift;
  940: 
  941:     #   Line elements are pipe separated:
  942: 
  943:     my ($command, $key, $newline)  = split(/\|/, $scriptline);
  944:     &logthis('<font color="green"> isValideditCommand checking: '.
  945: 	     "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
  946:     
  947:     if ($command eq "delete") {
  948: 	#
  949: 	#   key with no newline.
  950: 	#
  951: 	if( ($key eq "") || ($newline ne "")) {
  952: 	    return 0;		# Must have key but no newline.
  953: 	} else {
  954: 	    return 1;		# Valid syntax.
  955: 	}
  956:     } elsif ($command eq "replace") {
  957: 	#
  958: 	#   key and newline:
  959: 	#
  960: 	if (($key eq "") || ($newline eq "")) {
  961: 	    return 0;
  962: 	} else {
  963: 	    return 1;
  964: 	}
  965:     } elsif ($command eq "append") {
  966: 	if (($key ne "") && ($newline eq "")) {
  967: 	    return 1;
  968: 	} else {
  969: 	    return 0;
  970: 	}
  971:     } else {
  972: 	return 0;		# Invalid command.
  973:     }
  974:     return 0;			# Should not get here!!!
  975: }
  976: #
  977: #   ApplyEdit - Applies an edit command to a line in a configuration 
  978: #               file.  It is the caller's responsiblity to validate the
  979: #               edit line.
  980: #   Parameters:
  981: #      $directive - A single edit directive to apply.  
  982: #                   Edit directives are of the form:
  983: #                  append|newline      - Appends a new line to the file.
  984: #                  replace|key|newline - Replaces the line with key value 'key'
  985: #                  delete|key          - Deletes the line with key value 'key'.
  986: #      $editor   - A config file editor object that contains the
  987: #                  file being edited.
  988: #
  989: sub ApplyEdit {
  990: 
  991:     my ($directive, $editor) = @_;
  992: 
  993:     # Break the directive down into its command and its parameters
  994:     # (at most two at this point.  The meaning of the parameters, if in fact
  995:     #  they exist depends on the command).
  996: 
  997:     my ($command, $p1, $p2) = split(/\|/, $directive);
  998: 
  999:     if($command eq "append") {
 1000: 	$editor->Append($p1);	          # p1 - key p2 null.
 1001:     } elsif ($command eq "replace") {
 1002: 	$editor->ReplaceLine($p1, $p2);   # p1 - key p2 = newline.
 1003:     } elsif ($command eq "delete") {
 1004: 	$editor->DeleteLine($p1);         # p1 - key p2 null.
 1005:     } else {			          # Should not get here!!!
 1006: 	die "Invalid command given to ApplyEdit $command"
 1007:     }
 1008: }
 1009: #
 1010: # AdjustOurHost:
 1011: #           Adjusts a host file stored in a configuration file editor object
 1012: #           for the true IP address of this host. This is necessary for hosts
 1013: #           that live behind a firewall.
 1014: #           Those hosts have a publicly distributed IP of the firewall, but
 1015: #           internally must use their actual IP.  We assume that a given
 1016: #           host only has a single IP interface for now.
 1017: # Formal Parameters:
 1018: #     editor   - The configuration file editor to adjust.  This
 1019: #                editor is assumed to contain a hosts.tab file.
 1020: # Strategy:
 1021: #    - Figure out our hostname.
 1022: #    - Lookup the entry for this host.
 1023: #    - Modify the line to contain our IP
 1024: #    - Do a replace for this host.
 1025: sub AdjustOurHost {
 1026:     my $editor        = shift;
 1027: 
 1028:     # figure out who I am.
 1029: 
 1030:     my $myHostName    = $perlvar{'lonHostID'}; # LonCAPA hostname.
 1031: 
 1032:     #  Get my host file entry.
 1033: 
 1034:     my $ConfigLine    = $editor->Find($myHostName);
 1035:     if(! (defined $ConfigLine)) {
 1036: 	die "AdjustOurHost - no entry for me in hosts file $myHostName";
 1037:     }
 1038:     # figure out my IP:
 1039:     #   Use the config line to get my hostname.
 1040:     #   Use gethostbyname to translate that into an IP address.
 1041:     #
 1042:     my ($id,$domain,$role,$name,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
 1043:     #
 1044:     #  Reassemble the config line from the elements in the list.
 1045:     #  Note that if the loncnew items were not present before, they will
 1046:     #  be now even if they would be empty
 1047:     #
 1048:     my $newConfigLine = $id;
 1049:     foreach my $item ($domain, $role, $name, $maxcon, $idleto, $mincon) {
 1050: 	$newConfigLine .= ":".$item;
 1051:     }
 1052:     #  Replace the line:
 1053: 
 1054:     $editor->ReplaceLine($id, $newConfigLine);
 1055:     
 1056: }
 1057: #
 1058: #   ReplaceConfigFile:
 1059: #              Replaces a configuration file with the contents of a
 1060: #              configuration file editor object.
 1061: #              This is done by:
 1062: #              - Copying the target file to <filename>.old
 1063: #              - Writing the new file to <filename>.tmp
 1064: #              - Moving <filename.tmp>  -> <filename>
 1065: #              This laborious process ensures that the system is never without
 1066: #              a configuration file that's at least valid (even if the contents
 1067: #              may be dated).
 1068: #   Parameters:
 1069: #        filename   - Name of the file to modify... this is a full path.
 1070: #        editor     - Editor containing the file.
 1071: #
 1072: sub ReplaceConfigFile {
 1073:     
 1074:     my ($filename, $editor) = @_;
 1075: 
 1076:     CopyFile ($filename, $filename.".old");
 1077: 
 1078:     my $contents  = $editor->Get(); # Get the contents of the file.
 1079: 
 1080:     InstallFile($filename, $contents);
 1081: }
 1082: #   
 1083: #
 1084: #   Called to edit a configuration table  file
 1085: #   Parameters:
 1086: #      request           - The entire command/request sent by lonc or lonManage
 1087: #   Return:
 1088: #      The reply to send to the client.
 1089: #
 1090: sub EditFile {
 1091:     my $request = shift;
 1092: 
 1093:     #  Split the command into it's pieces:  edit:filetype:script
 1094: 
 1095:     my ($cmd, $filetype, $script) = split(/:/, $request,3);	# : in script
 1096: 
 1097:     #  Check the pre-coditions for success:
 1098: 
 1099:     if($cmd != "edit") {	# Something is amiss afoot alack.
 1100: 	return "error:edit request detected, but request != 'edit'\n";
 1101:     }
 1102:     if( ($filetype ne "hosts")  &&
 1103: 	($filetype ne "domain")) {
 1104: 	return "error:edit requested with invalid file specifier: $filetype \n";
 1105:     }
 1106: 
 1107:     #   Split the edit script and check it's validity.
 1108: 
 1109:     my @scriptlines = split(/\n/, $script);  # one line per element.
 1110:     my $linecount   = scalar(@scriptlines);
 1111:     for(my $i = 0; $i < $linecount; $i++) {
 1112: 	chomp($scriptlines[$i]);
 1113: 	if(!isValidEditCommand($scriptlines[$i])) {
 1114: 	    return "error:edit with bad script line: '$scriptlines[$i]' \n";
 1115: 	}
 1116:     }
 1117: 
 1118:     #   Execute the edit operation.
 1119:     #   - Create a config file editor for the appropriate file and 
 1120:     #   - execute each command in the script:
 1121:     #
 1122:     my $configfile = ConfigFileFromSelector($filetype);
 1123:     if (!(defined $configfile)) {
 1124: 	return "refused\n";
 1125:     }
 1126:     my $editor = ConfigFileEdit->new($configfile);
 1127: 
 1128:     for (my $i = 0; $i < $linecount; $i++) {
 1129: 	ApplyEdit($scriptlines[$i], $editor);
 1130:     }
 1131:     # If the file is the host file, ensure that our host is
 1132:     # adjusted to have our ip:
 1133:     #
 1134:     if($filetype eq "host") {
 1135: 	AdjustOurHost($editor);
 1136:     }
 1137:     #  Finally replace the current file with our file.
 1138:     #
 1139:     ReplaceConfigFile($configfile, $editor);
 1140: 
 1141:     return "ok\n";
 1142: }
 1143: 
 1144: #   read_profile
 1145: #
 1146: #   Returns a set of specific entries from a user's profile file.
 1147: #   this is a utility function that is used by both get_profile_entry and
 1148: #   get_profile_entry_encrypted.
 1149: #
 1150: # Parameters:
 1151: #    udom       - Domain in which the user exists.
 1152: #    uname      - User's account name (loncapa account)
 1153: #    namespace  - The profile namespace to open.
 1154: #    what       - A set of & separated queries.
 1155: # Returns:
 1156: #    If all ok: - The string that needs to be shipped back to the user.
 1157: #    If failure - A string that starts with error: followed by the failure
 1158: #                 reason.. note that this probabyl gets shipped back to the
 1159: #                 user as well.
 1160: #
 1161: sub read_profile {
 1162:     my ($udom, $uname, $namespace, $what) = @_;
 1163:     
 1164:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 1165: 				 &GDBM_READER());
 1166:     if ($hashref) {
 1167:         my @queries=split(/\&/,$what);
 1168:         if ($namespace eq 'roles') {
 1169:             @queries = map { &unescape($_); } @queries; 
 1170:         }
 1171:         my $qresult='';
 1172: 	
 1173: 	for (my $i=0;$i<=$#queries;$i++) {
 1174: 	    $qresult.="$hashref->{$queries[$i]}&";    # Presumably failure gives empty string.
 1175: 	}
 1176: 	$qresult=~s/\&$//;              # Remove trailing & from last lookup.
 1177: 	if (&untie_user_hash($hashref)) {
 1178: 	    return $qresult;
 1179: 	} else {
 1180: 	    return "error: ".($!+0)." untie (GDBM) Failed";
 1181: 	}
 1182:     } else {
 1183: 	if ($!+0 == 2) {
 1184: 	    return "error:No such file or GDBM reported bad block error";
 1185: 	} else {
 1186: 	    return "error: ".($!+0)." tie (GDBM) Failed";
 1187: 	}
 1188:     }
 1189: 
 1190: }
 1191: #--------------------- Request Handlers --------------------------------------------
 1192: #
 1193: #   By convention each request handler registers itself prior to the sub 
 1194: #   declaration:
 1195: #
 1196: 
 1197: #++
 1198: #
 1199: #  Handles ping requests.
 1200: #  Parameters:
 1201: #      $cmd    - the actual keyword that invoked us.
 1202: #      $tail   - the tail of the request that invoked us.
 1203: #      $replyfd- File descriptor connected to the client
 1204: #  Implicit Inputs:
 1205: #      $currenthostid - Global variable that carries the name of the host we are
 1206: #                       known as.
 1207: #  Returns:
 1208: #      1       - Ok to continue processing.
 1209: #      0       - Program should exit.
 1210: #  Side effects:
 1211: #      Reply information is sent to the client.
 1212: sub ping_handler {
 1213:     my ($cmd, $tail, $client) = @_;
 1214:     Debug("$cmd $tail $client .. $currenthostid:");
 1215:    
 1216:     Reply( $client,\$currenthostid,"$cmd:$tail");
 1217:    
 1218:     return 1;
 1219: }
 1220: &register_handler("ping", \&ping_handler, 0, 1, 1);       # Ping unencoded, client or manager.
 1221: 
 1222: #++
 1223: #
 1224: # Handles pong requests.  Pong replies with our current host id, and
 1225: #                         the results of a ping sent to us via our lonc.
 1226: #
 1227: # Parameters:
 1228: #      $cmd    - the actual keyword that invoked us.
 1229: #      $tail   - the tail of the request that invoked us.
 1230: #      $replyfd- File descriptor connected to the client
 1231: #  Implicit Inputs:
 1232: #      $currenthostid - Global variable that carries the name of the host we are
 1233: #                       connected to.
 1234: #  Returns:
 1235: #      1       - Ok to continue processing.
 1236: #      0       - Program should exit.
 1237: #  Side effects:
 1238: #      Reply information is sent to the client.
 1239: sub pong_handler {
 1240:     my ($cmd, $tail, $replyfd) = @_;
 1241: 
 1242:     my $reply=&Apache::lonnet::reply("ping",$clientname);
 1243:     &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail"); 
 1244:     return 1;
 1245: }
 1246: &register_handler("pong", \&pong_handler, 0, 1, 1);       # Pong unencoded, client or manager
 1247: 
 1248: #++
 1249: #      Called to establish an encrypted session key with the remote client.
 1250: #      Note that with secure lond, in most cases this function is never
 1251: #      invoked.  Instead, the secure session key is established either
 1252: #      via a local file that's locked down tight and only lives for a short
 1253: #      time, or via an ssl tunnel...and is generated from a bunch-o-random
 1254: #      bits from /dev/urandom, rather than the predictable pattern used by
 1255: #      by this sub.  This sub is only used in the old-style insecure
 1256: #      key negotiation.
 1257: # Parameters:
 1258: #      $cmd    - the actual keyword that invoked us.
 1259: #      $tail   - the tail of the request that invoked us.
 1260: #      $replyfd- File descriptor connected to the client
 1261: #  Implicit Inputs:
 1262: #      $currenthostid - Global variable that carries the name of the host
 1263: #                       known as.
 1264: #      $clientname    - Global variable that carries the name of the host we're connected to.
 1265: #  Returns:
 1266: #      1       - Ok to continue processing.
 1267: #      0       - Program should exit.
 1268: #  Implicit Outputs:
 1269: #      Reply information is sent to the client.
 1270: #      $cipher is set with a reference to a new IDEA encryption object.
 1271: #
 1272: sub establish_key_handler {
 1273:     my ($cmd, $tail, $replyfd) = @_;
 1274: 
 1275:     my $buildkey=time.$$.int(rand 100000);
 1276:     $buildkey=~tr/1-6/A-F/;
 1277:     $buildkey=int(rand 100000).$buildkey.int(rand 100000);
 1278:     my $key=$currenthostid.$clientname;
 1279:     $key=~tr/a-z/A-Z/;
 1280:     $key=~tr/G-P/0-9/;
 1281:     $key=~tr/Q-Z/0-9/;
 1282:     $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
 1283:     $key=substr($key,0,32);
 1284:     my $cipherkey=pack("H32",$key);
 1285:     $cipher=new IDEA $cipherkey;
 1286:     &Reply($replyfd, \$buildkey, "$cmd:$tail"); 
 1287:    
 1288:     return 1;
 1289: 
 1290: }
 1291: &register_handler("ekey", \&establish_key_handler, 0, 1,1);
 1292: 
 1293: #     Handler for the load command.  Returns the current system load average
 1294: #     to the requestor.
 1295: #
 1296: # Parameters:
 1297: #      $cmd    - the actual keyword that invoked us.
 1298: #      $tail   - the tail of the request that invoked us.
 1299: #      $replyfd- File descriptor connected to the client
 1300: #  Implicit Inputs:
 1301: #      $currenthostid - Global variable that carries the name of the host
 1302: #                       known as.
 1303: #      $clientname    - Global variable that carries the name of the host we're connected to.
 1304: #  Returns:
 1305: #      1       - Ok to continue processing.
 1306: #      0       - Program should exit.
 1307: #  Side effects:
 1308: #      Reply information is sent to the client.
 1309: sub load_handler {
 1310:     my ($cmd, $tail, $replyfd) = @_;
 1311: 
 1312: 
 1313: 
 1314:    # Get the load average from /proc/loadavg and calculate it as a percentage of
 1315:    # the allowed load limit as set by the perl global variable lonLoadLim
 1316: 
 1317:     my $loadavg;
 1318:     my $loadfile=IO::File->new('/proc/loadavg');
 1319:    
 1320:     $loadavg=<$loadfile>;
 1321:     $loadavg =~ s/\s.*//g;                      # Extract the first field only.
 1322:    
 1323:     my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
 1324: 
 1325:     &Reply( $replyfd, \$loadpercent, "$cmd:$tail");
 1326:    
 1327:     return 1;
 1328: }
 1329: &register_handler("load", \&load_handler, 0, 1, 0);
 1330: 
 1331: #
 1332: #   Process the userload request.  This sub returns to the client the current
 1333: #  user load average.  It can be invoked either by clients or managers.
 1334: #
 1335: # Parameters:
 1336: #      $cmd    - the actual keyword that invoked us.
 1337: #      $tail   - the tail of the request that invoked us.
 1338: #      $replyfd- File descriptor connected to the client
 1339: #  Implicit Inputs:
 1340: #      $currenthostid - Global variable that carries the name of the host
 1341: #                       known as.
 1342: #      $clientname    - Global variable that carries the name of the host we're connected to.
 1343: #  Returns:
 1344: #      1       - Ok to continue processing.
 1345: #      0       - Program should exit
 1346: # Implicit inputs:
 1347: #     whatever the userload() function requires.
 1348: #  Implicit outputs:
 1349: #     the reply is written to the client.
 1350: #
 1351: sub user_load_handler {
 1352:     my ($cmd, $tail, $replyfd) = @_;
 1353: 
 1354:     my $userloadpercent=&Apache::lonnet::userload();
 1355:     &Reply($replyfd, \$userloadpercent, "$cmd:$tail");
 1356:     
 1357:     return 1;
 1358: }
 1359: &register_handler("userload", \&user_load_handler, 0, 1, 0);
 1360: 
 1361: #   Process a request for the authorization type of a user:
 1362: #   (userauth).
 1363: #
 1364: # Parameters:
 1365: #      $cmd    - the actual keyword that invoked us.
 1366: #      $tail   - the tail of the request that invoked us.
 1367: #      $replyfd- File descriptor connected to the client
 1368: #  Returns:
 1369: #      1       - Ok to continue processing.
 1370: #      0       - Program should exit
 1371: # Implicit outputs:
 1372: #    The user authorization type is written to the client.
 1373: #
 1374: sub user_authorization_type {
 1375:     my ($cmd, $tail, $replyfd) = @_;
 1376:    
 1377:     my $userinput = "$cmd:$tail";
 1378:    
 1379:     #  Pull the domain and username out of the command tail.
 1380:     # and call get_auth_type to determine the authentication type.
 1381:    
 1382:     my ($udom,$uname)=split(/:/,$tail);
 1383:     my $result = &get_auth_type($udom, $uname);
 1384:     if($result eq "nouser") {
 1385: 	&Failure( $replyfd, "unknown_user\n", $userinput);
 1386:     } else {
 1387: 	#
 1388: 	# We only want to pass the second field from get_auth_type
 1389: 	# for ^krb.. otherwise we'll be handing out the encrypted
 1390: 	# password for internals e.g.
 1391: 	#
 1392: 	my ($type,$otherinfo) = split(/:/,$result);
 1393: 	if($type =~ /^krb/) {
 1394: 	    $type = $result;
 1395: 	} else {
 1396:             $type .= ':';
 1397:         }
 1398: 	&Reply( $replyfd, \$type, $userinput);
 1399:     }
 1400:   
 1401:     return 1;
 1402: }
 1403: &register_handler("currentauth", \&user_authorization_type, 1, 1, 0);
 1404: 
 1405: #   Process a request by a manager to push a hosts or domain table 
 1406: #   to us.  We pick apart the command and pass it on to the subs
 1407: #   that already exist to do this.
 1408: #
 1409: # Parameters:
 1410: #      $cmd    - the actual keyword that invoked us.
 1411: #      $tail   - the tail of the request that invoked us.
 1412: #      $client - File descriptor connected to the client
 1413: #  Returns:
 1414: #      1       - Ok to continue processing.
 1415: #      0       - Program should exit
 1416: # Implicit Output:
 1417: #    a reply is written to the client.
 1418: sub push_file_handler {
 1419:     my ($cmd, $tail, $client) = @_;
 1420:     &Debug("In push file handler");
 1421:     my $userinput = "$cmd:$tail";
 1422: 
 1423:     # At this time we only know that the IP of our partner is a valid manager
 1424:     # the code below is a hook to do further authentication (e.g. to resolve
 1425:     # spoofing).
 1426: 
 1427:     my $cert = &GetCertificate($userinput);
 1428:     if(&ValidManager($cert)) {
 1429: 	&Debug("Valid manager: $client");
 1430: 
 1431: 	# Now presumably we have the bona fides of both the peer host and the
 1432: 	# process making the request.
 1433:       
 1434: 	my $reply = &PushFile($userinput);
 1435: 	&Reply($client, \$reply, $userinput);
 1436: 
 1437:     } else {
 1438: 	&logthis("push_file_handler $client is not valid");
 1439: 	&Failure( $client, "refused\n", $userinput);
 1440:     } 
 1441:     return 1;
 1442: }
 1443: &register_handler("pushfile", \&push_file_handler, 1, 0, 1);
 1444: 
 1445: # The du_handler routine should be considered obsolete and is retained
 1446: # for communication with legacy servers.  Please see the du2_handler.
 1447: #
 1448: #   du  - list the disk usage of a directory recursively. 
 1449: #    
 1450: #   note: stolen code from the ls file handler
 1451: #   under construction by Rick Banghart 
 1452: #    .
 1453: # Parameters:
 1454: #    $cmd        - The command that dispatched us (du).
 1455: #    $ududir     - The directory path to list... I'm not sure what this
 1456: #                  is relative as things like ls:. return e.g.
 1457: #                  no_such_dir.
 1458: #    $client     - Socket open on the client.
 1459: # Returns:
 1460: #     1 - indicating that the daemon should not disconnect.
 1461: # Side Effects:
 1462: #   The reply is written to  $client.
 1463: #
 1464: sub du_handler {
 1465:     my ($cmd, $ududir, $client) = @_;
 1466:     ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
 1467:     my $userinput = "$cmd:$ududir";
 1468: 
 1469:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
 1470: 	&Failure($client,"refused\n","$cmd:$ududir");
 1471: 	return 1;
 1472:     }
 1473:     #  Since $ududir could have some nasties in it,
 1474:     #  we will require that ududir is a valid
 1475:     #  directory.  Just in case someone tries to
 1476:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
 1477:     #  etc.
 1478:     #
 1479:     if (-d $ududir) {
 1480: 	my $total_size=0;
 1481: 	my $code=sub { 
 1482: 	    if ($_=~/\.\d+\./) { return;} 
 1483: 	    if ($_=~/\.meta$/) { return;}
 1484: 	    if (-d $_)         { return;}
 1485: 	    $total_size+=(stat($_))[7];
 1486: 	};
 1487: 	chdir($ududir);
 1488: 	find($code,$ududir);
 1489: 	$total_size=int($total_size/1024);
 1490: 	&Reply($client,\$total_size,"$cmd:$ududir");
 1491:     } else {
 1492: 	&Failure($client, "bad_directory:$ududir\n","$cmd:$ududir"); 
 1493:     }
 1494:     return 1;
 1495: }
 1496: &register_handler("du", \&du_handler, 0, 1, 0);
 1497: 
 1498: # Please also see the du_handler, which is obsoleted by du2. 
 1499: # du2_handler differs from du_handler in that required path to directory
 1500: # provided by &propath() is prepended in the handler instead of on the 
 1501: # client side.
 1502: #
 1503: #   du2  - list the disk usage of a directory recursively.
 1504: #
 1505: # Parameters:
 1506: #    $cmd        - The command that dispatched us (du).
 1507: #    $tail       - The tail of the request that invoked us.
 1508: #                  $tail is a : separated list of the following:
 1509: #                   - $ududir - directory path to list (before prepending)
 1510: #                   - $getpropath = 1 if &propath() should prepend
 1511: #                   - $uname - username to use for &propath or user dir
 1512: #                   - $udom - domain to use for &propath or user dir
 1513: #                   All are escaped.
 1514: #    $client     - Socket open on the client.
 1515: # Returns:
 1516: #     1 - indicating that the daemon should not disconnect.
 1517: # Side Effects:
 1518: #   The reply is written to $client.
 1519: #
 1520: 
 1521: sub du2_handler {
 1522:     my ($cmd, $tail, $client) = @_;
 1523:     my ($ududir,$getpropath,$uname,$udom) = map { &unescape($_) } (split(/:/, $tail));
 1524:     my $userinput = "$cmd:$tail";
 1525:     if (($ududir=~/\.\./) || (($ududir!~m|^/home/httpd/|) && (!$getpropath))) {
 1526:         &Failure($client,"refused\n","$cmd:$tail");
 1527:         return 1;
 1528:     }
 1529:     if ($getpropath) {
 1530:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
 1531:             $ududir = &propath($udom,$uname).'/'.$ududir;
 1532:         } else {
 1533:             &Failure($client,"refused\n","$cmd:$tail");
 1534:             return 1;
 1535:         }
 1536:     }
 1537:     #  Since $ududir could have some nasties in it,
 1538:     #  we will require that ududir is a valid
 1539:     #  directory.  Just in case someone tries to
 1540:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
 1541:     #  etc.
 1542:     #
 1543:     if (-d $ududir) {
 1544:         my $total_size=0;
 1545:         my $code=sub {
 1546:             if ($_=~/\.\d+\./) { return;}
 1547:             if ($_=~/\.meta$/) { return;}
 1548:             if (-d $_)         { return;}
 1549:             $total_size+=(stat($_))[7];
 1550:         };
 1551:         chdir($ududir);
 1552:         find($code,$ududir);
 1553:         $total_size=int($total_size/1024);
 1554:         &Reply($client,\$total_size,"$cmd:$ududir");
 1555:     } else {
 1556:         &Failure($client, "bad_directory:$ududir\n","$cmd:$tail");
 1557:     }
 1558:     return 1;
 1559: }
 1560: &register_handler("du2", \&du2_handler, 0, 1, 0);
 1561: 
 1562: #
 1563: # The ls_handler routine should be considered obsolete and is retained
 1564: # for communication with legacy servers.  Please see the ls3_handler.
 1565: #
 1566: #   ls  - list the contents of a directory.  For each file in the
 1567: #    selected directory the filename followed by the full output of
 1568: #    the stat function is returned.  The returned info for each
 1569: #    file are separated by ':'.  The stat fields are separated by &'s.
 1570: # Parameters:
 1571: #    $cmd        - The command that dispatched us (ls).
 1572: #    $ulsdir     - The directory path to list... I'm not sure what this
 1573: #                  is relative as things like ls:. return e.g.
 1574: #                  no_such_dir.
 1575: #    $client     - Socket open on the client.
 1576: # Returns:
 1577: #     1 - indicating that the daemon should not disconnect.
 1578: # Side Effects:
 1579: #   The reply is written to  $client.
 1580: #
 1581: sub ls_handler {
 1582:     # obsoleted by ls2_handler
 1583:     my ($cmd, $ulsdir, $client) = @_;
 1584: 
 1585:     my $userinput = "$cmd:$ulsdir";
 1586: 
 1587:     my $obs;
 1588:     my $rights;
 1589:     my $ulsout='';
 1590:     my $ulsfn;
 1591:     if (-e $ulsdir) {
 1592: 	if(-d $ulsdir) {
 1593: 	    if (opendir(LSDIR,$ulsdir)) {
 1594: 		while ($ulsfn=readdir(LSDIR)) {
 1595: 		    undef($obs);
 1596: 		    undef($rights); 
 1597: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1598: 		    #We do some obsolete checking here
 1599: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
 1600: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
 1601: 			my @obsolete=<FILE>;
 1602: 			foreach my $obsolete (@obsolete) {
 1603: 			    if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
 1604: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
 1605: 			}
 1606: 		    }
 1607: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
 1608: 		    if($obs eq '1') { $ulsout.="&1"; }
 1609: 		    else { $ulsout.="&0"; }
 1610: 		    if($rights eq '1') { $ulsout.="&1:"; }
 1611: 		    else { $ulsout.="&0:"; }
 1612: 		}
 1613: 		closedir(LSDIR);
 1614: 	    }
 1615: 	} else {
 1616: 	    my @ulsstats=stat($ulsdir);
 1617: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1618: 	}
 1619:     } else {
 1620: 	$ulsout='no_such_dir';
 1621:     }
 1622:     if ($ulsout eq '') { $ulsout='empty'; }
 1623:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
 1624:     
 1625:     return 1;
 1626: 
 1627: }
 1628: &register_handler("ls", \&ls_handler, 0, 1, 0);
 1629: 
 1630: # The ls2_handler routine should be considered obsolete and is retained
 1631: # for communication with legacy servers.  Please see the ls3_handler.
 1632: # Please also see the ls_handler, which was itself obsoleted by ls2.
 1633: # ls2_handler differs from ls_handler in that it escapes its return 
 1634: # values before concatenating them together with ':'s.
 1635: #
 1636: #   ls2  - list the contents of a directory.  For each file in the
 1637: #    selected directory the filename followed by the full output of
 1638: #    the stat function is returned.  The returned info for each
 1639: #    file are separated by ':'.  The stat fields are separated by &'s.
 1640: # Parameters:
 1641: #    $cmd        - The command that dispatched us (ls).
 1642: #    $ulsdir     - The directory path to list... I'm not sure what this
 1643: #                  is relative as things like ls:. return e.g.
 1644: #                  no_such_dir.
 1645: #    $client     - Socket open on the client.
 1646: # Returns:
 1647: #     1 - indicating that the daemon should not disconnect.
 1648: # Side Effects:
 1649: #   The reply is written to  $client.
 1650: #
 1651: sub ls2_handler {
 1652:     my ($cmd, $ulsdir, $client) = @_;
 1653: 
 1654:     my $userinput = "$cmd:$ulsdir";
 1655: 
 1656:     my $obs;
 1657:     my $rights;
 1658:     my $ulsout='';
 1659:     my $ulsfn;
 1660:     if (-e $ulsdir) {
 1661:         if(-d $ulsdir) {
 1662:             if (opendir(LSDIR,$ulsdir)) {
 1663:                 while ($ulsfn=readdir(LSDIR)) {
 1664:                     undef($obs);
 1665: 		    undef($rights); 
 1666:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1667:                     #We do some obsolete checking here
 1668:                     if(-e $ulsdir.'/'.$ulsfn.".meta") { 
 1669:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
 1670:                         my @obsolete=<FILE>;
 1671:                         foreach my $obsolete (@obsolete) {
 1672:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
 1673:                             if($obsolete =~ m|(<copyright>)(default)|) {
 1674:                                 $rights = 1;
 1675:                             }
 1676:                         }
 1677:                     }
 1678:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
 1679:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1680:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1681:                     $ulsout.= &escape($tmp).':';
 1682:                 }
 1683:                 closedir(LSDIR);
 1684:             }
 1685:         } else {
 1686:             my @ulsstats=stat($ulsdir);
 1687:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1688:         }
 1689:     } else {
 1690:         $ulsout='no_such_dir';
 1691:    }
 1692:    if ($ulsout eq '') { $ulsout='empty'; }
 1693:    &Reply($client, \$ulsout, $userinput); # This supports debug logging.
 1694:    return 1;
 1695: }
 1696: &register_handler("ls2", \&ls2_handler, 0, 1, 0);
 1697: #
 1698: #   ls3  - list the contents of a directory.  For each file in the
 1699: #    selected directory the filename followed by the full output of
 1700: #    the stat function is returned.  The returned info for each
 1701: #    file are separated by ':'.  The stat fields are separated by &'s.
 1702: # Parameters:
 1703: #    $cmd        - The command that dispatched us (ls).
 1704: #    $tail       - The tail of the request that invoked us.
 1705: #                  $tail is a : separated list of the following:
 1706: #                   - $ulsdir - directory path to list (before prepending)
 1707: #                   - $getpropath = 1 if &propath() should prepend
 1708: #                   - $getuserdir = 1 if path to user dir in lonUsers should
 1709: #                                     prepend
 1710: #                   - $alternate_root - path to prepend
 1711: #                   - $uname - username to use for &propath or user dir
 1712: #                   - $udom - domain to use for &propath or user dir
 1713: #            All of these except $getpropath and &getuserdir are escaped.    
 1714: #                  no_such_dir.
 1715: #    $client     - Socket open on the client.
 1716: # Returns:
 1717: #     1 - indicating that the daemon should not disconnect.
 1718: # Side Effects:
 1719: #   The reply is written to $client.
 1720: #
 1721: 
 1722: sub ls3_handler {
 1723:     my ($cmd, $tail, $client) = @_;
 1724:     my $userinput = "$cmd:$tail";
 1725:     my ($ulsdir,$getpropath,$getuserdir,$alternate_root,$uname,$udom) =
 1726:         split(/:/,$tail);
 1727:     if (defined($ulsdir)) {
 1728:         $ulsdir = &unescape($ulsdir);
 1729:     }
 1730:     if (defined($alternate_root)) {
 1731:         $alternate_root = &unescape($alternate_root);
 1732:     }
 1733:     if (defined($uname)) {
 1734:         $uname = &unescape($uname);
 1735:     }
 1736:     if (defined($udom)) {
 1737:         $udom = &unescape($udom);
 1738:     }
 1739: 
 1740:     my $dir_root = $perlvar{'lonDocRoot'};
 1741:     if ($getpropath) {
 1742:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
 1743:             $dir_root = &propath($udom,$uname);
 1744:             $dir_root =~ s/\/$//;
 1745:         } else {
 1746:             &Failure($client,"refused\n","$cmd:$tail");
 1747:             return 1;
 1748:         }
 1749:     } elsif ($getuserdir) {
 1750:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
 1751:             my $subdir=$uname.'__';
 1752:             $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 1753:             $dir_root = $Apache::lonnet::perlvar{'lonUsersDir'}
 1754:                        ."/$udom/$subdir/$uname";
 1755:         } else {
 1756:             &Failure($client,"refused\n","$cmd:$tail");
 1757:             return 1;
 1758:         }
 1759:     } elsif ($alternate_root ne '') {
 1760:         $dir_root = $alternate_root;
 1761:     }
 1762:     if (($dir_root ne '') && ($dir_root ne '/')) {
 1763:         if ($ulsdir =~ /^\//) {
 1764:             $ulsdir = $dir_root.$ulsdir;
 1765:         } else {
 1766:             $ulsdir = $dir_root.'/'.$ulsdir;
 1767:         }
 1768:     }
 1769:     my $obs;
 1770:     my $rights;
 1771:     my $ulsout='';
 1772:     my $ulsfn;
 1773:     if (-e $ulsdir) {
 1774:         if(-d $ulsdir) {
 1775:             if (opendir(LSDIR,$ulsdir)) {
 1776:                 while ($ulsfn=readdir(LSDIR)) {
 1777:                     undef($obs);
 1778:                     undef($rights);
 1779:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1780:                     #We do some obsolete checking here
 1781:                     if(-e $ulsdir.'/'.$ulsfn.".meta") {
 1782:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
 1783:                         my @obsolete=<FILE>;
 1784:                         foreach my $obsolete (@obsolete) {
 1785:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
 1786:                             if($obsolete =~ m|(<copyright>)(default)|) {
 1787:                                 $rights = 1;
 1788:                             }
 1789:                         }
 1790:                     }
 1791:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
 1792:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1793:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1794:                     $ulsout.= &escape($tmp).':';
 1795:                 }
 1796:                 closedir(LSDIR);
 1797:             }
 1798:         } else {
 1799:             my @ulsstats=stat($ulsdir);
 1800:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1801:         }
 1802:     } else {
 1803:         $ulsout='no_such_dir';
 1804:     }
 1805:     if ($ulsout eq '') { $ulsout='empty'; }
 1806:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
 1807:     return 1;
 1808: }
 1809: &register_handler("ls3", \&ls3_handler, 0, 1, 0);
 1810: 
 1811: sub read_lonnet_global {
 1812:     my ($cmd,$tail,$client) = @_;
 1813:     my $userinput = "$cmd:$tail";
 1814:     my $requested = &Apache::lonnet::thaw_unescape($tail);
 1815:     my $result;
 1816:     my %packagevars = (
 1817:                         spareid => \%Apache::lonnet::spareid,
 1818:                         perlvar => \%Apache::lonnet::perlvar,
 1819:                       );
 1820:     my %limit_to = (
 1821:                     perlvar => {
 1822:                                  lonOtherAuthen => 1,
 1823:                                  lonBalancer    => 1,
 1824:                                  lonVersion     => 1,
 1825:                                  lonSysEMail    => 1,
 1826:                                  lonHostID      => 1,
 1827:                                  lonRole        => 1,
 1828:                                  lonDefDomain   => 1,
 1829:                                  lonLoadLim     => 1,
 1830:                                  lonUserLoadLim => 1,
 1831:                                }
 1832:                   );
 1833:     if (ref($requested) eq 'HASH') {
 1834:         foreach my $what (keys(%{$requested})) {
 1835:             my $response;
 1836:             my $items = {};
 1837:             if (exists($packagevars{$what})) {
 1838:                 if (ref($limit_to{$what}) eq 'HASH') {
 1839:                     foreach my $varname (keys(%{$packagevars{$what}})) {
 1840:                         if ($limit_to{$what}{$varname}) {
 1841:                             $items->{$varname} = $packagevars{$what}{$varname};
 1842:                         }
 1843:                     }
 1844:                 } else {
 1845:                     $items = $packagevars{$what};
 1846:                 }
 1847:                 if ($what eq 'perlvar') {
 1848:                     if (!exists($packagevars{$what}{'lonBalancer'})) {
 1849:                         if ($dist =~ /^(centos|rhes|fedora|scientific)/) {
 1850:                             my $othervarref=LONCAPA::Configuration::read_conf('httpd.conf');
 1851:                             if (ref($othervarref) eq 'HASH') {
 1852:                                 $items->{'lonBalancer'} = $othervarref->{'lonBalancer'};
 1853:                             }
 1854:                         }
 1855:                     }
 1856:                 }
 1857:                 $response = &Apache::lonnet::freeze_escape($items);
 1858:             }
 1859:             $result .= &escape($what).'='.$response.'&';
 1860:         }
 1861:     }
 1862:     $result =~ s/\&$//;
 1863:     &Reply($client,\$result,$userinput);
 1864:     return 1;
 1865: }
 1866: &register_handler("readlonnetglobal", \&read_lonnet_global, 0, 1, 0);
 1867: 
 1868: sub server_devalidatecache_handler {
 1869:     my ($cmd,$tail,$client) = @_;
 1870:     my $userinput = "$cmd:$tail";
 1871:     my $items = &unescape($tail);
 1872:     my @cached = split(/\&/,$items);
 1873:     foreach my $key (@cached) {
 1874:         if ($key =~ /:/) {
 1875:             my ($name,$id) = map { &unescape($_); } split(/:/,$key);
 1876:             &Apache::lonnet::devalidate_cache_new($name,$id);
 1877:         }
 1878:     }
 1879:     my $result = 'ok';
 1880:     &Reply($client,\$result,$userinput);
 1881:     return 1;
 1882: }
 1883: &register_handler("devalidatecache", \&server_devalidatecache_handler, 0, 1, 0);
 1884: 
 1885: sub server_timezone_handler {
 1886:     my ($cmd,$tail,$client) = @_;
 1887:     my $userinput = "$cmd:$tail";
 1888:     my $timezone;
 1889:     my $clockfile = '/etc/sysconfig/clock'; # Fedora/CentOS/SuSE
 1890:     my $tzfile = '/etc/timezone'; # Debian/Ubuntu
 1891:     if (-e $clockfile) {
 1892:         if (open(my $fh,"<$clockfile")) {
 1893:             while (<$fh>) {
 1894:                 next if (/^[\#\s]/);
 1895:                 if (/^(?:TIME)?ZONE\s*=\s*['"]?\s*([\w\/]+)/) {
 1896:                     $timezone = $1;
 1897:                     last;
 1898:                 }
 1899:             }
 1900:             close($fh);
 1901:         }
 1902:     } elsif (-e $tzfile) {
 1903:         if (open(my $fh,"<$tzfile")) {
 1904:             $timezone = <$fh>;
 1905:             close($fh);
 1906:             chomp($timezone);
 1907:             if ($timezone =~ m{^Etc/(\w+)$}) {
 1908:                 $timezone = $1;
 1909:             }
 1910:         }
 1911:     }
 1912:     &Reply($client,\$timezone,$userinput); # This supports debug logging.
 1913:     return 1;
 1914: }
 1915: &register_handler("servertimezone", \&server_timezone_handler, 0, 1, 0);
 1916: 
 1917: sub server_loncaparev_handler {
 1918:     my ($cmd,$tail,$client) = @_;
 1919:     my $userinput = "$cmd:$tail";
 1920:     &Reply($client,\$perlvar{'lonVersion'},$userinput);
 1921:     return 1;
 1922: }
 1923: &register_handler("serverloncaparev", \&server_loncaparev_handler, 0, 1, 0);
 1924: 
 1925: sub server_homeID_handler {
 1926:     my ($cmd,$tail,$client) = @_;
 1927:     my $userinput = "$cmd:$tail";
 1928:     &Reply($client,\$perlvar{'lonHostID'},$userinput);
 1929:     return 1;
 1930: }
 1931: &register_handler("serverhomeID", \&server_homeID_handler, 0, 1, 0);
 1932: 
 1933: sub server_distarch_handler {
 1934:     my ($cmd,$tail,$client) = @_;
 1935:     my $userinput = "$cmd:$tail";
 1936:     my $reply = &distro_and_arch();
 1937:     &Reply($client,\$reply,$userinput);
 1938:     return 1;
 1939: }
 1940: &register_handler("serverdistarch", \&server_distarch_handler, 0, 1, 0);
 1941: 
 1942: sub server_certs_handler {
 1943:     my ($cmd,$tail,$client) = @_;
 1944:     my $userinput = "$cmd:$tail";
 1945:     my $result;
 1946:     my $result = &LONCAPA::Lond::server_certs(\%perlvar);
 1947:     &Reply($client,\$result,$userinput);
 1948:     return;
 1949: }
 1950: &register_handler("servercerts", \&server_certs_handler, 0, 1, 0);
 1951: 
 1952: #   Process a reinit request.  Reinit requests that either
 1953: #   lonc or lond be reinitialized so that an updated 
 1954: #   host.tab or domain.tab can be processed.
 1955: #
 1956: # Parameters:
 1957: #      $cmd    - the actual keyword that invoked us.
 1958: #      $tail   - the tail of the request that invoked us.
 1959: #      $client - File descriptor connected to the client
 1960: #  Returns:
 1961: #      1       - Ok to continue processing.
 1962: #      0       - Program should exit
 1963: #  Implicit output:
 1964: #     a reply is sent to the client.
 1965: #
 1966: sub reinit_process_handler {
 1967:     my ($cmd, $tail, $client) = @_;
 1968:    
 1969:     my $userinput = "$cmd:$tail";
 1970:    
 1971:     my $cert = &GetCertificate($userinput);
 1972:     if(&ValidManager($cert)) {
 1973: 	chomp($userinput);
 1974: 	my $reply = &ReinitProcess($userinput);
 1975: 	&Reply( $client,  \$reply, $userinput);
 1976:     } else {
 1977: 	&Failure( $client, "refused\n", $userinput);
 1978:     }
 1979:     return 1;
 1980: }
 1981: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
 1982: 
 1983: #  Process the editing script for a table edit operation.
 1984: #  the editing operation must be encrypted and requested by
 1985: #  a manager host.
 1986: #
 1987: # Parameters:
 1988: #      $cmd    - the actual keyword that invoked us.
 1989: #      $tail   - the tail of the request that invoked us.
 1990: #      $client - File descriptor connected to the client
 1991: #  Returns:
 1992: #      1       - Ok to continue processing.
 1993: #      0       - Program should exit
 1994: #  Implicit output:
 1995: #     a reply is sent to the client.
 1996: #
 1997: sub edit_table_handler {
 1998:     my ($command, $tail, $client) = @_;
 1999:    
 2000:     my $userinput = "$command:$tail";
 2001: 
 2002:     my $cert = &GetCertificate($userinput);
 2003:     if(&ValidManager($cert)) {
 2004: 	my($filetype, $script) = split(/:/, $tail);
 2005: 	if (($filetype eq "hosts") || 
 2006: 	    ($filetype eq "domain")) {
 2007: 	    if($script ne "") {
 2008: 		&Reply($client,              # BUGBUG - EditFile
 2009: 		      &EditFile($userinput), #   could fail.
 2010: 		      $userinput);
 2011: 	    } else {
 2012: 		&Failure($client,"refused\n",$userinput);
 2013: 	    }
 2014: 	} else {
 2015: 	    &Failure($client,"refused\n",$userinput);
 2016: 	}
 2017:     } else {
 2018: 	&Failure($client,"refused\n",$userinput);
 2019:     }
 2020:     return 1;
 2021: }
 2022: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
 2023: 
 2024: #
 2025: #   Authenticate a user against the LonCAPA authentication
 2026: #   database.  Note that there are several authentication
 2027: #   possibilities:
 2028: #   - unix     - The user can be authenticated against the unix
 2029: #                password file.
 2030: #   - internal - The user can be authenticated against a purely 
 2031: #                internal per user password file.
 2032: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
 2033: #                ticket granting authority.
 2034: #   - user     - The person tailoring LonCAPA can supply a user authentication
 2035: #                mechanism that is per system.
 2036: #
 2037: # Parameters:
 2038: #    $cmd      - The command that got us here.
 2039: #    $tail     - Tail of the command (remaining parameters).
 2040: #    $client   - File descriptor connected to client.
 2041: # Returns
 2042: #     0        - Requested to exit, caller should shut down.
 2043: #     1        - Continue processing.
 2044: # Implicit inputs:
 2045: #    The authentication systems describe above have their own forms of implicit
 2046: #    input into the authentication process that are described above.
 2047: #
 2048: sub authenticate_handler {
 2049:     my ($cmd, $tail, $client) = @_;
 2050: 
 2051:     
 2052:     #  Regenerate the full input line 
 2053:     
 2054:     my $userinput  = $cmd.":".$tail;
 2055:     
 2056:     #  udom    - User's domain.
 2057:     #  uname   - Username.
 2058:     #  upass   - User's password.
 2059:     #  checkdefauth - Pass to validate_user() to try authentication
 2060:     #                 with default auth type(s) if no user account.
 2061:     #  clientcancheckhost - Passed by clients with functionality in lonauth.pm
 2062:     #                       to check if session can be hosted.
 2063:     
 2064:     my ($udom, $uname, $upass, $checkdefauth, $clientcancheckhost)=split(/:/,$tail);
 2065:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass,  checkdefauth = $checkdefauth");
 2066:     chomp($upass);
 2067:     $upass=&unescape($upass);
 2068: 
 2069:     my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
 2070:     if($pwdcorrect) {
 2071:         my $canhost = 1;
 2072:         unless ($clientcancheckhost) {
 2073:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 2074:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 2075:             my @intdoms;
 2076:             my $internet_names = &Apache::lonnet::get_internet_names($clientname);
 2077:             if (ref($internet_names) eq 'ARRAY') {
 2078:                 @intdoms = @{$internet_names};
 2079:             }
 2080:             unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
 2081:                 my ($remote,$hosted);
 2082:                 my $remotesession = &get_usersession_config($udom,'remotesession');
 2083:                 if (ref($remotesession) eq 'HASH') {
 2084:                     $remote = $remotesession->{'remote'};
 2085:                 }
 2086:                 my $hostedsession = &get_usersession_config($clienthomedom,'hostedsession');
 2087:                 if (ref($hostedsession) eq 'HASH') {
 2088:                     $hosted = $hostedsession->{'hosted'};
 2089:                 }
 2090:                 $canhost = &Apache::lonnet::can_host_session($udom,$clientname,
 2091:                                                              $clientversion,
 2092:                                                              $remote,$hosted);
 2093:             }
 2094:         }
 2095:         if ($canhost) {               
 2096:             &Reply( $client, "authorized\n", $userinput);
 2097:         } else {
 2098:             &Reply( $client, "not_allowed_to_host\n", $userinput);
 2099:         }
 2100: 	#
 2101: 	#  Bad credentials: Failed to authorize
 2102: 	#
 2103:     } else {
 2104: 	&Failure( $client, "non_authorized\n", $userinput);
 2105:     }
 2106: 
 2107:     return 1;
 2108: }
 2109: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
 2110: 
 2111: #
 2112: #   Change a user's password.  Note that this function is complicated by
 2113: #   the fact that a user may be authenticated in more than one way:
 2114: #   At present, we are not able to change the password for all types of
 2115: #   authentication methods.  Only for:
 2116: #      unix    - unix password or shadow passoword style authentication.
 2117: #      local   - Locally written authentication mechanism.
 2118: #   For now, kerb4 and kerb5 password changes are not supported and result
 2119: #   in an error.
 2120: # FUTURE WORK:
 2121: #    Support kerberos passwd changes?
 2122: # Parameters:
 2123: #    $cmd      - The command that got us here.
 2124: #    $tail     - Tail of the command (remaining parameters).
 2125: #    $client   - File descriptor connected to client.
 2126: # Returns
 2127: #     0        - Requested to exit, caller should shut down.
 2128: #     1        - Continue processing.
 2129: # Implicit inputs:
 2130: #    The authentication systems describe above have their own forms of implicit
 2131: #    input into the authentication process that are described above.
 2132: sub change_password_handler {
 2133:     my ($cmd, $tail, $client) = @_;
 2134: 
 2135:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
 2136: 
 2137:     #
 2138:     #  udom  - user's domain.
 2139:     #  uname - Username.
 2140:     #  upass - Current password.
 2141:     #  npass - New password.
 2142:     #  context - Context in which this was called 
 2143:     #            (preferences or reset_by_email).
 2144:     #  lonhost - HostID of server where request originated 
 2145:    
 2146:     my ($udom,$uname,$upass,$npass,$context,$lonhost)=split(/:/,$tail);
 2147: 
 2148:     $upass=&unescape($upass);
 2149:     $npass=&unescape($npass);
 2150:     &Debug("Trying to change password for $uname");
 2151: 
 2152:     # First require that the user can be authenticated with their
 2153:     # old password unless context was 'reset_by_email':
 2154:     
 2155:     my ($validated,$failure);
 2156:     if ($context eq 'reset_by_email') {
 2157:         if ($lonhost eq '') {
 2158:             $failure = 'invalid_client';
 2159:         } else {
 2160:             $validated = 1;
 2161:         }
 2162:     } else {
 2163:         $validated = &validate_user($udom, $uname, $upass);
 2164:     }
 2165:     if($validated) {
 2166: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
 2167: 	
 2168: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
 2169: 	if ($howpwd eq 'internal') {
 2170: 	    &Debug("internal auth");
 2171:             my $ncpass = &hash_passwd($udom,$npass);
 2172: 	    if(&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
 2173: 		my $msg="Result of password change for $uname: pwchange_success";
 2174:                 if ($lonhost) {
 2175:                     $msg .= " - request originated from: $lonhost";
 2176:                 }
 2177:                 &logthis($msg);
 2178:                 &update_passwd_history($uname,$udom,$howpwd,$context);
 2179: 		&Reply($client, "ok\n", $userinput);
 2180: 	    } else {
 2181: 		&logthis("Unable to open $uname passwd "               
 2182: 			 ."to change password");
 2183: 		&Failure( $client, "non_authorized\n",$userinput);
 2184: 	    }
 2185: 	} elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
 2186: 	    my $result = &change_unix_password($uname, $npass);
 2187:             if ($result eq 'ok') {
 2188:                 &update_passwd_history($uname,$udom,$howpwd,$context);
 2189:              }
 2190: 	    &logthis("Result of password change for $uname: ".
 2191: 		     $result);
 2192: 	    &Reply($client, \$result, $userinput);
 2193: 	} else {
 2194: 	    # this just means that the current password mode is not
 2195: 	    # one we know how to change (e.g the kerberos auth modes or
 2196: 	    # locally written auth handler).
 2197: 	    #
 2198: 	    &Failure( $client, "auth_mode_error\n", $userinput);
 2199: 	}  
 2200: 	
 2201:     } else {
 2202: 	if ($failure eq '') {
 2203: 	    $failure = 'non_authorized';
 2204: 	}
 2205: 	&Failure( $client, "$failure\n", $userinput);
 2206:     }
 2207: 
 2208:     return 1;
 2209: }
 2210: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
 2211: 
 2212: sub hash_passwd {
 2213:     my ($domain,$plainpass,@rest) = @_;
 2214:     my ($salt,$cost);
 2215:     if (@rest) {
 2216:         $cost = $rest[0];
 2217:         # salt is first 22 characters, base-64 encoded by bcrypt
 2218:         my $plainsalt = substr($rest[1],0,22);
 2219:         $salt = Crypt::Eksblowfish::Bcrypt::de_base64($plainsalt);
 2220:     } else {
 2221:         my $defaultcost;
 2222:         my %domconfig =
 2223:             &Apache::lonnet::get_dom('configuration',['password'],$domain);
 2224:         if (ref($domconfig{'password'}) eq 'HASH') {
 2225:             $defaultcost = $domconfig{'password'}{'cost'};
 2226:         }
 2227:         if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
 2228:             $cost = 10;
 2229:         } else {
 2230:             $cost = $defaultcost;
 2231:         }
 2232:         # Generate random 16-octet base64 salt
 2233:         $salt = "";
 2234:         $salt .= pack("C", int rand(256)) for 1..16;
 2235:     }
 2236:     my $hash = &Crypt::Eksblowfish::Bcrypt::bcrypt_hash({
 2237:         key_nul => 1,
 2238:         cost    => $cost,
 2239:         salt    => $salt,
 2240:     }, Digest::SHA::sha512(Encode::encode('UTF-8',$plainpass)));
 2241: 
 2242:     my $result = join("!", "", "bcrypt", sprintf("%02d",$cost),
 2243:                 &Crypt::Eksblowfish::Bcrypt::en_base64($salt).
 2244:                 &Crypt::Eksblowfish::Bcrypt::en_base64($hash));
 2245:     return $result;
 2246: }
 2247: 
 2248: #
 2249: #   Create a new user.  User in this case means a lon-capa user.
 2250: #   The user must either already exist in some authentication realm
 2251: #   like kerberos or the /etc/passwd.  If not, a user completely local to
 2252: #   this loncapa system is created.
 2253: #
 2254: # Parameters:
 2255: #    $cmd      - The command that got us here.
 2256: #    $tail     - Tail of the command (remaining parameters).
 2257: #    $client   - File descriptor connected to client.
 2258: # Returns
 2259: #     0        - Requested to exit, caller should shut down.
 2260: #     1        - Continue processing.
 2261: # Implicit inputs:
 2262: #    The authentication systems describe above have their own forms of implicit
 2263: #    input into the authentication process that are described above.
 2264: sub add_user_handler {
 2265: 
 2266:     my ($cmd, $tail, $client) = @_;
 2267: 
 2268: 
 2269:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
 2270:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
 2271: 
 2272:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
 2273: 
 2274: 
 2275:     if($udom eq $currentdomainid) { # Reject new users for other domains...
 2276: 	
 2277: 	my $oldumask=umask(0077);
 2278: 	chomp($npass);
 2279: 	$npass=&unescape($npass);
 2280: 	my $passfilename  = &password_path($udom, $uname);
 2281: 	&Debug("Password file created will be:".$passfilename);
 2282: 	if (-e $passfilename) {
 2283: 	    &Failure( $client, "already_exists\n", $userinput);
 2284: 	} else {
 2285: 	    my $fperror='';
 2286: 	    if (!&mkpath($passfilename)) {
 2287: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
 2288: 		    ."makeuser";
 2289: 	    }
 2290: 	    unless ($fperror) {
 2291: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
 2292:                                              $passfilename,'makeuser');
 2293: 		&Reply($client,\$result, $userinput);     #BUGBUG - could be fail
 2294: 	    } else {
 2295: 		&Failure($client, \$fperror, $userinput);
 2296: 	    }
 2297: 	}
 2298: 	umask($oldumask);
 2299:     }  else {
 2300: 	&Failure($client, "not_right_domain\n",
 2301: 		$userinput);	# Even if we are multihomed.
 2302:     
 2303:     }
 2304:     return 1;
 2305: 
 2306: }
 2307: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
 2308: 
 2309: #
 2310: #   Change the authentication method of a user.  Note that this may
 2311: #   also implicitly change the user's password if, for example, the user is
 2312: #   joining an existing authentication realm.  Known authentication realms at
 2313: #   this time are:
 2314: #    internal   - Purely internal password file (only loncapa knows this user)
 2315: #    local      - Institutionally written authentication module.
 2316: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
 2317: #    kerb4      - kerberos version 4
 2318: #    kerb5      - kerberos version 5
 2319: #
 2320: # Parameters:
 2321: #    $cmd      - The command that got us here.
 2322: #    $tail     - Tail of the command (remaining parameters).
 2323: #    $client   - File descriptor connected to client.
 2324: # Returns
 2325: #     0        - Requested to exit, caller should shut down.
 2326: #     1        - Continue processing.
 2327: # Implicit inputs:
 2328: #    The authentication systems describe above have their own forms of implicit
 2329: #    input into the authentication process that are described above.
 2330: # NOTE:
 2331: #   This is also used to change the authentication credential values (e.g. passwd).
 2332: #   
 2333: #
 2334: sub change_authentication_handler {
 2335: 
 2336:     my ($cmd, $tail, $client) = @_;
 2337:    
 2338:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
 2339: 
 2340:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
 2341:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
 2342:     if ($udom ne $currentdomainid) {
 2343: 	&Failure( $client, "not_right_domain\n", $client);
 2344:     } else {
 2345: 	
 2346: 	chomp($npass);
 2347: 	
 2348: 	$npass=&unescape($npass);
 2349: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
 2350: 	my $passfilename = &password_path($udom, $uname);
 2351: 	if ($passfilename) {	# Not allowed to create a new user!!
 2352: 	    # If just changing the unix passwd. need to arrange to run
 2353: 	    # passwd since otherwise make_passwd_file will fail as 
 2354: 	    # creation of unix authenticated users is no longer supported
 2355:             # except from the command line, when running make_domain_coordinator.pl
 2356: 
 2357: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
 2358: 		my $result = &change_unix_password($uname, $npass);
 2359: 		&logthis("Result of password change for $uname: ".$result);
 2360: 		if ($result eq "ok") {
 2361:                     &update_passwd_history($uname,$udom,$umode,'changeuserauth'); 
 2362: 		    &Reply($client, \$result);
 2363: 		} else {
 2364: 		    &Failure($client, \$result);
 2365: 		}
 2366: 	    } else {
 2367: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
 2368:                                              $passfilename,'changeuserauth');
 2369: 		#
 2370: 		#  If the current auth mode is internal, and the old auth mode was
 2371: 		#  unix, or krb*,  and the user is an author for this domain,
 2372: 		#  re-run manage_permissions for that role in order to be able
 2373: 		#  to take ownership of the construction space back to www:www
 2374: 		#
 2375: 
 2376: 
 2377: 		&Reply($client, \$result, $userinput);
 2378: 	    }
 2379: 	       
 2380: 
 2381: 	} else {	       
 2382: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
 2383: 	}
 2384:     }
 2385:     return 1;
 2386: }
 2387: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
 2388: 
 2389: sub update_passwd_history {
 2390:     my ($uname,$udom,$umode,$context) = @_;
 2391:     my $proname=&propath($udom,$uname);
 2392:     my $now = time;
 2393:     if (open(my $fh,">>$proname/passwd.log")) {
 2394:         print $fh "$now:$umode:$context\n";
 2395:         close($fh);
 2396:     }
 2397:     return;
 2398: }
 2399: 
 2400: #
 2401: #   Determines if this is the home server for a user.  The home server
 2402: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
 2403: #   to do is determine if this file exists.
 2404: #
 2405: # Parameters:
 2406: #    $cmd      - The command that got us here.
 2407: #    $tail     - Tail of the command (remaining parameters).
 2408: #    $client   - File descriptor connected to client.
 2409: # Returns
 2410: #     0        - Requested to exit, caller should shut down.
 2411: #     1        - Continue processing.
 2412: # Implicit inputs:
 2413: #    The authentication systems describe above have their own forms of implicit
 2414: #    input into the authentication process that are described above.
 2415: #
 2416: sub is_home_handler {
 2417:     my ($cmd, $tail, $client) = @_;
 2418:    
 2419:     my $userinput  = "$cmd:$tail";
 2420:    
 2421:     my ($udom,$uname)=split(/:/,$tail);
 2422:     chomp($uname);
 2423:     my $passfile = &password_filename($udom, $uname);
 2424:     if($passfile) {
 2425: 	&Reply( $client, "found\n", $userinput);
 2426:     } else {
 2427: 	&Failure($client, "not_found\n", $userinput);
 2428:     }
 2429:     return 1;
 2430: }
 2431: &register_handler("home", \&is_home_handler, 0,1,0);
 2432: 
 2433: #
 2434: #   Process an update request for a resource.
 2435: #   A resource has been modified that we hold a subscription to.
 2436: #   If the resource is not local, then we must update, or at least invalidate our
 2437: #   cached copy of the resource. 
 2438: # Parameters:
 2439: #    $cmd      - The command that got us here.
 2440: #    $tail     - Tail of the command (remaining parameters).
 2441: #    $client   - File descriptor connected to client.
 2442: # Returns
 2443: #     0        - Requested to exit, caller should shut down.
 2444: #     1        - Continue processing.
 2445: # Implicit inputs:
 2446: #    The authentication systems describe above have their own forms of implicit
 2447: #    input into the authentication process that are described above.
 2448: #
 2449: sub update_resource_handler {
 2450: 
 2451:     my ($cmd, $tail, $client) = @_;
 2452:    
 2453:     my $userinput = "$cmd:$tail";
 2454:    
 2455:     my $fname= $tail;		# This allows interactive testing
 2456: 
 2457: 
 2458:     my $ownership=ishome($fname);
 2459:     if ($ownership eq 'not_owner') {
 2460: 	if (-e $fname) {
 2461:             # Delete preview file, if exists
 2462:             unlink("$fname.tmp");
 2463:             # Get usage stats
 2464: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
 2465: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
 2466: 	    my $now=time;
 2467: 	    my $since=$now-$atime;
 2468:             # If the file has not been used within lonExpire seconds,
 2469:             # unsubscribe from it and delete local copy
 2470: 	    if ($since>$perlvar{'lonExpire'}) {
 2471: 		my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
 2472: 		&devalidate_meta_cache($fname);
 2473: 		unlink("$fname");
 2474: 		unlink("$fname.meta");
 2475: 	    } else {
 2476:             # Yes, this is in active use. Get a fresh copy. Since it might be in
 2477:             # very active use and huge (like a movie), copy it to "in.transfer" filename first.
 2478: 		my $transname="$fname.in.transfer";
 2479: 		my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
 2480: 		my $response;
 2481: # FIXME: cannot replicate files that take more than two minutes to transfer?
 2482: #		alarm(120);
 2483: # FIXME: this should use the LWP mechanism, not internal alarms.
 2484:                 alarm(1200);
 2485: 		{
 2486: 		    my $request=new HTTP::Request('GET',"$remoteurl");
 2487:                     $response=&LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,0,1);
 2488: 		}
 2489: 		alarm(0);
 2490: 		if ($response->is_error()) {
 2491: # FIXME: we should probably clean up here instead of just whine
 2492: 		    unlink($transname);
 2493: 		    my $message=$response->status_line;
 2494: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
 2495: 		} else {
 2496: 		    if ($remoteurl!~/\.meta$/) {
 2497: # FIXME: isn't there an internal LWP mechanism for this?
 2498: 			alarm(120);
 2499: 			{
 2500: 			    my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2501:                             my $mresponse = &LONCAPA::LWPReq::makerequest($clientname,$mrequest,$fname.'.meta',\%perlvar,120,0,1);
 2502: 			    if ($mresponse->is_error()) {
 2503: 				unlink($fname.'.meta');
 2504: 			    }
 2505: 			}
 2506: 			alarm(0);
 2507: 		    }
 2508:                     # we successfully transfered, copy file over to real name
 2509: 		    rename($transname,$fname);
 2510: 		    &devalidate_meta_cache($fname);
 2511: 		}
 2512: 	    }
 2513: 	    &Reply( $client, "ok\n", $userinput);
 2514: 	} else {
 2515: 	    &Failure($client, "not_found\n", $userinput);
 2516: 	}
 2517:     } else {
 2518: 	&Failure($client, "rejected\n", $userinput);
 2519:     }
 2520:     return 1;
 2521: }
 2522: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
 2523: 
 2524: sub devalidate_meta_cache {
 2525:     my ($url) = @_;
 2526:     use Cache::Memcached;
 2527:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
 2528:     $url = &Apache::lonnet::declutter($url);
 2529:     $url =~ s-\.meta$--;
 2530:     my $id = &escape('meta:'.$url);
 2531:     $memcache->delete($id);
 2532: }
 2533: 
 2534: #
 2535: #   Fetch a user file from a remote server to the user's home directory
 2536: #   userfiles subdir.
 2537: # Parameters:
 2538: #    $cmd      - The command that got us here.
 2539: #    $tail     - Tail of the command (remaining parameters).
 2540: #    $client   - File descriptor connected to client.
 2541: # Returns
 2542: #     0        - Requested to exit, caller should shut down.
 2543: #     1        - Continue processing.
 2544: #
 2545: sub fetch_user_file_handler {
 2546: 
 2547:     my ($cmd, $tail, $client) = @_;
 2548: 
 2549:     my $userinput = "$cmd:$tail";
 2550:     my $fname           = $tail;
 2551:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
 2552:     my $udir=&propath($udom,$uname).'/userfiles';
 2553:     unless (-e $udir) {
 2554: 	mkdir($udir,0770); 
 2555:     }
 2556:     Debug("fetch user file for $fname");
 2557:     if (-e $udir) {
 2558: 	$ufile=~s/^[\.\~]+//;
 2559: 
 2560: 	# IF necessary, create the path right down to the file.
 2561: 	# Note that any regular files in the way of this path are
 2562: 	# wiped out to deal with some earlier folly of mine.
 2563: 
 2564: 	if (!&mkpath($udir.'/'.$ufile)) {
 2565: 	    &Failure($client, "unable_to_create\n", $userinput);	    
 2566: 	}
 2567: 
 2568: 	my $destname=$udir.'/'.$ufile;
 2569: 	my $transname=$udir.'/'.$ufile.'.in.transit';
 2570:         my $clientprotocol=$Apache::lonnet::protocol{$clientname};
 2571:         $clientprotocol = 'http' if ($clientprotocol ne 'https');
 2572: 	my $clienthost = &Apache::lonnet::hostname($clientname);
 2573: 	my $remoteurl=$clientprotocol.'://'.$clienthost.'/userfiles/'.$fname;
 2574: 	my $response;
 2575: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
 2576: 	alarm(1200);
 2577: 	{
 2578: 	    my $request=new HTTP::Request('GET',"$remoteurl");
 2579:             my $verifycert = 1;
 2580:             my @machine_ids = &Apache::lonnet::current_machine_ids();
 2581:             if (grep(/^\Q$clientname\E$/,@machine_ids)) {
 2582:                 $verifycert = 0;
 2583:             }
 2584:             $response = &LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,$verifycert);
 2585: 	}
 2586: 	alarm(0);
 2587: 	if ($response->is_error()) {
 2588: 	    unlink($transname);
 2589: 	    my $message=$response->status_line;
 2590: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
 2591: 	    &Failure($client, "failed\n", $userinput);
 2592: 	} else {
 2593: 	    Debug("Renaming $transname to $destname");
 2594: 	    if (!rename($transname,$destname)) {
 2595: 		&logthis("Unable to move $transname to $destname");
 2596: 		unlink($transname);
 2597: 		&Failure($client, "failed\n", $userinput);
 2598: 	    } else {
 2599:                 if ($fname =~ /^default.+\.(page|sequence)$/) {
 2600:                     my ($major,$minor) = split(/\./,$clientversion);
 2601:                     if (($major < 2) || ($major == 2 && $minor < 11)) {
 2602:                         my $now = time;
 2603:                         &Apache::lonnet::do_cache_new('crschange',$udom.'_'.$uname,$now,600);
 2604:                         my $key = &escape('internal.contentchange');
 2605:                         my $what = "$key=$now";
 2606:                         my $hashref = &tie_user_hash($udom,$uname,'environment',
 2607:                                                      &GDBM_WRCREAT(),"P",$what);
 2608:                         if ($hashref) {
 2609:                             $hashref->{$key}=$now;
 2610:                             if (!&untie_user_hash($hashref)) {
 2611:                                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
 2612:                                          "when updating internal.contentchange");
 2613:                             }
 2614:                         }
 2615:                     }
 2616:                 }
 2617: 		&Reply($client, "ok\n", $userinput);
 2618: 	    }
 2619: 	}   
 2620:     } else {
 2621: 	&Failure($client, "not_home\n", $userinput);
 2622:     }
 2623:     return 1;
 2624: }
 2625: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
 2626: 
 2627: #
 2628: #   Remove a file from a user's home directory userfiles subdirectory.
 2629: # Parameters:
 2630: #    cmd   - the Lond request keyword that got us here.
 2631: #    tail  - the part of the command past the keyword.
 2632: #    client- File descriptor connected with the client.
 2633: #
 2634: # Returns:
 2635: #    1    - Continue processing.
 2636: sub remove_user_file_handler {
 2637:     my ($cmd, $tail, $client) = @_;
 2638: 
 2639:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
 2640: 
 2641:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
 2642:     if ($ufile =~m|/\.\./|) {
 2643: 	# any files paths with /../ in them refuse 
 2644: 	# to deal with
 2645: 	&Failure($client, "refused\n", "$cmd:$tail");
 2646:     } else {
 2647: 	my $udir = &propath($udom,$uname);
 2648: 	if (-e $udir) {
 2649: 	    my $file=$udir.'/userfiles/'.$ufile;
 2650: 	    if (-e $file) {
 2651: 		#
 2652: 		#   If the file is a regular file unlink is fine...
 2653: 		#   However it's possible the client wants a dir 
 2654: 		#   removed, in which case rmdir is more appropriate.
 2655: 		#   Note: rmdir will only remove an empty directory.
 2656: 		#
 2657: 	        if (-f $file){
 2658: 		    unlink($file);
 2659:                     # for html files remove the associated .bak file 
 2660:                     # which may have been created by the editor.
 2661:                     if ($ufile =~ m{^((docs|supplemental)/(?:\d+|default)/\d+(?:|/.+)/)[^/]+\.x?html?$}i) {
 2662:                         my $path = $1;
 2663:                         if (-e $file.'.bak') {
 2664:                             unlink($file.'.bak');
 2665:                         }
 2666:                     }
 2667: 		} elsif(-d $file) {
 2668: 		    rmdir($file);
 2669: 		}
 2670: 		if (-e $file) {
 2671: 		    #  File is still there after we deleted it ?!?
 2672: 
 2673: 		    &Failure($client, "failed\n", "$cmd:$tail");
 2674: 		} else {
 2675: 		    &Reply($client, "ok\n", "$cmd:$tail");
 2676: 		}
 2677: 	    } else {
 2678: 		&Failure($client, "not_found\n", "$cmd:$tail");
 2679: 	    }
 2680: 	} else {
 2681: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 2682: 	}
 2683:     }
 2684:     return 1;
 2685: }
 2686: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
 2687: 
 2688: #
 2689: #   make a directory in a user's home directory userfiles subdirectory.
 2690: # Parameters:
 2691: #    cmd   - the Lond request keyword that got us here.
 2692: #    tail  - the part of the command past the keyword.
 2693: #    client- File descriptor connected with the client.
 2694: #
 2695: # Returns:
 2696: #    1    - Continue processing.
 2697: sub mkdir_user_file_handler {
 2698:     my ($cmd, $tail, $client) = @_;
 2699: 
 2700:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
 2701:     $dir=&unescape($dir);
 2702:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
 2703:     if ($ufile =~m|/\.\./|) {
 2704: 	# any files paths with /../ in them refuse 
 2705: 	# to deal with
 2706: 	&Failure($client, "refused\n", "$cmd:$tail");
 2707:     } else {
 2708: 	my $udir = &propath($udom,$uname);
 2709: 	if (-e $udir) {
 2710: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
 2711: 	    if (!&mkpath($newdir)) {
 2712: 		&Failure($client, "failed\n", "$cmd:$tail");
 2713: 	    }
 2714: 	    &Reply($client, "ok\n", "$cmd:$tail");
 2715: 	} else {
 2716: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 2717: 	}
 2718:     }
 2719:     return 1;
 2720: }
 2721: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
 2722: 
 2723: #
 2724: #   rename a file in a user's home directory userfiles subdirectory.
 2725: # Parameters:
 2726: #    cmd   - the Lond request keyword that got us here.
 2727: #    tail  - the part of the command past the keyword.
 2728: #    client- File descriptor connected with the client.
 2729: #
 2730: # Returns:
 2731: #    1    - Continue processing.
 2732: sub rename_user_file_handler {
 2733:     my ($cmd, $tail, $client) = @_;
 2734: 
 2735:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
 2736:     $old=&unescape($old);
 2737:     $new=&unescape($new);
 2738:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
 2739: 	# any files paths with /../ in them refuse to deal with
 2740: 	&Failure($client, "refused\n", "$cmd:$tail");
 2741:     } else {
 2742: 	my $udir = &propath($udom,$uname);
 2743: 	if (-e $udir) {
 2744: 	    my $oldfile=$udir.'/userfiles/'.$old;
 2745: 	    my $newfile=$udir.'/userfiles/'.$new;
 2746: 	    if (-e $newfile) {
 2747: 		&Failure($client, "exists\n", "$cmd:$tail");
 2748: 	    } elsif (! -e $oldfile) {
 2749: 		&Failure($client, "not_found\n", "$cmd:$tail");
 2750: 	    } else {
 2751: 		if (!rename($oldfile,$newfile)) {
 2752: 		    &Failure($client, "failed\n", "$cmd:$tail");
 2753: 		} else {
 2754: 		    &Reply($client, "ok\n", "$cmd:$tail");
 2755: 		}
 2756: 	    }
 2757: 	} else {
 2758: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 2759: 	}
 2760:     }
 2761:     return 1;
 2762: }
 2763: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
 2764: 
 2765: #
 2766: #  Checks if the specified user has an active session on the server
 2767: #  return ok if so, not_found if not
 2768: #
 2769: # Parameters:
 2770: #   cmd      - The request keyword that dispatched to tus.
 2771: #   tail     - The tail of the request (colon separated parameters).
 2772: #   client   - Filehandle open on the client.
 2773: # Return:
 2774: #    1.
 2775: sub user_has_session_handler {
 2776:     my ($cmd, $tail, $client) = @_;
 2777: 
 2778:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
 2779:     
 2780:     opendir(DIR,$perlvar{'lonIDsDir'});
 2781:     my $filename;
 2782:     while ($filename=readdir(DIR)) {
 2783: 	last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
 2784:     }
 2785:     if ($filename) {
 2786: 	&Reply($client, "ok\n", "$cmd:$tail");
 2787:     } else {
 2788: 	&Failure($client, "not_found\n", "$cmd:$tail");
 2789:     }
 2790:     return 1;
 2791: 
 2792: }
 2793: &register_handler("userhassession", \&user_has_session_handler, 0,1,0);
 2794: 
 2795: #
 2796: #  Authenticate access to a user file by checking that the token the user's 
 2797: #  passed also exists in their session file
 2798: #
 2799: # Parameters:
 2800: #   cmd      - The request keyword that dispatched to tus.
 2801: #   tail     - The tail of the request (colon separated parameters).
 2802: #   client   - Filehandle open on the client.
 2803: # Return:
 2804: #    1.
 2805: sub token_auth_user_file_handler {
 2806:     my ($cmd, $tail, $client) = @_;
 2807: 
 2808:     my ($fname, $session) = split(/:/, $tail);
 2809:     
 2810:     chomp($session);
 2811:     my $reply="non_auth";
 2812:     my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
 2813:     if (open(ENVIN,"$file")) {
 2814: 	flock(ENVIN,LOCK_SH);
 2815: 	tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
 2816: 	if (exists($disk_env{"userfile.$fname"})) {
 2817: 	    $reply="ok";
 2818: 	} else {
 2819: 	    foreach my $envname (keys(%disk_env)) {
 2820: 		if ($envname=~ m|^userfile\.\Q$fname\E|) {
 2821: 		    $reply="ok";
 2822: 		    last;
 2823: 		}
 2824: 	    }
 2825: 	}
 2826: 	untie(%disk_env);
 2827: 	close(ENVIN);
 2828: 	&Reply($client, \$reply, "$cmd:$tail");
 2829:     } else {
 2830: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
 2831:     }
 2832:     return 1;
 2833: 
 2834: }
 2835: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
 2836: 
 2837: #
 2838: #   Unsubscribe from a resource.
 2839: #
 2840: # Parameters:
 2841: #    $cmd      - The command that got us here.
 2842: #    $tail     - Tail of the command (remaining parameters).
 2843: #    $client   - File descriptor connected to client.
 2844: # Returns
 2845: #     0        - Requested to exit, caller should shut down.
 2846: #     1        - Continue processing.
 2847: #
 2848: sub unsubscribe_handler {
 2849:     my ($cmd, $tail, $client) = @_;
 2850: 
 2851:     my $userinput= "$cmd:$tail";
 2852:     
 2853:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
 2854: 
 2855:     &Debug("Unsubscribing $fname");
 2856:     if (-e $fname) {
 2857: 	&Debug("Exists");
 2858: 	&Reply($client, &unsub($fname,$clientip), $userinput);
 2859:     } else {
 2860: 	&Failure($client, "not_found\n", $userinput);
 2861:     }
 2862:     return 1;
 2863: }
 2864: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
 2865: 
 2866: #   Subscribe to a resource
 2867: #
 2868: # Parameters:
 2869: #    $cmd      - The command that got us here.
 2870: #    $tail     - Tail of the command (remaining parameters).
 2871: #    $client   - File descriptor connected to client.
 2872: # Returns
 2873: #     0        - Requested to exit, caller should shut down.
 2874: #     1        - Continue processing.
 2875: #
 2876: sub subscribe_handler {
 2877:     my ($cmd, $tail, $client)= @_;
 2878: 
 2879:     my $userinput  = "$cmd:$tail";
 2880: 
 2881:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
 2882: 
 2883:     return 1;
 2884: }
 2885: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
 2886: 
 2887: #
 2888: #   Determine the latest version of a resource (it looks for the highest
 2889: #   past version and then returns that +1)
 2890: #
 2891: # Parameters:
 2892: #    $cmd      - The command that got us here.
 2893: #    $tail     - Tail of the command (remaining parameters).
 2894: #                 (Should consist of an absolute path to a file)
 2895: #    $client   - File descriptor connected to client.
 2896: # Returns
 2897: #     0        - Requested to exit, caller should shut down.
 2898: #     1        - Continue processing.
 2899: #
 2900: sub current_version_handler {
 2901:     my ($cmd, $tail, $client) = @_;
 2902: 
 2903:     my $userinput= "$cmd:$tail";
 2904:    
 2905:     my $fname   = $tail;
 2906:     &Reply( $client, &currentversion($fname)."\n", $userinput);
 2907:     return 1;
 2908: 
 2909: }
 2910: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
 2911: 
 2912: #  Make an entry in a user's activity log.
 2913: #
 2914: # Parameters:
 2915: #    $cmd      - The command that got us here.
 2916: #    $tail     - Tail of the command (remaining parameters).
 2917: #    $client   - File descriptor connected to client.
 2918: # Returns
 2919: #     0        - Requested to exit, caller should shut down.
 2920: #     1        - Continue processing.
 2921: #
 2922: sub activity_log_handler {
 2923:     my ($cmd, $tail, $client) = @_;
 2924: 
 2925: 
 2926:     my $userinput= "$cmd:$tail";
 2927: 
 2928:     my ($udom,$uname,$what)=split(/:/,$tail);
 2929:     chomp($what);
 2930:     my $proname=&propath($udom,$uname);
 2931:     my $now=time;
 2932:     my $hfh;
 2933:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
 2934: 	print $hfh "$now:$clientname:$what\n";
 2935: 	&Reply( $client, "ok\n", $userinput); 
 2936:     } else {
 2937: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
 2938: 		 ."while attempting log\n", 
 2939: 		 $userinput);
 2940:     }
 2941: 
 2942:     return 1;
 2943: }
 2944: &register_handler("log", \&activity_log_handler, 0, 1, 0);
 2945: 
 2946: #
 2947: #   Put a namespace entry in a user profile hash.
 2948: #   My druthers would be for this to be an encrypted interaction too.
 2949: #   anything that might be an inadvertent covert channel about either
 2950: #   user authentication or user personal information....
 2951: #
 2952: # Parameters:
 2953: #    $cmd      - The command that got us here.
 2954: #    $tail     - Tail of the command (remaining parameters).
 2955: #    $client   - File descriptor connected to client.
 2956: # Returns
 2957: #     0        - Requested to exit, caller should shut down.
 2958: #     1        - Continue processing.
 2959: #
 2960: sub put_user_profile_entry {
 2961:     my ($cmd, $tail, $client)  = @_;
 2962: 
 2963:     my $userinput = "$cmd:$tail";
 2964:     
 2965:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
 2966:     if ($namespace ne 'roles') {
 2967: 	chomp($what);
 2968: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2969: 				  &GDBM_WRCREAT(),"P",$what);
 2970: 	if($hashref) {
 2971: 	    my @pairs=split(/\&/,$what);
 2972: 	    foreach my $pair (@pairs) {
 2973: 		my ($key,$value)=split(/=/,$pair);
 2974: 		$hashref->{$key}=$value;
 2975: 	    }
 2976: 	    if (&untie_user_hash($hashref)) {
 2977: 		&Reply( $client, "ok\n", $userinput);
 2978: 	    } else {
 2979: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 2980: 			"while attempting put\n", 
 2981: 			$userinput);
 2982: 	    }
 2983: 	} else {
 2984: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 2985: 		     "while attempting put\n", $userinput);
 2986: 	}
 2987:     } else {
 2988:         &Failure( $client, "refused\n", $userinput);
 2989:     }
 2990:     
 2991:     return 1;
 2992: }
 2993: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
 2994: 
 2995: #   Put a piece of new data in hash, returns error if entry already exists
 2996: # Parameters:
 2997: #    $cmd      - The command that got us here.
 2998: #    $tail     - Tail of the command (remaining parameters).
 2999: #    $client   - File descriptor connected to client.
 3000: # Returns
 3001: #     0        - Requested to exit, caller should shut down.
 3002: #     1        - Continue processing.
 3003: #
 3004: sub newput_user_profile_entry {
 3005:     my ($cmd, $tail, $client)  = @_;
 3006: 
 3007:     my $userinput = "$cmd:$tail";
 3008: 
 3009:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
 3010:     if ($namespace eq 'roles') {
 3011:         &Failure( $client, "refused\n", $userinput);
 3012: 	return 1;
 3013:     }
 3014: 
 3015:     chomp($what);
 3016: 
 3017:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3018: 				 &GDBM_WRCREAT(),"N",$what);
 3019:     if(!$hashref) {
 3020: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3021: 		  "while attempting put\n", $userinput);
 3022: 	return 1;
 3023:     }
 3024: 
 3025:     my @pairs=split(/\&/,$what);
 3026:     foreach my $pair (@pairs) {
 3027: 	my ($key,$value)=split(/=/,$pair);
 3028: 	if (exists($hashref->{$key})) {
 3029:             if (!&untie_user_hash($hashref)) {
 3030:                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
 3031:                          "while attempting newput - early out as key exists");
 3032:             }
 3033:             &Failure($client, "key_exists: ".$key."\n",$userinput);
 3034:             return 1;
 3035: 	}
 3036:     }
 3037: 
 3038:     foreach my $pair (@pairs) {
 3039: 	my ($key,$value)=split(/=/,$pair);
 3040: 	$hashref->{$key}=$value;
 3041:     }
 3042: 
 3043:     if (&untie_user_hash($hashref)) {
 3044: 	&Reply( $client, "ok\n", $userinput);
 3045:     } else {
 3046: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 3047: 		 "while attempting put\n", 
 3048: 		 $userinput);
 3049:     }
 3050:     return 1;
 3051: }
 3052: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
 3053: 
 3054: # 
 3055: #   Increment a profile entry in the user history file.
 3056: #   The history contains keyword value pairs.  In this case,
 3057: #   The value itself is a pair of numbers.  The first, the current value
 3058: #   the second an increment that this function applies to the current
 3059: #   value.
 3060: #
 3061: # Parameters:
 3062: #    $cmd      - The command that got us here.
 3063: #    $tail     - Tail of the command (remaining parameters).
 3064: #    $client   - File descriptor connected to client.
 3065: # Returns
 3066: #     0        - Requested to exit, caller should shut down.
 3067: #     1        - Continue processing.
 3068: #
 3069: sub increment_user_value_handler {
 3070:     my ($cmd, $tail, $client) = @_;
 3071:     
 3072:     my $userinput   = "$cmd:$tail";
 3073:     
 3074:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
 3075:     if ($namespace ne 'roles') {
 3076:         chomp($what);
 3077: 	my $hashref = &tie_user_hash($udom, $uname,
 3078: 				     $namespace, &GDBM_WRCREAT(),
 3079: 				     "P",$what);
 3080: 	if ($hashref) {
 3081: 	    my @pairs=split(/\&/,$what);
 3082: 	    foreach my $pair (@pairs) {
 3083: 		my ($key,$value)=split(/=/,$pair);
 3084:                 $value = &unescape($value);
 3085: 		# We could check that we have a number...
 3086: 		if (! defined($value) || $value eq '') {
 3087: 		    $value = 1;
 3088: 		}
 3089: 		$hashref->{$key}+=$value;
 3090:                 if ($namespace eq 'nohist_resourcetracker') {
 3091:                     if ($hashref->{$key} < 0) {
 3092:                         $hashref->{$key} = 0;
 3093:                     }
 3094:                 }
 3095: 	    }
 3096: 	    if (&untie_user_hash($hashref)) {
 3097: 		&Reply( $client, "ok\n", $userinput);
 3098: 	    } else {
 3099: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 3100: 			 "while attempting inc\n", $userinput);
 3101: 	    }
 3102: 	} else {
 3103: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3104: 		     "while attempting inc\n", $userinput);
 3105: 	}
 3106:     } else {
 3107: 	&Failure($client, "refused\n", $userinput);
 3108:     }
 3109:     
 3110:     return 1;
 3111: }
 3112: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
 3113: 
 3114: #
 3115: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
 3116: #   Each 'role' a user has implies a set of permissions.  Adding a new role
 3117: #   for a person grants the permissions packaged with that role
 3118: #   to that user when the role is selected.
 3119: #
 3120: # Parameters:
 3121: #    $cmd       - The command string (rolesput).
 3122: #    $tail      - The remainder of the request line.  For rolesput this
 3123: #                 consists of a colon separated list that contains:
 3124: #                 The domain and user that is granting the role (logged).
 3125: #                 The domain and user that is getting the role.
 3126: #                 The roles being granted as a set of & separated pairs.
 3127: #                 each pair a key value pair.
 3128: #    $client    - File descriptor connected to the client.
 3129: # Returns:
 3130: #     0         - If the daemon should exit
 3131: #     1         - To continue processing.
 3132: #
 3133: #
 3134: sub roles_put_handler {
 3135:     my ($cmd, $tail, $client) = @_;
 3136: 
 3137:     my $userinput  = "$cmd:$tail";
 3138: 
 3139:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
 3140:     
 3141: 
 3142:     my $namespace='roles';
 3143:     chomp($what);
 3144:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3145: 				 &GDBM_WRCREAT(), "P",
 3146: 				 "$exedom:$exeuser:$what");
 3147:     #
 3148:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
 3149:     #  handle is open for the minimal amount of time.  Since the flush
 3150:     #  is done on close this improves the chances the log will be an un-
 3151:     #  corrupted ordered thing.
 3152:     if ($hashref) {
 3153: 	my $pass_entry = &get_auth_type($udom, $uname);
 3154: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
 3155: 	$auth_type = $auth_type.":";
 3156: 	my @pairs=split(/\&/,$what);
 3157: 	foreach my $pair (@pairs) {
 3158: 	    my ($key,$value)=split(/=/,$pair);
 3159: 	    &manage_permissions($key, $udom, $uname,
 3160: 			       $auth_type);
 3161: 	    $hashref->{$key}=$value;
 3162: 	}
 3163: 	if (&untie_user_hash($hashref)) {
 3164: 	    &Reply($client, "ok\n", $userinput);
 3165: 	} else {
 3166: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 3167: 		     "while attempting rolesput\n", $userinput);
 3168: 	}
 3169:     } else {
 3170: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3171: 		 "while attempting rolesput\n", $userinput);
 3172:     }
 3173:     return 1;
 3174: }
 3175: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
 3176: 
 3177: #
 3178: #   Deletes (removes) a role for a user.   This is equivalent to removing
 3179: #  a permissions package associated with the role from the user's profile.
 3180: #
 3181: # Parameters:
 3182: #     $cmd                 - The command (rolesdel)
 3183: #     $tail                - The remainder of the request line. This consists
 3184: #                             of:
 3185: #                             The domain and user requesting the change (logged)
 3186: #                             The domain and user being changed.
 3187: #                             The roles being revoked.  These are shipped to us
 3188: #                             as a bunch of & separated role name keywords.
 3189: #     $client              - The file handle open on the client.
 3190: # Returns:
 3191: #     1                    - Continue processing
 3192: #     0                    - Exit.
 3193: #
 3194: sub roles_delete_handler {
 3195:     my ($cmd, $tail, $client)  = @_;
 3196: 
 3197:     my $userinput    = "$cmd:$tail";
 3198:    
 3199:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
 3200:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
 3201: 	   "what = ".$what);
 3202:     my $namespace='roles';
 3203:     chomp($what);
 3204:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3205: 				 &GDBM_WRCREAT(), "D",
 3206: 				 "$exedom:$exeuser:$what");
 3207:     
 3208:     if ($hashref) {
 3209: 	my @rolekeys=split(/\&/,$what);
 3210: 	
 3211: 	foreach my $key (@rolekeys) {
 3212: 	    delete $hashref->{$key};
 3213: 	}
 3214: 	if (&untie_user_hash($hashref)) {
 3215: 	    &Reply($client, "ok\n", $userinput);
 3216: 	} else {
 3217: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 3218: 		     "while attempting rolesdel\n", $userinput);
 3219: 	}
 3220:     } else {
 3221:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3222: 		 "while attempting rolesdel\n", $userinput);
 3223:     }
 3224:     
 3225:     return 1;
 3226: }
 3227: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
 3228: 
 3229: # Unencrypted get from a user's profile database.  See 
 3230: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
 3231: # This function retrieves a keyed item from a specific named database in the
 3232: # user's directory.
 3233: #
 3234: # Parameters:
 3235: #   $cmd             - Command request keyword (get).
 3236: #   $tail            - Tail of the command.  This is a colon separated list
 3237: #                      consisting of the domain and username that uniquely
 3238: #                      identifies the profile,
 3239: #                      The 'namespace' which selects the gdbm file to 
 3240: #                      do the lookup in, 
 3241: #                      & separated list of keys to lookup.  Note that
 3242: #                      the values are returned as an & separated list too.
 3243: #   $client          - File descriptor open on the client.
 3244: # Returns:
 3245: #   1       - Continue processing.
 3246: #   0       - Exit.
 3247: #
 3248: sub get_profile_entry {
 3249:     my ($cmd, $tail, $client) = @_;
 3250: 
 3251:     my $userinput= "$cmd:$tail";
 3252:    
 3253:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 3254:     chomp($what);
 3255: 
 3256: 
 3257:     my $replystring = read_profile($udom, $uname, $namespace, $what);
 3258:     my ($first) = split(/:/,$replystring);
 3259:     if($first ne "error") {
 3260: 	&Reply($client, \$replystring, $userinput);
 3261:     } else {
 3262: 	&Failure($client, $replystring." while attempting get\n", $userinput);
 3263:     }
 3264:     return 1;
 3265: 
 3266: 
 3267: }
 3268: &register_handler("get", \&get_profile_entry, 0,1,0);
 3269: 
 3270: #
 3271: #  Process the encrypted get request.  Note that the request is sent
 3272: #  in clear, but the reply is encrypted.  This is a small covert channel:
 3273: #  information about the sensitive keys is given to the snooper.  Just not
 3274: #  information about the values of the sensitive key.  Hmm if I wanted to
 3275: #  know these I'd snoop for the egets. Get the profile item names from them
 3276: #  and then issue a get for them since there's no enforcement of the
 3277: #  requirement of an encrypted get for particular profile items.  If I
 3278: #  were re-doing this, I'd force the request to be encrypted as well as the
 3279: #  reply.  I'd also just enforce encrypted transactions for all gets since
 3280: #  that would prevent any covert channel snooping.
 3281: #
 3282: #  Parameters:
 3283: #     $cmd               - Command keyword of request (eget).
 3284: #     $tail              - Tail of the command.  See GetProfileEntry
#                          for more information about this.
 3285: #     $client            - File open on the client.
 3286: #  Returns:
 3287: #     1      - Continue processing
 3288: #     0      - server should exit.
 3289: sub get_profile_entry_encrypted {
 3290:     my ($cmd, $tail, $client) = @_;
 3291: 
 3292:     my $userinput = "$cmd:$tail";
 3293:    
 3294:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 3295:     chomp($what);
 3296:     my $qresult = read_profile($udom, $uname, $namespace, $what);
 3297:     my ($first) = split(/:/, $qresult);
 3298:     if($first ne "error") {
 3299: 	
 3300: 	if ($cipher) {
 3301: 	    my $cmdlength=length($qresult);
 3302: 	    $qresult.="         ";
 3303: 	    my $encqresult='';
 3304: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 3305: 		$encqresult.= unpack("H16", 
 3306: 				     $cipher->encrypt(substr($qresult,
 3307: 							     $encidx,
 3308: 							     8)));
 3309: 	    }
 3310: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
 3311: 	} else {
 3312: 		&Failure( $client, "error:no_key\n", $userinput);
 3313: 	    }
 3314:     } else {
 3315: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
 3316: 
 3317:     }
 3318:     
 3319:     return 1;
 3320: }
 3321: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
 3322: 
 3323: #
 3324: #   Deletes a key in a user profile database.
 3325: #   
 3326: #   Parameters:
 3327: #       $cmd                  - Command keyword (del).
 3328: #       $tail                 - Command tail.  IN this case a colon
 3329: #                               separated list containing:
 3330: #                               The domain and user that identifies uniquely
 3331: #                               the identity of the user.
 3332: #                               The profile namespace (name of the profile
 3333: #                               database file).
 3334: #                               & separated list of keywords to delete.
 3335: #       $client              - File open on client socket.
 3336: # Returns:
 3337: #     1   - Continue processing
 3338: #     0   - Exit server.
 3339: #
 3340: #
 3341: sub delete_profile_entry {
 3342:     my ($cmd, $tail, $client) = @_;
 3343: 
 3344:     my $userinput = "cmd:$tail";
 3345: 
 3346:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 3347:     chomp($what);
 3348:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3349: 				 &GDBM_WRCREAT(),
 3350: 				 "D",$what);
 3351:     if ($hashref) {
 3352:         my @keys=split(/\&/,$what);
 3353: 	foreach my $key (@keys) {
 3354: 	    delete($hashref->{$key});
 3355: 	}
 3356: 	if (&untie_user_hash($hashref)) {
 3357: 	    &Reply($client, "ok\n", $userinput);
 3358: 	} else {
 3359: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3360: 		    "while attempting del\n", $userinput);
 3361: 	}
 3362:     } else {
 3363: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3364: 		 "while attempting del\n", $userinput);
 3365:     }
 3366:     return 1;
 3367: }
 3368: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
 3369: 
 3370: #
 3371: #  List the set of keys that are defined in a profile database file.
 3372: #  A successful reply from this will contain an & separated list of
 3373: #  the keys. 
 3374: # Parameters:
 3375: #     $cmd              - Command request (keys).
 3376: #     $tail             - Remainder of the request, a colon separated
 3377: #                         list containing domain/user that identifies the
 3378: #                         user being queried, and the database namespace
 3379: #                         (database filename essentially).
 3380: #     $client           - File open on the client.
 3381: #  Returns:
 3382: #    1    - Continue processing.
 3383: #    0    - Exit the server.
 3384: #
 3385: sub get_profile_keys {
 3386:     my ($cmd, $tail, $client) = @_;
 3387: 
 3388:     my $userinput = "$cmd:$tail";
 3389: 
 3390:     my ($udom,$uname,$namespace)=split(/:/,$tail);
 3391:     my $qresult='';
 3392:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3393: 				  &GDBM_READER());
 3394:     if ($hashref) {
 3395: 	foreach my $key (keys %$hashref) {
 3396: 	    $qresult.="$key&";
 3397: 	}
 3398: 	if (&untie_user_hash($hashref)) {
 3399: 	    $qresult=~s/\&$//;
 3400: 	    &Reply($client, \$qresult, $userinput);
 3401: 	} else {
 3402: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3403: 		    "while attempting keys\n", $userinput);
 3404: 	}
 3405:     } else {
 3406: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3407: 		 "while attempting keys\n", $userinput);
 3408:     }
 3409:    
 3410:     return 1;
 3411: }
 3412: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
 3413: 
 3414: #
 3415: #   Dump the contents of a user profile database.
 3416: #   Note that this constitutes a very large covert channel too since
 3417: #   the dump will return sensitive information that is not encrypted.
 3418: #   The naive security assumption is that the session negotiation ensures
 3419: #   our client is trusted and I don't believe that's assured at present.
 3420: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
 3421: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
 3422: # 
 3423: #  Parameters:
 3424: #     $cmd           - The command request keyword (currentdump).
 3425: #     $tail          - Remainder of the request, consisting of a colon
 3426: #                      separated list that has the domain/username and
 3427: #                      the namespace to dump (database file).
 3428: #     $client        - file open on the remote client.
 3429: # Returns:
 3430: #     1    - Continue processing.
 3431: #     0    - Exit the server.
 3432: #
 3433: sub dump_profile_database {
 3434:     my ($cmd, $tail, $client) = @_;
 3435: 
 3436:     my $res = LONCAPA::Lond::dump_profile_database($tail);
 3437: 
 3438:     if ($res =~ /^error:/) {
 3439:         Failure($client, \$res, "$cmd:$tail");
 3440:     } else {
 3441:         Reply($client, \$res, "$cmd:$tail");
 3442:     }
 3443: 
 3444:     return 1;  
 3445: 
 3446:     #TODO remove 
 3447:     my $userinput = "$cmd:$tail";
 3448:    
 3449:     my ($udom,$uname,$namespace) = split(/:/,$tail);
 3450:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3451: 				 &GDBM_READER());
 3452:     if ($hashref) {
 3453: 	# Structure of %data:
 3454: 	# $data{$symb}->{$parameter}=$value;
 3455: 	# $data{$symb}->{'v.'.$parameter}=$version;
 3456: 	# since $parameter will be unescaped, we do not
 3457:  	# have to worry about silly parameter names...
 3458: 	
 3459:         my $qresult='';
 3460: 	my %data = ();                     # A hash of anonymous hashes..
 3461: 	while (my ($key,$value) = each(%$hashref)) {
 3462: 	    my ($v,$symb,$param) = split(/:/,$key);
 3463: 	    next if ($v eq 'version' || $symb eq 'keys');
 3464: 	    next if (exists($data{$symb}) && 
 3465: 		     exists($data{$symb}->{$param}) &&
 3466: 		     $data{$symb}->{'v.'.$param} > $v);
 3467: 	    $data{$symb}->{$param}=$value;
 3468: 	    $data{$symb}->{'v.'.$param}=$v;
 3469: 	}
 3470: 	if (&untie_user_hash($hashref)) {
 3471: 	    while (my ($symb,$param_hash) = each(%data)) {
 3472: 		while(my ($param,$value) = each (%$param_hash)){
 3473: 		    next if ($param =~ /^v\./);       # Ignore versions...
 3474: 		    #
 3475: 		    #   Just dump the symb=value pairs separated by &
 3476: 		    #
 3477: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
 3478: 		}
 3479: 	    }
 3480: 	    chop($qresult);
 3481: 	    &Reply($client , \$qresult, $userinput);
 3482: 	} else {
 3483: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 3484: 		     "while attempting currentdump\n", $userinput);
 3485: 	}
 3486:     } else {
 3487: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3488: 		"while attempting currentdump\n", $userinput);
 3489:     }
 3490: 
 3491:     return 1;
 3492: }
 3493: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
 3494: 
 3495: #
 3496: #   Dump a profile database with an optional regular expression
 3497: #   to match against the keys.  In this dump, no effort is made
 3498: #   to separate symb from version information. Presumably the
 3499: #   databases that are dumped by this command are of a different
 3500: #   structure.  Need to look at this and improve the documentation of
 3501: #   both this and the currentdump handler.
 3502: # Parameters:
 3503: #    $cmd                     - The command keyword.
 3504: #    $tail                    - All of the characters after the $cmd:
 3505: #                               These are expected to be a colon
 3506: #                               separated list containing:
 3507: #                               domain/user - identifying the user.
 3508: #                               namespace   - identifying the database.
 3509: #                               regexp      - optional regular expression
 3510: #                                             that is matched against
 3511: #                                             database keywords to do
 3512: #                                             selective dumps.
 3513: #                               range       - optional range of entries
 3514: #                                             e.g., 10-20 would return the
 3515: #                                             10th to 19th items, etc.  
 3516: #   $client                   - Channel open on the client.
 3517: # Returns:
 3518: #    1    - Continue processing.
 3519: # Side effects:
 3520: #    response is written to $client.
 3521: #
 3522: sub dump_with_regexp {
 3523:     my ($cmd, $tail, $client) = @_;
 3524: 
 3525:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
 3526:     
 3527:     if ($res =~ /^error:/) {
 3528:         Failure($client, \$res, "$cmd:$tail");
 3529:     } else {
 3530:         Reply($client, \$res, "$cmd:$tail");
 3531:     }
 3532: 
 3533:     return 1;
 3534: }
 3535: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
 3536: 
 3537: #  Store a set of key=value pairs associated with a versioned name.
 3538: #
 3539: #  Parameters:
 3540: #    $cmd                - Request command keyword.
 3541: #    $tail               - Tail of the request.  This is a colon
 3542: #                          separated list containing:
 3543: #                          domain/user - User and authentication domain.
 3544: #                          namespace   - Name of the database being modified
 3545: #                          rid         - Resource keyword to modify.
 3546: #                          what        - new value associated with rid.
 3547: #                          laststore   - (optional) version=timestamp
 3548: #                                        for most recent transaction for rid
 3549: #                                        in namespace, when cstore was called
 3550: #
 3551: #    $client             - Socket open on the client.
 3552: #
 3553: #
 3554: #  Returns:
 3555: #      1 (keep on processing).
 3556: #  Side-Effects:
 3557: #    Writes to the client
 3558: #    Successful storage will cause either 'ok', or, if $laststore was included
 3559: #    in the tail of the request, and the version number for the last transaction
 3560: #    is larger than the version in $laststore, delay:$numtrans , where $numtrans
 3561: #    is the number of store evevnts recorded for rid in namespace since
 3562: #    lonnet::store() was called by the client.
 3563: #
 3564: sub store_handler {
 3565:     my ($cmd, $tail, $client) = @_;
 3566:  
 3567:     my $userinput = "$cmd:$tail";
 3568:     chomp($tail);
 3569:     my ($udom,$uname,$namespace,$rid,$what,$laststore) =split(/:/,$tail);
 3570:     if ($namespace ne 'roles') {
 3571: 
 3572: 	my @pairs=split(/\&/,$what);
 3573: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
 3574: 				       &GDBM_WRCREAT(), "S",
 3575: 				       "$rid:$what");
 3576: 	if ($hashref) {
 3577: 	    my $now = time;
 3578:             my $numtrans;
 3579:             if ($laststore) {
 3580:                 my ($previousversion,$previoustime) = split(/\=/,$laststore);
 3581:                 my ($lastversion,$lasttime) = (0,0);
 3582:                 $lastversion = $hashref->{"version:$rid"};
 3583:                 if ($lastversion) {
 3584:                     $lasttime = $hashref->{"$lastversion:$rid:timestamp"};
 3585:                 }
 3586:                 if (($previousversion) && ($previousversion !~ /\D/)) {
 3587:                     if (($lastversion > $previousversion) && ($lasttime >= $previoustime)) {
 3588:                         $numtrans = $lastversion - $previousversion;
 3589:                     }
 3590:                 } elsif ($lastversion) {
 3591:                     $numtrans = $lastversion;
 3592:                 }
 3593:                 if ($numtrans) {
 3594:                     $numtrans =~ s/D//g;
 3595:                 }
 3596:             }
 3597: 	    $hashref->{"version:$rid"}++;
 3598: 	    my $version=$hashref->{"version:$rid"};
 3599: 	    my $allkeys=''; 
 3600: 	    foreach my $pair (@pairs) {
 3601: 		my ($key,$value)=split(/=/,$pair);
 3602: 		$allkeys.=$key.':';
 3603: 		$hashref->{"$version:$rid:$key"}=$value;
 3604: 	    }
 3605: 	    $hashref->{"$version:$rid:timestamp"}=$now;
 3606: 	    $allkeys.='timestamp';
 3607: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
 3608: 	    if (&untie_user_hash($hashref)) {
 3609:                 my $msg = 'ok';
 3610:                 if ($numtrans) {
 3611:                     $msg = 'delay:'.$numtrans;
 3612:                 }
 3613: 		&Reply($client, "$msg\n", $userinput);
 3614: 	    } else {
 3615: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3616: 			"while attempting store\n", $userinput);
 3617: 	    }
 3618: 	} else {
 3619: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3620: 		     "while attempting store\n", $userinput);
 3621: 	}
 3622:     } else {
 3623: 	&Failure($client, "refused\n", $userinput);
 3624:     }
 3625: 
 3626:     return 1;
 3627: }
 3628: &register_handler("store", \&store_handler, 0, 1, 0);
 3629: 
 3630: #  Modify a set of key=value pairs associated with a versioned name.
 3631: #
 3632: #  Parameters:
 3633: #    $cmd                - Request command keyword.
 3634: #    $tail               - Tail of the request.  This is a colon
 3635: #                          separated list containing:
 3636: #                          domain/user - User and authentication domain.
 3637: #                          namespace   - Name of the database being modified
 3638: #                          rid         - Resource keyword to modify.
 3639: #                          v           - Version item to modify
 3640: #                          what        - new value associated with rid.
 3641: #
 3642: #    $client             - Socket open on the client.
 3643: #
 3644: #
 3645: #  Returns:
 3646: #      1 (keep on processing).
 3647: #  Side-Effects:
 3648: #    Writes to the client
 3649: sub putstore_handler {
 3650:     my ($cmd, $tail, $client) = @_;
 3651:  
 3652:     my $userinput = "$cmd:$tail";
 3653: 
 3654:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
 3655:     if ($namespace ne 'roles') {
 3656: 
 3657: 	chomp($what);
 3658: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
 3659: 				       &GDBM_WRCREAT(), "M",
 3660: 				       "$rid:$v:$what");
 3661: 	if ($hashref) {
 3662: 	    my $now = time;
 3663: 	    my %data = &hash_extract($what);
 3664: 	    my @allkeys;
 3665: 	    while (my($key,$value) = each(%data)) {
 3666: 		push(@allkeys,$key);
 3667: 		$hashref->{"$v:$rid:$key"} = $value;
 3668: 	    }
 3669: 	    my $allkeys = join(':',@allkeys);
 3670: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
 3671: 
 3672: 	    if (&untie_user_hash($hashref)) {
 3673: 		&Reply($client, "ok\n", $userinput);
 3674: 	    } else {
 3675: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3676: 			"while attempting store\n", $userinput);
 3677: 	    }
 3678: 	} else {
 3679: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3680: 		     "while attempting store\n", $userinput);
 3681: 	}
 3682:     } else {
 3683: 	&Failure($client, "refused\n", $userinput);
 3684:     }
 3685: 
 3686:     return 1;
 3687: }
 3688: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
 3689: 
 3690: sub hash_extract {
 3691:     my ($str)=@_;
 3692:     my %hash;
 3693:     foreach my $pair (split(/\&/,$str)) {
 3694: 	my ($key,$value)=split(/=/,$pair);
 3695: 	$hash{$key}=$value;
 3696:     }
 3697:     return (%hash);
 3698: }
 3699: sub hash_to_str {
 3700:     my ($hash_ref)=@_;
 3701:     my $str;
 3702:     foreach my $key (keys(%$hash_ref)) {
 3703: 	$str.=$key.'='.$hash_ref->{$key}.'&';
 3704:     }
 3705:     $str=~s/\&$//;
 3706:     return $str;
 3707: }
 3708: 
 3709: #
 3710: #  Dump out all versions of a resource that has key=value pairs associated
 3711: # with it for each version.  These resources are built up via the store
 3712: # command.
 3713: #
 3714: #  Parameters:
 3715: #     $cmd               - Command keyword.
 3716: #     $tail              - Remainder of the request which consists of:
 3717: #                          domain/user   - User and auth. domain.
 3718: #                          namespace     - name of resource database.
 3719: #                          rid           - Resource id.
 3720: #    $client             - socket open on the client.
 3721: #
 3722: # Returns:
 3723: #      1  indicating the caller should not yet exit.
 3724: # Side-effects:
 3725: #   Writes a reply to the client.
 3726: #   The reply is a string of the following shape:
 3727: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
 3728: #    Where the 1 above represents version 1.
 3729: #    this continues for all pairs of keys in all versions.
 3730: #
 3731: #
 3732: #    
 3733: #
 3734: sub restore_handler {
 3735:     my ($cmd, $tail, $client) = @_;
 3736: 
 3737:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
 3738:     my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
 3739:     $namespace=~s/\//\_/g;
 3740:     $namespace = &LONCAPA::clean_username($namespace);
 3741: 
 3742:     chomp($rid);
 3743:     my $qresult='';
 3744:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
 3745:     if ($hashref) {
 3746: 	my $version=$hashref->{"version:$rid"};
 3747: 	$qresult.="version=$version&";
 3748: 	my $scope;
 3749: 	for ($scope=1;$scope<=$version;$scope++) {
 3750: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
 3751: 	    my @keys=split(/:/,$vkeys);
 3752: 	    my $key;
 3753: 	    $qresult.="$scope:keys=$vkeys&";
 3754: 	    foreach $key (@keys) {
 3755: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
 3756: 	    }                                  
 3757: 	}
 3758: 	if (&untie_user_hash($hashref)) {
 3759: 	    $qresult=~s/\&$//;
 3760: 	    &Reply( $client, \$qresult, $userinput);
 3761: 	} else {
 3762: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3763: 		    "while attempting restore\n", $userinput);
 3764: 	}
 3765:     } else {
 3766: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3767: 		"while attempting restore\n", $userinput);
 3768:     }
 3769:   
 3770:     return 1;
 3771: 
 3772: 
 3773: }
 3774: &register_handler("restore", \&restore_handler, 0,1,0);
 3775: 
 3776: #
 3777: #   Add a chat message to a synchronous discussion board.
 3778: #
 3779: # Parameters:
 3780: #    $cmd                - Request keyword.
 3781: #    $tail               - Tail of the command. A colon separated list
 3782: #                          containing:
 3783: #                          cdom    - Domain on which the chat board lives
 3784: #                          cnum    - Course containing the chat board.
 3785: #                          newpost - Body of the posting.
 3786: #                          group   - Optional group, if chat board is only 
 3787: #                                    accessible in a group within the course 
 3788: #   $client              - Socket open on the client.
 3789: # Returns:
 3790: #   1    - Indicating caller should keep on processing.
 3791: #
 3792: # Side-effects:
 3793: #   writes a reply to the client.
 3794: #
 3795: #
 3796: sub send_chat_handler {
 3797:     my ($cmd, $tail, $client) = @_;
 3798: 
 3799:     
 3800:     my $userinput = "$cmd:$tail";
 3801: 
 3802:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
 3803:     &chat_add($cdom,$cnum,$newpost,$group);
 3804:     &Reply($client, "ok\n", $userinput);
 3805: 
 3806:     return 1;
 3807: }
 3808: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
 3809: 
 3810: #
 3811: #   Retrieve the set of chat messages from a discussion board.
 3812: #
 3813: #  Parameters:
 3814: #    $cmd             - Command keyword that initiated the request.
 3815: #    $tail            - Remainder of the request after the command
 3816: #                       keyword.  In this case a colon separated list of
 3817: #                       chat domain    - Which discussion board.
 3818: #                       chat id        - Discussion thread(?)
 3819: #                       domain/user    - Authentication domain and username
 3820: #                                        of the requesting person.
 3821: #                       group          - Optional course group containing
 3822: #                                        the board.      
 3823: #   $client           - Socket open on the client program.
 3824: # Returns:
 3825: #    1     - continue processing
 3826: # Side effects:
 3827: #    Response is written to the client.
 3828: #
 3829: sub retrieve_chat_handler {
 3830:     my ($cmd, $tail, $client) = @_;
 3831: 
 3832: 
 3833:     my $userinput = "$cmd:$tail";
 3834: 
 3835:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
 3836:     my $reply='';
 3837:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
 3838: 	$reply.=&escape($_).':';
 3839:     }
 3840:     $reply=~s/\:$//;
 3841:     &Reply($client, \$reply, $userinput);
 3842: 
 3843: 
 3844:     return 1;
 3845: }
 3846: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
 3847: 
 3848: #
 3849: #  Initiate a query of an sql database.  SQL query repsonses get put in
 3850: #  a file for later retrieval.  This prevents sql query results from
 3851: #  bottlenecking the system.  Note that with loncnew, perhaps this is
 3852: #  less of an issue since multiple outstanding requests can be concurrently
 3853: #  serviced.
 3854: #
 3855: #  Parameters:
 3856: #     $cmd       - COmmand keyword that initiated the request.
 3857: #     $tail      - Remainder of the command after the keyword.
 3858: #                  For this function, this consists of a query and
 3859: #                  3 arguments that are self-documentingly labelled
 3860: #                  in the original arg1, arg2, arg3.
 3861: #     $client    - Socket open on the client.
 3862: # Return:
 3863: #    1   - Indicating processing should continue.
 3864: # Side-effects:
 3865: #    a reply is written to $client.
 3866: #
 3867: sub send_query_handler {
 3868:     my ($cmd, $tail, $client) = @_;
 3869: 
 3870: 
 3871:     my $userinput = "$cmd:$tail";
 3872: 
 3873:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
 3874:     $query=~s/\n*$//g;
 3875:     &Reply($client, "". &sql_reply("$clientname\&$query".
 3876: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
 3877: 	  $userinput);
 3878:     
 3879:     return 1;
 3880: }
 3881: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
 3882: 
 3883: #
 3884: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
 3885: #   The query is submitted via a "querysend" transaction.
 3886: #   There it is passed on to the lonsql daemon, queued and issued to
 3887: #   mysql.
 3888: #     This transaction is invoked when the sql transaction is complete
 3889: #   it stores the query results in flie and indicates query completion.
 3890: #   presumably local software then fetches this response... I'm guessing
 3891: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
 3892: #   lonsql on completion of the query interacts with the lond of our
 3893: #   client to do a query reply storing two files:
 3894: #    - id     - The results of the query.
 3895: #    - id.end - Indicating the transaction completed. 
 3896: #    NOTE: id is a unique id assigned to the query and querysend time.
 3897: # Parameters:
 3898: #    $cmd        - Command keyword that initiated this request.
 3899: #    $tail       - Remainder of the tail.  In this case that's a colon
 3900: #                  separated list containing the query Id and the 
 3901: #                  results of the query.
 3902: #    $client     - Socket open on the client.
 3903: # Return:
 3904: #    1           - Indicating that we should continue processing.
 3905: # Side effects:
 3906: #    ok written to the client.
 3907: #
 3908: sub reply_query_handler {
 3909:     my ($cmd, $tail, $client) = @_;
 3910: 
 3911: 
 3912:     my $userinput = "$cmd:$tail";
 3913: 
 3914:     my ($id,$reply)=split(/:/,$tail); 
 3915:     my $store;
 3916:     my $execdir=$perlvar{'lonDaemons'};
 3917:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
 3918: 	$reply=~s/\&/\n/g;
 3919: 	print $store $reply;
 3920: 	close $store;
 3921: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
 3922: 	print $store2 "done\n";
 3923: 	close $store2;
 3924: 	&Reply($client, "ok\n", $userinput);
 3925:     } else {
 3926: 	&Failure($client, "error: ".($!+0)
 3927: 		." IO::File->new Failed ".
 3928: 		"while attempting queryreply\n", $userinput);
 3929:     }
 3930:  
 3931: 
 3932:     return 1;
 3933: }
 3934: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
 3935: 
 3936: #
 3937: #  Process the courseidput request.  Not quite sure what this means
 3938: #  at the system level sense.  It appears a gdbm file in the 
 3939: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
 3940: #  a set of entries made in that database.
 3941: #
 3942: # Parameters:
 3943: #   $cmd      - The command keyword that initiated this request.
 3944: #   $tail     - Tail of the command.  In this case consists of a colon
 3945: #               separated list contaning the domain to apply this to and
 3946: #               an ampersand separated list of keyword=value pairs.
 3947: #               Each value is a colon separated list that includes:  
 3948: #               description, institutional code and course owner.
 3949: #               For backward compatibility with versions included
 3950: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
 3951: #               code and/or course owner are preserved from the existing 
 3952: #               record when writing a new record in response to 1.1 or 
 3953: #               1.2 implementations of lonnet::flushcourselogs().   
 3954: #                      
 3955: #   $client   - Socket open on the client.
 3956: # Returns:
 3957: #   1    - indicating that processing should continue
 3958: #
 3959: # Side effects:
 3960: #   reply is written to the client.
 3961: #
 3962: sub put_course_id_handler {
 3963:     my ($cmd, $tail, $client) = @_;
 3964: 
 3965: 
 3966:     my $userinput = "$cmd:$tail";
 3967: 
 3968:     my ($udom, $what) = split(/:/, $tail,2);
 3969:     chomp($what);
 3970:     my $now=time;
 3971:     my @pairs=split(/\&/,$what);
 3972: 
 3973:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 3974:     if ($hashref) {
 3975: 	foreach my $pair (@pairs) {
 3976:             my ($key,$courseinfo) = split(/=/,$pair,2);
 3977:             $courseinfo =~ s/=/:/g;
 3978:             if (defined($hashref->{$key})) {
 3979:                 my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
 3980:                 if (ref($value) eq 'HASH') {
 3981:                     my @items = ('description','inst_code','owner','type');
 3982:                     my @new_items = split(/:/,$courseinfo,-1);
 3983:                     my %storehash; 
 3984:                     for (my $i=0; $i<@new_items; $i++) {
 3985:                         $storehash{$items[$i]} = &unescape($new_items[$i]);
 3986:                     }
 3987:                     $hashref->{$key} = 
 3988:                         &Apache::lonnet::freeze_escape(\%storehash);
 3989:                     my $unesc_key = &unescape($key);
 3990:                     $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
 3991:                     next;
 3992:                 }
 3993:             }
 3994:             my @current_items = split(/:/,$hashref->{$key},-1);
 3995:             shift(@current_items); # remove description
 3996:             pop(@current_items);   # remove last access
 3997:             my $numcurrent = scalar(@current_items);
 3998:             if ($numcurrent > 3) {
 3999:                 $numcurrent = 3;
 4000:             }
 4001:             my @new_items = split(/:/,$courseinfo,-1);
 4002:             my $numnew = scalar(@new_items);
 4003:             if ($numcurrent > 0) {
 4004:                 if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2 
 4005:                     for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
 4006:                         $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
 4007:                     }
 4008:                 }
 4009:             }
 4010:             $hashref->{$key}=$courseinfo.':'.$now;
 4011: 	}
 4012: 	if (&untie_domain_hash($hashref)) {
 4013: 	    &Reply( $client, "ok\n", $userinput);
 4014: 	} else {
 4015: 	    &Failure($client, "error: ".($!+0)
 4016: 		     ." untie(GDBM) Failed ".
 4017: 		     "while attempting courseidput\n", $userinput);
 4018: 	}
 4019:     } else {
 4020: 	&Failure($client, "error: ".($!+0)
 4021: 		 ." tie(GDBM) Failed ".
 4022: 		 "while attempting courseidput\n", $userinput);
 4023:     }
 4024: 
 4025:     return 1;
 4026: }
 4027: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
 4028: 
 4029: sub put_course_id_hash_handler {
 4030:     my ($cmd, $tail, $client) = @_;
 4031:     my $userinput = "$cmd:$tail";
 4032:     my ($udom,$mode,$what) = split(/:/, $tail,3);
 4033:     chomp($what);
 4034:     my $now=time;
 4035:     my @pairs=split(/\&/,$what);
 4036:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 4037:     if ($hashref) {
 4038:         foreach my $pair (@pairs) {
 4039:             my ($key,$value)=split(/=/,$pair);
 4040:             my $unesc_key = &unescape($key);
 4041:             if ($mode ne 'timeonly') {
 4042:                 if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
 4043:                     my $curritems = &Apache::lonnet::thaw_unescape($key); 
 4044:                     if (ref($curritems) ne 'HASH') {
 4045:                         my @current_items = split(/:/,$hashref->{$key},-1);
 4046:                         my $lasttime = pop(@current_items);
 4047:                         $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
 4048:                     } else {
 4049:                         $hashref->{&escape('lasttime:'.$unesc_key)} = '';
 4050:                     }
 4051:                 } 
 4052:                 $hashref->{$key} = $value;
 4053:             }
 4054:             if ($mode ne 'notime') {
 4055:                 $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
 4056:             }
 4057:         }
 4058:         if (&untie_domain_hash($hashref)) {
 4059:             &Reply($client, "ok\n", $userinput);
 4060:         } else {
 4061:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4062:                      "while attempting courseidputhash\n", $userinput);
 4063:         }
 4064:     } else {
 4065:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 4066:                   "while attempting courseidputhash\n", $userinput);
 4067:     }
 4068:     return 1;
 4069: }
 4070: &register_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
 4071: 
 4072: #  Retrieves the value of a course id resource keyword pattern
 4073: #  defined since a starting date.  Both the starting date and the
 4074: #  keyword pattern are optional.  If the starting date is not supplied it
 4075: #  is treated as the beginning of time.  If the pattern is not found,
 4076: #  it is treatred as "." matching everything.
 4077: #
 4078: #  Parameters:
 4079: #     $cmd     - Command keyword that resulted in us being dispatched.
 4080: #     $tail    - The remainder of the command that, in this case, consists
 4081: #                of a colon separated list of:
 4082: #                 domain   - The domain in which the course database is 
 4083: #                            defined.
 4084: #                 since    - Optional parameter describing the minimum
 4085: #                            time of definition(?) of the resources that
 4086: #                            will match the dump.
 4087: #                 description - regular expression that is used to filter
 4088: #                            the dump.  Only keywords matching this regexp
 4089: #                            will be used.
 4090: #                 institutional code - optional supplied code to filter 
 4091: #                            the dump. Only courses with an institutional code 
 4092: #                            that match the supplied code will be returned.
 4093: #                 owner    - optional supplied username and domain of owner to
 4094: #                            filter the dump.  Only courses for which the course
 4095: #                            owner matches the supplied username and/or domain
 4096: #                            will be returned. Pre-2.2.0 legacy entries from 
 4097: #                            nohist_courseiddump will only contain usernames.
 4098: #                 type     - optional parameter for selection 
 4099: #                 regexp_ok - if 1 or -1 allow the supplied institutional code
 4100: #                            filter to behave as a regular expression:
 4101: #	                      1 will not exclude the course if the instcode matches the RE 
 4102: #                            -1 will exclude the course if the instcode matches the RE
 4103: #                 rtn_as_hash - whether to return the information available for
 4104: #                            each matched item as a frozen hash of all 
 4105: #                            key, value pairs in the item's hash, or as a 
 4106: #                            colon-separated list of (in order) description,
 4107: #                            institutional code, and course owner.
 4108: #                 selfenrollonly - filter by courses allowing self-enrollment  
 4109: #                                  now or in the future (selfenrollonly = 1).
 4110: #                 catfilter - filter by course category, assigned to a course 
 4111: #                             using manually defined categories (i.e., not
 4112: #                             self-cataloging based on on institutional code).   
 4113: #                 showhidden - include course in results even if course  
 4114: #                              was set to be excluded from course catalog (DC only).
 4115: #                 caller -  if set to 'coursecatalog', courses set to be hidden
 4116: #                           from course catalog will be excluded from results (unless
 4117: #                           overridden by "showhidden".
 4118: #                 cloner - escaped username:domain of course cloner (if picking course to
 4119: #                          clone).
 4120: #                 cc_clone_list - escaped comma separated list of courses for which 
 4121: #                                 course cloner has active CC role (and so can clone
 4122: #                                 automatically).
 4123: #                 cloneonly - filter by courses for which cloner has rights to clone.
 4124: #                 createdbefore - include courses for which creation date preceeded this date.
 4125: #                 createdafter - include courses for which creation date followed this date.
 4126: #                 creationcontext - include courses created in specified context 
 4127: #
 4128: #                 domcloner - flag to indicate if user can create CCs in course's domain.
 4129: #                             If so, ability to clone course is automatic.
 4130: #                 hasuniquecode - filter by courses for which a six character unique code has 
 4131: #                                 been set.
 4132: #
 4133: #     $client  - The socket open on the client.
 4134: # Returns:
 4135: #    1     - Continue processing.
 4136: # Side Effects:
 4137: #   a reply is written to $client.
 4138: sub dump_course_id_handler {
 4139:     my ($cmd, $tail, $client) = @_;
 4140: 
 4141:     my $res = LONCAPA::Lond::dump_course_id_handler($tail);
 4142:     if ($res =~ /^error:/) {
 4143:         Failure($client, \$res, "$cmd:$tail");
 4144:     } else {
 4145:         Reply($client, \$res, "$cmd:$tail");
 4146:     }
 4147: 
 4148:     return 1;  
 4149: 
 4150:     #TODO remove
 4151:     my $userinput = "$cmd:$tail";
 4152: 
 4153:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
 4154:         $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
 4155:         $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
 4156:         $creationcontext,$domcloner,$hasuniquecode) =split(/:/,$tail);
 4157:     my $now = time;
 4158:     my ($cloneruname,$clonerudom,%cc_clone);
 4159:     if (defined($description)) {
 4160: 	$description=&unescape($description);
 4161:     } else {
 4162: 	$description='.';
 4163:     }
 4164:     if (defined($instcodefilter)) {
 4165:         $instcodefilter=&unescape($instcodefilter);
 4166:     } else {
 4167:         $instcodefilter='.';
 4168:     }
 4169:     my ($ownerunamefilter,$ownerdomfilter);
 4170:     if (defined($ownerfilter)) {
 4171:         $ownerfilter=&unescape($ownerfilter);
 4172:         if ($ownerfilter ne '.' && defined($ownerfilter)) {
 4173:             if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
 4174:                  $ownerunamefilter = $1;
 4175:                  $ownerdomfilter = $2;
 4176:             } else {
 4177:                 $ownerunamefilter = $ownerfilter;
 4178:                 $ownerdomfilter = '';
 4179:             }
 4180:         }
 4181:     } else {
 4182:         $ownerfilter='.';
 4183:     }
 4184: 
 4185:     if (defined($coursefilter)) {
 4186:         $coursefilter=&unescape($coursefilter);
 4187:     } else {
 4188:         $coursefilter='.';
 4189:     }
 4190:     if (defined($typefilter)) {
 4191:         $typefilter=&unescape($typefilter);
 4192:     } else {
 4193:         $typefilter='.';
 4194:     }
 4195:     if (defined($regexp_ok)) {
 4196:         $regexp_ok=&unescape($regexp_ok);
 4197:     }
 4198:     if (defined($catfilter)) {
 4199:         $catfilter=&unescape($catfilter);
 4200:     }
 4201:     if (defined($cloner)) {
 4202:         $cloner = &unescape($cloner);
 4203:         ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/); 
 4204:     }
 4205:     if (defined($cc_clone_list)) {
 4206:         $cc_clone_list = &unescape($cc_clone_list);
 4207:         my @cc_cloners = split('&',$cc_clone_list);
 4208:         foreach my $cid (@cc_cloners) {
 4209:             my ($clonedom,$clonenum) = split(':',$cid);
 4210:             next if ($clonedom ne $udom); 
 4211:             $cc_clone{$clonedom.'_'.$clonenum} = 1;
 4212:         } 
 4213:     }
 4214:     if ($createdbefore ne '') {
 4215:         $createdbefore = &unescape($createdbefore);
 4216:     } else {
 4217:        $createdbefore = 0;
 4218:     }
 4219:     if ($createdafter ne '') {
 4220:         $createdafter = &unescape($createdafter);
 4221:     } else {
 4222:         $createdafter = 0;
 4223:     }
 4224:     if ($creationcontext ne '') {
 4225:         $creationcontext = &unescape($creationcontext);
 4226:     } else {
 4227:         $creationcontext = '.';
 4228:     }
 4229:     unless ($hasuniquecode) {
 4230:         $hasuniquecode = '.';
 4231:     }
 4232:     my $unpack = 1;
 4233:     if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' && 
 4234:         $typefilter eq '.') {
 4235:         $unpack = 0;
 4236:     }
 4237:     if (!defined($since)) { $since=0; }
 4238:     my $qresult='';
 4239:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 4240:     if ($hashref) {
 4241: 	while (my ($key,$value) = each(%$hashref)) {
 4242:             my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
 4243:                 %unesc_val,$selfenroll_end,$selfenroll_types,$created,
 4244:                 $context);
 4245:             $unesc_key = &unescape($key);
 4246:             if ($unesc_key =~ /^lasttime:/) {
 4247:                 next;
 4248:             } else {
 4249:                 $lasttime_key = &escape('lasttime:'.$unesc_key);
 4250:             }
 4251:             if ($hashref->{$lasttime_key} ne '') {
 4252:                 $lasttime = $hashref->{$lasttime_key};
 4253:                 next if ($lasttime<$since);
 4254:             }
 4255:             my ($canclone,$valchange);
 4256:             my $items = &Apache::lonnet::thaw_unescape($value);
 4257:             if (ref($items) eq 'HASH') {
 4258:                 if ($hashref->{$lasttime_key} eq '') {
 4259:                     next if ($since > 1);
 4260:                 }
 4261:                 $is_hash =  1;
 4262:                 if ($domcloner) {
 4263:                     $canclone = 1;
 4264:                 } elsif (defined($clonerudom)) {
 4265:                     if ($items->{'cloners'}) {
 4266:                         my @cloneable = split(',',$items->{'cloners'});
 4267:                         if (@cloneable) {
 4268:                             if (grep(/^\*$/,@cloneable))  {
 4269:                                 $canclone = 1;
 4270:                             } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
 4271:                                 $canclone = 1;
 4272:                             } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
 4273:                                 $canclone = 1;
 4274:                             }
 4275:                         }
 4276:                         unless ($canclone) {
 4277:                             if ($cloneruname ne '' && $clonerudom ne '') {
 4278:                                 if ($cc_clone{$unesc_key}) {
 4279:                                     $canclone = 1;
 4280:                                     $items->{'cloners'} .= ','.$cloneruname.':'.
 4281:                                                            $clonerudom;
 4282:                                     $valchange = 1;
 4283:                                 }
 4284:                             }
 4285:                         }
 4286:                     } elsif (defined($cloneruname)) {
 4287:                         if ($cc_clone{$unesc_key}) {
 4288:                             $canclone = 1;
 4289:                             $items->{'cloners'} = $cloneruname.':'.$clonerudom;
 4290:                             $valchange = 1;
 4291:                         }
 4292:                         unless ($canclone) {
 4293:                             if ($items->{'owner'} =~ /:/) {
 4294:                                 if ($items->{'owner'} eq $cloner) {
 4295:                                     $canclone = 1;
 4296:                                 }
 4297:                             } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
 4298:                                 $canclone = 1;
 4299:                             }
 4300:                             if ($canclone) {
 4301:                                 $items->{'cloners'} = $cloneruname.':'.$clonerudom;
 4302:                                 $valchange = 1;
 4303:                             }
 4304:                         }
 4305:                     }
 4306:                 }
 4307:                 if ($unpack || !$rtn_as_hash) {
 4308:                     $unesc_val{'descr'} = $items->{'description'};
 4309:                     $unesc_val{'inst_code'} = $items->{'inst_code'};
 4310:                     $unesc_val{'owner'} = $items->{'owner'};
 4311:                     $unesc_val{'type'} = $items->{'type'};
 4312:                     $unesc_val{'cloners'} = $items->{'cloners'};
 4313:                     $unesc_val{'created'} = $items->{'created'};
 4314:                     $unesc_val{'context'} = $items->{'context'};
 4315:                 }
 4316:                 $selfenroll_types = $items->{'selfenroll_types'};
 4317:                 $selfenroll_end = $items->{'selfenroll_end_date'};
 4318:                 $created = $items->{'created'};
 4319:                 $context = $items->{'context'};
 4320:                 if ($hasuniquecode ne '.') {
 4321:                     next unless ($items->{'uniquecode'});
 4322:                 }
 4323:                 if ($selfenrollonly) {
 4324:                     next if (!$selfenroll_types);
 4325:                     if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
 4326:                         next;
 4327:                     }
 4328:                 }
 4329:                 if ($creationcontext ne '.') {
 4330:                     next if (($context ne '') && ($context ne $creationcontext));  
 4331:                 }
 4332:                 if ($createdbefore > 0) {
 4333:                     next if (($created eq '') || ($created > $createdbefore));   
 4334:                 }
 4335:                 if ($createdafter > 0) {
 4336:                     next if (($created eq '') || ($created <= $createdafter)); 
 4337:                 }
 4338:                 if ($catfilter ne '') {
 4339:                     next if ($items->{'categories'} eq '');
 4340:                     my @categories = split('&',$items->{'categories'}); 
 4341:                     next if (@categories == 0);
 4342:                     my @subcats = split('&',$catfilter);
 4343:                     my $matchcat = 0;
 4344:                     foreach my $cat (@categories) {
 4345:                         if (grep(/^\Q$cat\E$/,@subcats)) {
 4346:                             $matchcat = 1;
 4347:                             last;
 4348:                         }
 4349:                     }
 4350:                     next if (!$matchcat);
 4351:                 }
 4352:                 if ($caller eq 'coursecatalog') {
 4353:                     if ($items->{'hidefromcat'} eq 'yes') {
 4354:                         next if !$showhidden;
 4355:                     }
 4356:                 }
 4357:             } else {
 4358:                 next if ($catfilter ne '');
 4359:                 next if ($selfenrollonly);
 4360:                 next if ($createdbefore || $createdafter);
 4361:                 next if ($creationcontext ne '.');
 4362:                 if ((defined($clonerudom)) && (defined($cloneruname)))  {
 4363:                     if ($cc_clone{$unesc_key}) {
 4364:                         $canclone = 1;
 4365:                         $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
 4366:                     }
 4367:                 }
 4368:                 $is_hash =  0;
 4369:                 my @courseitems = split(/:/,$value);
 4370:                 $lasttime = pop(@courseitems);
 4371:                 if ($hashref->{$lasttime_key} eq '') {
 4372:                     next if ($lasttime<$since);
 4373:                 }
 4374: 	        ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
 4375:             }
 4376:             if ($cloneonly) {
 4377:                next unless ($canclone);
 4378:             }
 4379:             my $match = 1;
 4380: 	    if ($description ne '.') {
 4381:                 if (!$is_hash) {
 4382:                     $unesc_val{'descr'} = &unescape($val{'descr'});
 4383:                 }
 4384:                 if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
 4385:                     $match = 0;
 4386:                 }
 4387:             }
 4388:             if ($instcodefilter ne '.') {
 4389:                 if (!$is_hash) {
 4390:                     $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
 4391:                 }
 4392:                 if ($regexp_ok == 1) {
 4393:                     if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
 4394:                         $match = 0;
 4395:                     }
 4396:                 } elsif ($regexp_ok == -1) {
 4397:                     if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
 4398:                         $match = 0;
 4399:                     }
 4400:                 } else {
 4401:                     if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
 4402:                         $match = 0;
 4403:                     }
 4404:                 }
 4405: 	    }
 4406:             if ($ownerfilter ne '.') {
 4407:                 if (!$is_hash) {
 4408:                     $unesc_val{'owner'} = &unescape($val{'owner'});
 4409:                 }
 4410:                 if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
 4411:                     if ($unesc_val{'owner'} =~ /:/) {
 4412:                         if (eval{$unesc_val{'owner'} !~ 
 4413:                              /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
 4414:                             $match = 0;
 4415:                         } 
 4416:                     } else {
 4417:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
 4418:                             $match = 0;
 4419:                         }
 4420:                     }
 4421:                 } elsif ($ownerunamefilter ne '') {
 4422:                     if ($unesc_val{'owner'} =~ /:/) {
 4423:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
 4424:                              $match = 0;
 4425:                         }
 4426:                     } else {
 4427:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
 4428:                             $match = 0;
 4429:                         }
 4430:                     }
 4431:                 } elsif ($ownerdomfilter ne '') {
 4432:                     if ($unesc_val{'owner'} =~ /:/) {
 4433:                         if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
 4434:                              $match = 0;
 4435:                         }
 4436:                     } else {
 4437:                         if ($ownerdomfilter ne $udom) {
 4438:                             $match = 0;
 4439:                         }
 4440:                     }
 4441:                 }
 4442:             }
 4443:             if ($coursefilter ne '.') {
 4444:                 if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
 4445:                     $match = 0;
 4446:                 }
 4447:             }
 4448:             if ($typefilter ne '.') {
 4449:                 if (!$is_hash) {
 4450:                     $unesc_val{'type'} = &unescape($val{'type'});
 4451:                 }
 4452:                 if ($unesc_val{'type'} eq '') {
 4453:                     if ($typefilter ne 'Course') {
 4454:                         $match = 0;
 4455:                     }
 4456:                 } else {
 4457:                     if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
 4458:                         $match = 0;
 4459:                     }
 4460:                 }
 4461:             }
 4462:             if ($match == 1) {
 4463:                 if ($rtn_as_hash) {
 4464:                     if ($is_hash) {
 4465:                         if ($valchange) {
 4466:                             my $newvalue = &Apache::lonnet::freeze_escape($items);
 4467:                             $qresult.=$key.'='.$newvalue.'&';
 4468:                         } else {
 4469:                             $qresult.=$key.'='.$value.'&';
 4470:                         }
 4471:                     } else {
 4472:                         my %rtnhash = ( 'description' => &unescape($val{'descr'}),
 4473:                                         'inst_code' => &unescape($val{'inst_code'}),
 4474:                                         'owner'     => &unescape($val{'owner'}),
 4475:                                         'type'      => &unescape($val{'type'}),
 4476:                                         'cloners'   => &unescape($val{'cloners'}),
 4477:                                       );
 4478:                         my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
 4479:                         $qresult.=$key.'='.$items.'&';
 4480:                     }
 4481:                 } else {
 4482:                     if ($is_hash) {
 4483:                         $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
 4484:                                     &escape($unesc_val{'inst_code'}).':'.
 4485:                                     &escape($unesc_val{'owner'}).'&';
 4486:                     } else {
 4487:                         $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
 4488:                                     ':'.$val{'owner'}.'&';
 4489:                     }
 4490:                 }
 4491:             }
 4492: 	}
 4493: 	if (&untie_domain_hash($hashref)) {
 4494: 	    chop($qresult);
 4495: 	    &Reply($client, \$qresult, $userinput);
 4496: 	} else {
 4497: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4498: 		    "while attempting courseiddump\n", $userinput);
 4499: 	}
 4500:     } else {
 4501: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 4502: 		"while attempting courseiddump\n", $userinput);
 4503:     }
 4504:     return 1;
 4505: }
 4506: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
 4507: 
 4508: sub course_lastaccess_handler {
 4509:     my ($cmd, $tail, $client) = @_;
 4510:     my $userinput = "$cmd:$tail";
 4511:     my ($cdom,$cnum) = split(':',$tail); 
 4512:     my (%lastaccess,$qresult);
 4513:     my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
 4514:     if ($hashref) {
 4515:         while (my ($key,$value) = each(%$hashref)) {
 4516:             my ($unesc_key,$lasttime);
 4517:             $unesc_key = &unescape($key);
 4518:             if ($cnum) {
 4519:                 next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
 4520:             }
 4521:             if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
 4522:                 $lastaccess{$1} = $value;
 4523:             } else {
 4524:                 my $items = &Apache::lonnet::thaw_unescape($value);
 4525:                 if (ref($items) eq 'HASH') {
 4526:                     unless ($lastaccess{$unesc_key}) {
 4527:                         $lastaccess{$unesc_key} = '';
 4528:                     }
 4529:                 } else {
 4530:                     my @courseitems = split(':',$value);
 4531:                     $lastaccess{$unesc_key} = pop(@courseitems);
 4532:                 }
 4533:             }
 4534:         }
 4535:         foreach my $cid (sort(keys(%lastaccess))) {
 4536:             $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&'; 
 4537:         }
 4538:         if (&untie_domain_hash($hashref)) {
 4539:             if ($qresult) {
 4540:                 chop($qresult);
 4541:             }
 4542:             &Reply($client, \$qresult, $userinput);
 4543:         } else {
 4544:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4545:                     "while attempting lastacourseaccess\n", $userinput);
 4546:         }
 4547:     } else {
 4548:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 4549:                 "while attempting lastcourseaccess\n", $userinput);
 4550:     }
 4551:     return 1;
 4552: }
 4553: &register_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
 4554: 
 4555: #
 4556: # Puts an unencrypted entry in a namespace db file at the domain level 
 4557: #
 4558: # Parameters:
 4559: #    $cmd      - The command that got us here.
 4560: #    $tail     - Tail of the command (remaining parameters).
 4561: #    $client   - File descriptor connected to client.
 4562: # Returns
 4563: #     0        - Requested to exit, caller should shut down.
 4564: #     1        - Continue processing.
 4565: #  Side effects:
 4566: #     reply is written to $client.
 4567: #
 4568: sub put_domain_handler {
 4569:     my ($cmd,$tail,$client) = @_;
 4570: 
 4571:     my $userinput = "$cmd:$tail";
 4572: 
 4573:     my ($udom,$namespace,$what) =split(/:/,$tail,3);
 4574:     chomp($what);
 4575:     my @pairs=split(/\&/,$what);
 4576:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
 4577:                                    "P", $what);
 4578:     if ($hashref) {
 4579:         foreach my $pair (@pairs) {
 4580:             my ($key,$value)=split(/=/,$pair);
 4581:             $hashref->{$key}=$value;
 4582:         }
 4583:         if (&untie_domain_hash($hashref)) {
 4584:             &Reply($client, "ok\n", $userinput);
 4585:         } else {
 4586:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4587:                      "while attempting putdom\n", $userinput);
 4588:         }
 4589:     } else {
 4590:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 4591:                   "while attempting putdom\n", $userinput);
 4592:     }
 4593: 
 4594:     return 1;
 4595: }
 4596: &register_handler("putdom", \&put_domain_handler, 0, 1, 0);
 4597: 
 4598: # Updates one or more entries in clickers.db file at the domain level
 4599: #
 4600: # Parameters:
 4601: #    $cmd      - The command that got us here.
 4602: #    $tail     - Tail of the command (remaining parameters).
 4603: #                In this case a colon separated list containing:
 4604: #                (a) the domain for which we are updating the entries,
 4605: #                (b) the action required -- add or del -- and
 4606: #                (c) a &-separated list of entries to add or delete.
 4607: #    $client   - File descriptor connected to client.
 4608: # Returns
 4609: #     1        - Continue processing.
 4610: #     0        - Requested to exit, caller should shut down.
 4611: #  Side effects:
 4612: #     reply is written to $client.
 4613: #
 4614: 
 4615: 
 4616: sub update_clickers {
 4617:     my ($cmd, $tail, $client)  = @_;
 4618: 
 4619:     my $userinput = "$cmd:$tail";
 4620:     my ($udom,$action,$what) =split(/:/,$tail,3);
 4621:     chomp($what);
 4622: 
 4623:     my $hashref = &tie_domain_hash($udom, "clickers", &GDBM_WRCREAT(),
 4624:                                  "U","$action:$what");
 4625: 
 4626:     if (!$hashref) {
 4627:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 4628:                   "while attempting updateclickers\n", $userinput);
 4629:         return 1;
 4630:     }
 4631: 
 4632:     my @pairs=split(/\&/,$what);
 4633:     foreach my $pair (@pairs) {
 4634:         my ($key,$value)=split(/=/,$pair);
 4635:         if ($action eq 'add') {
 4636:             if (exists($hashref->{$key})) {
 4637:                 my @newvals = split(/,/,&unescape($value));
 4638:                 my @currvals = split(/,/,&unescape($hashref->{$key}));
 4639:                 my @merged = sort(keys(%{{map { $_ => 1 } (@newvals,@currvals)}}));
 4640:                 $hashref->{$key}=&escape(join(',',@merged));
 4641:             } else {
 4642:                 $hashref->{$key}=$value;
 4643:             }
 4644:         } elsif ($action eq 'del') {
 4645:             if (exists($hashref->{$key})) {
 4646:                 my %current;
 4647:                 map { $current{$_} = 1; } split(/,/,&unescape($hashref->{$key}));
 4648:                 map { delete($current{$_}); } split(/,/,&unescape($value));
 4649:                 if (keys(%current)) {
 4650:                     $hashref->{$key}=&escape(join(',',sort(keys(%current))));
 4651:                 } else {
 4652:                     delete($hashref->{$key});
 4653:                 }
 4654:             }
 4655:         }
 4656:     }
 4657:     if (&untie_user_hash($hashref)) {
 4658:         &Reply( $client, "ok\n", $userinput);
 4659:     } else {
 4660:         &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 4661:                  "while attempting put\n",
 4662:                  $userinput);
 4663:     }
 4664:     return 1;
 4665: }
 4666: &register_handler("updateclickers", \&update_clickers, 0, 1, 0);
 4667: 
 4668: 
 4669: # Deletes one or more entries in a namespace db file at the domain level
 4670: #
 4671: # Parameters:
 4672: #    $cmd      - The command that got us here.
 4673: #    $tail     - Tail of the command (remaining parameters).
 4674: #                In this case a colon separated list containing:
 4675: #                (a) the domain for which we are deleting the entries,
 4676: #                (b) &-separated list of keys to delete.  
 4677: #    $client   - File descriptor connected to client.
 4678: # Returns
 4679: #     1        - Continue processing.
 4680: #     0        - Requested to exit, caller should shut down.
 4681: #  Side effects:
 4682: #     reply is written to $client.
 4683: #
 4684: 
 4685: sub del_domain_handler {
 4686:     my ($cmd,$tail,$client) = @_;
 4687: 
 4688:     my $userinput = "$cmd:$tail";
 4689: 
 4690:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
 4691:     chomp($what);
 4692:     my $hashref = &tie_domain_hash($udom,$namespace,&GDBM_WRCREAT(),
 4693:                                    "D", $what);
 4694:     if ($hashref) {
 4695:         my @keys=split(/\&/,$what);
 4696:         foreach my $key (@keys) {
 4697:             delete($hashref->{$key});
 4698:         }
 4699:         if (&untie_user_hash($hashref)) {
 4700:             &Reply($client, "ok\n", $userinput);
 4701:         } else {
 4702:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4703:                     "while attempting deldom\n", $userinput);
 4704:         }
 4705:     } else {
 4706:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 4707:                  "while attempting deldom\n", $userinput);
 4708:     }
 4709:     return 1;
 4710: }
 4711: &register_handler("deldom", \&del_domain_handler, 0, 1, 0);
 4712: 
 4713: 
 4714: # Unencrypted get from the namespace database file at the domain level.
 4715: # This function retrieves a keyed item from a specific named database in the
 4716: # domain directory.
 4717: #
 4718: # Parameters:
 4719: #   $cmd             - Command request keyword (get).
 4720: #   $tail            - Tail of the command.  This is a colon separated list
 4721: #                      consisting of the domain and the 'namespace' 
 4722: #                      which selects the gdbm file to do the lookup in,
 4723: #                      & separated list of keys to lookup.  Note that
 4724: #                      the values are returned as an & separated list too.
 4725: #   $client          - File descriptor open on the client.
 4726: # Returns:
 4727: #   1       - Continue processing.
 4728: #   0       - Exit.
 4729: #  Side effects:
 4730: #     reply is written to $client.
 4731: #
 4732: 
 4733: sub get_domain_handler {
 4734:     my ($cmd, $tail, $client) = @_;
 4735: 
 4736: 
 4737:     my $userinput = "$client:$tail";
 4738: 
 4739:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
 4740:     chomp($what);
 4741:     my @queries=split(/\&/,$what);
 4742:     my $qresult='';
 4743:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
 4744:     if ($hashref) {
 4745:         for (my $i=0;$i<=$#queries;$i++) {
 4746:             $qresult.="$hashref->{$queries[$i]}&";
 4747:         }
 4748:         if (&untie_domain_hash($hashref)) {
 4749:             $qresult=~s/\&$//;
 4750:             &Reply($client, \$qresult, $userinput);
 4751:         } else {
 4752:             &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 4753:                       "while attempting getdom\n",$userinput);
 4754:         }
 4755:     } else {
 4756:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 4757:                  "while attempting getdom\n",$userinput);
 4758:     }
 4759: 
 4760:     return 1;
 4761: }
 4762: &register_handler("getdom", \&get_domain_handler, 0, 1, 0);
 4763: 
 4764: #
 4765: #  Puts an id to a domains id database. 
 4766: #
 4767: #  Parameters:
 4768: #   $cmd     - The command that triggered us.
 4769: #   $tail    - Remainder of the request other than the command. This is a 
 4770: #              colon separated list containing:
 4771: #              $domain  - The domain for which we are writing the id.
 4772: #              $pairs  - The id info to write... this is and & separated list
 4773: #                        of keyword=value.
 4774: #   $client  - Socket open on the client.
 4775: #  Returns:
 4776: #    1   - Continue processing.
 4777: #  Side effects:
 4778: #     reply is written to $client.
 4779: #
 4780: sub put_id_handler {
 4781:     my ($cmd,$tail,$client) = @_;
 4782: 
 4783: 
 4784:     my $userinput = "$cmd:$tail";
 4785: 
 4786:     my ($udom,$what)=split(/:/,$tail);
 4787:     chomp($what);
 4788:     my @pairs=split(/\&/,$what);
 4789:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
 4790: 				   "P", $what);
 4791:     if ($hashref) {
 4792: 	foreach my $pair (@pairs) {
 4793: 	    my ($key,$value)=split(/=/,$pair);
 4794: 	    $hashref->{$key}=$value;
 4795: 	}
 4796: 	if (&untie_domain_hash($hashref)) {
 4797: 	    &Reply($client, "ok\n", $userinput);
 4798: 	} else {
 4799: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4800: 		     "while attempting idput\n", $userinput);
 4801: 	}
 4802:     } else {
 4803: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 4804: 		  "while attempting idput\n", $userinput);
 4805:     }
 4806: 
 4807:     return 1;
 4808: }
 4809: &register_handler("idput", \&put_id_handler, 0, 1, 0);
 4810: 
 4811: #
 4812: #  Retrieves a set of id values from the id database.
 4813: #  Returns an & separated list of results, one for each requested id to the
 4814: #  client.
 4815: #
 4816: # Parameters:
 4817: #   $cmd       - Command keyword that caused us to be dispatched.
 4818: #   $tail      - Tail of the command.  Consists of a colon separated:
 4819: #               domain - the domain whose id table we dump
 4820: #               ids      Consists of an & separated list of
 4821: #                        id keywords whose values will be fetched.
 4822: #                        nonexisting keywords will have an empty value.
 4823: #   $client    - Socket open on the client.
 4824: #
 4825: # Returns:
 4826: #    1 - indicating processing should continue.
 4827: # Side effects:
 4828: #   An & separated list of results is written to $client.
 4829: #
 4830: sub get_id_handler {
 4831:     my ($cmd, $tail, $client) = @_;
 4832: 
 4833:     
 4834:     my $userinput = "$client:$tail";
 4835:     
 4836:     my ($udom,$what)=split(/:/,$tail);
 4837:     chomp($what);
 4838:     my @queries=split(/\&/,$what);
 4839:     my $qresult='';
 4840:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
 4841:     if ($hashref) {
 4842: 	for (my $i=0;$i<=$#queries;$i++) {
 4843: 	    $qresult.="$hashref->{$queries[$i]}&";
 4844: 	}
 4845: 	if (&untie_domain_hash($hashref)) {
 4846: 	    $qresult=~s/\&$//;
 4847: 	    &Reply($client, \$qresult, $userinput);
 4848: 	} else {
 4849: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 4850: 		      "while attempting idget\n",$userinput);
 4851: 	}
 4852:     } else {
 4853: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 4854: 		 "while attempting idget\n",$userinput);
 4855:     }
 4856:     
 4857:     return 1;
 4858: }
 4859: &register_handler("idget", \&get_id_handler, 0, 1, 0);
 4860: 
 4861: #   Deletes one or more ids in a domain's id database.
 4862: #
 4863: #   Parameters:
 4864: #       $cmd                  - Command keyword (iddel).
 4865: #       $tail                 - Command tail.  In this case a colon
 4866: #                               separated list containing:
 4867: #                               The domain for which we are deleting the id(s).
 4868: #                               &-separated list of id(s) to delete.
 4869: #       $client               - File open on client socket.
 4870: # Returns:
 4871: #     1   - Continue processing
 4872: #     0   - Exit server.
 4873: #     
 4874: #
 4875: 
 4876: sub del_id_handler {
 4877:     my ($cmd,$tail,$client) = @_;
 4878: 
 4879:     my $userinput = "$cmd:$tail";
 4880: 
 4881:     my ($udom,$what)=split(/:/,$tail);
 4882:     chomp($what);
 4883:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
 4884:                                    "D", $what);
 4885:     if ($hashref) {
 4886:         my @keys=split(/\&/,$what);
 4887:         foreach my $key (@keys) {
 4888:             delete($hashref->{$key});
 4889:         }
 4890:         if (&untie_user_hash($hashref)) {
 4891:             &Reply($client, "ok\n", $userinput);
 4892:         } else {
 4893:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4894:                     "while attempting iddel\n", $userinput);
 4895:         }
 4896:     } else {
 4897:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 4898:                  "while attempting iddel\n", $userinput);
 4899:     }
 4900:     return 1;
 4901: }
 4902: &register_handler("iddel", \&del_id_handler, 0, 1, 0);
 4903: 
 4904: #
 4905: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
 4906: #
 4907: # Parameters
 4908: #   $cmd       - Command keyword that caused us to be dispatched.
 4909: #   $tail      - Tail of the command.  Consists of a colon separated:
 4910: #               domain - the domain whose dcmail we are recording
 4911: #               email    Consists of key=value pair 
 4912: #                        where key is unique msgid
 4913: #                        and value is message (in XML)
 4914: #   $client    - Socket open on the client.
 4915: #
 4916: # Returns:
 4917: #    1 - indicating processing should continue.
 4918: # Side effects
 4919: #     reply is written to $client.
 4920: #
 4921: sub put_dcmail_handler {
 4922:     my ($cmd,$tail,$client) = @_;
 4923:     my $userinput = "$cmd:$tail";
 4924: 
 4925: 
 4926:     my ($udom,$what)=split(/:/,$tail);
 4927:     chomp($what);
 4928:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
 4929:     if ($hashref) {
 4930:         my ($key,$value)=split(/=/,$what);
 4931:         $hashref->{$key}=$value;
 4932:     }
 4933:     if (&untie_domain_hash($hashref)) {
 4934:         &Reply($client, "ok\n", $userinput);
 4935:     } else {
 4936:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4937:                  "while attempting dcmailput\n", $userinput);
 4938:     }
 4939:     return 1;
 4940: }
 4941: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
 4942: 
 4943: #
 4944: # Retrieves broadcast e-mail from nohist_dcmail database
 4945: # Returns to client an & separated list of key=value pairs,
 4946: # where key is msgid and value is message information.
 4947: #
 4948: # Parameters
 4949: #   $cmd       - Command keyword that caused us to be dispatched.
 4950: #   $tail      - Tail of the command.  Consists of a colon separated:
 4951: #               domain - the domain whose dcmail table we dump
 4952: #               startfilter - beginning of time window 
 4953: #               endfilter - end of time window
 4954: #               sendersfilter - & separated list of username:domain 
 4955: #                 for senders to search for.
 4956: #   $client    - Socket open on the client.
 4957: #
 4958: # Returns:
 4959: #    1 - indicating processing should continue.
 4960: # Side effects
 4961: #     reply (& separated list of msgid=messageinfo pairs) is 
 4962: #     written to $client.
 4963: #
 4964: sub dump_dcmail_handler {
 4965:     my ($cmd, $tail, $client) = @_;
 4966:                                                                                 
 4967:     my $userinput = "$cmd:$tail";
 4968:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
 4969:     chomp($sendersfilter);
 4970:     my @senders = ();
 4971:     if (defined($startfilter)) {
 4972:         $startfilter=&unescape($startfilter);
 4973:     } else {
 4974:         $startfilter='.';
 4975:     }
 4976:     if (defined($endfilter)) {
 4977:         $endfilter=&unescape($endfilter);
 4978:     } else {
 4979:         $endfilter='.';
 4980:     }
 4981:     if (defined($sendersfilter)) {
 4982:         $sendersfilter=&unescape($sendersfilter);
 4983: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
 4984:     }
 4985: 
 4986:     my $qresult='';
 4987:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
 4988:     if ($hashref) {
 4989:         while (my ($key,$value) = each(%$hashref)) {
 4990:             my $match = 1;
 4991:             my ($timestamp,$subj,$uname,$udom) = 
 4992: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
 4993:             $subj = &unescape($subj);
 4994:             unless ($startfilter eq '.' || !defined($startfilter)) {
 4995:                 if ($timestamp < $startfilter) {
 4996:                     $match = 0;
 4997:                 }
 4998:             }
 4999:             unless ($endfilter eq '.' || !defined($endfilter)) {
 5000:                 if ($timestamp > $endfilter) {
 5001:                     $match = 0;
 5002:                 }
 5003:             }
 5004:             unless (@senders < 1) {
 5005:                 unless (grep/^$uname:$udom$/,@senders) {
 5006:                     $match = 0;
 5007:                 }
 5008:             }
 5009:             if ($match == 1) {
 5010:                 $qresult.=$key.'='.$value.'&';
 5011:             }
 5012:         }
 5013:         if (&untie_domain_hash($hashref)) {
 5014:             chop($qresult);
 5015:             &Reply($client, \$qresult, $userinput);
 5016:         } else {
 5017:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5018:                     "while attempting dcmaildump\n", $userinput);
 5019:         }
 5020:     } else {
 5021:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 5022:                 "while attempting dcmaildump\n", $userinput);
 5023:     }
 5024:     return 1;
 5025: }
 5026: 
 5027: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
 5028: 
 5029: #
 5030: # Puts domain roles in nohist_domainroles database
 5031: #
 5032: # Parameters
 5033: #   $cmd       - Command keyword that caused us to be dispatched.
 5034: #   $tail      - Tail of the command.  Consists of a colon separated:
 5035: #               domain - the domain whose roles we are recording  
 5036: #               role -   Consists of key=value pair
 5037: #                        where key is unique role
 5038: #                        and value is start/end date information
 5039: #   $client    - Socket open on the client.
 5040: #
 5041: # Returns:
 5042: #    1 - indicating processing should continue.
 5043: # Side effects
 5044: #     reply is written to $client.
 5045: #
 5046: 
 5047: sub put_domainroles_handler {
 5048:     my ($cmd,$tail,$client) = @_;
 5049: 
 5050:     my $userinput = "$cmd:$tail";
 5051:     my ($udom,$what)=split(/:/,$tail);
 5052:     chomp($what);
 5053:     my @pairs=split(/\&/,$what);
 5054:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
 5055:     if ($hashref) {
 5056:         foreach my $pair (@pairs) {
 5057:             my ($key,$value)=split(/=/,$pair);
 5058:             $hashref->{$key}=$value;
 5059:         }
 5060:         if (&untie_domain_hash($hashref)) {
 5061:             &Reply($client, "ok\n", $userinput);
 5062:         } else {
 5063:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5064:                      "while attempting domroleput\n", $userinput);
 5065:         }
 5066:     } else {
 5067:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 5068:                   "while attempting domroleput\n", $userinput);
 5069:     }
 5070:                                                                                   
 5071:     return 1;
 5072: }
 5073: 
 5074: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
 5075: 
 5076: #
 5077: # Retrieves domain roles from nohist_domainroles database
 5078: # Returns to client an & separated list of key=value pairs,
 5079: # where key is role and value is start and end date information.
 5080: #
 5081: # Parameters
 5082: #   $cmd       - Command keyword that caused us to be dispatched.
 5083: #   $tail      - Tail of the command.  Consists of a colon separated:
 5084: #               domain - the domain whose domain roles table we dump
 5085: #   $client    - Socket open on the client.
 5086: #
 5087: # Returns:
 5088: #    1 - indicating processing should continue.
 5089: # Side effects
 5090: #     reply (& separated list of role=start/end info pairs) is
 5091: #     written to $client.
 5092: #
 5093: sub dump_domainroles_handler {
 5094:     my ($cmd, $tail, $client) = @_;
 5095:                                                                                            
 5096:     my $userinput = "$cmd:$tail";
 5097:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
 5098:     chomp($rolesfilter);
 5099:     my @roles = ();
 5100:     if (defined($startfilter)) {
 5101:         $startfilter=&unescape($startfilter);
 5102:     } else {
 5103:         $startfilter='.';
 5104:     }
 5105:     if (defined($endfilter)) {
 5106:         $endfilter=&unescape($endfilter);
 5107:     } else {
 5108:         $endfilter='.';
 5109:     }
 5110:     if (defined($rolesfilter)) {
 5111:         $rolesfilter=&unescape($rolesfilter);
 5112: 	@roles = split(/\&/,$rolesfilter);
 5113:     }
 5114: 
 5115:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
 5116:     if ($hashref) {
 5117:         my $qresult = '';
 5118:         while (my ($key,$value) = each(%$hashref)) {
 5119:             my $match = 1;
 5120:             my ($end,$start) = split(/:/,&unescape($value));
 5121:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
 5122:             unless (@roles < 1) {
 5123:                 unless (grep/^\Q$trole\E$/,@roles) {
 5124:                     $match = 0;
 5125:                     next;
 5126:                 }
 5127:             }
 5128:             unless ($startfilter eq '.' || !defined($startfilter)) {
 5129:                 if ((defined($start)) && ($start >= $startfilter)) {
 5130:                     $match = 0;
 5131:                     next;
 5132:                 }
 5133:             }
 5134:             unless ($endfilter eq '.' || !defined($endfilter)) {
 5135:                 if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
 5136:                     $match = 0;
 5137:                     next;
 5138:                 }
 5139:             }
 5140:             if ($match == 1) {
 5141:                 $qresult.=$key.'='.$value.'&';
 5142:             }
 5143:         }
 5144:         if (&untie_domain_hash($hashref)) {
 5145:             chop($qresult);
 5146:             &Reply($client, \$qresult, $userinput);
 5147:         } else {
 5148:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5149:                     "while attempting domrolesdump\n", $userinput);
 5150:         }
 5151:     } else {
 5152:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 5153:                 "while attempting domrolesdump\n", $userinput);
 5154:     }
 5155:     return 1;
 5156: }
 5157: 
 5158: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
 5159: 
 5160: 
 5161: #  Process the tmpput command I'm not sure what this does.. Seems to
 5162: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
 5163: # where Id is the client's ip concatenated with a sequence number.
 5164: # The file will contain some value that is passed in.  Is this e.g.
 5165: # a login token?
 5166: #
 5167: # Parameters:
 5168: #    $cmd     - The command that got us dispatched.
 5169: #    $tail    - The remainder of the request following $cmd:
 5170: #               In this case this will be the contents of the file.
 5171: #    $client  - Socket connected to the client.
 5172: # Returns:
 5173: #    1 indicating processing can continue.
 5174: # Side effects:
 5175: #   A file is created in the local filesystem.
 5176: #   A reply is sent to the client.
 5177: sub tmp_put_handler {
 5178:     my ($cmd, $what, $client) = @_;
 5179: 
 5180:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
 5181: 
 5182:     my ($record,$context) = split(/:/,$what);
 5183:     if ($context ne '') {
 5184:         chomp($context);
 5185:         $context = &unescape($context);
 5186:     }
 5187:     my ($id,$store);
 5188:     $tmpsnum++;
 5189:     if (($context eq 'resetpw') || ($context eq 'createaccount')) {
 5190:         $id = &md5_hex(&md5_hex(time.{}.rand().$$));
 5191:     } else {
 5192:         $id = $$.'_'.$clientip.'_'.$tmpsnum;
 5193:     }
 5194:     $id=~s/\W/\_/g;
 5195:     $record=~s/\n//g;
 5196:     my $execdir=$perlvar{'lonDaemons'};
 5197:     if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
 5198: 	print $store $record;
 5199: 	close $store;
 5200: 	&Reply($client, \$id, $userinput);
 5201:     } else {
 5202: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
 5203: 		  "while attempting tmpput\n", $userinput);
 5204:     }
 5205:     return 1;
 5206:   
 5207: }
 5208: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
 5209: 
 5210: #   Processes the tmpget command.  This command returns the contents
 5211: #  of a temporary resource file(?) created via tmpput.
 5212: #
 5213: # Paramters:
 5214: #    $cmd      - Command that got us dispatched.
 5215: #    $id       - Tail of the command, contain the id of the resource
 5216: #                we want to fetch.
 5217: #    $client   - socket open on the client.
 5218: # Return:
 5219: #    1         - Inidcating processing can continue.
 5220: # Side effects:
 5221: #   A reply is sent to the client.
 5222: #
 5223: sub tmp_get_handler {
 5224:     my ($cmd, $id, $client) = @_;
 5225: 
 5226:     my $userinput = "$cmd:$id"; 
 5227:     
 5228: 
 5229:     $id=~s/\W/\_/g;
 5230:     my $store;
 5231:     my $execdir=$perlvar{'lonDaemons'};
 5232:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
 5233: 	my $reply=<$store>;
 5234: 	&Reply( $client, \$reply, $userinput);
 5235: 	close $store;
 5236:     } else {
 5237: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
 5238: 		  "while attempting tmpget\n", $userinput);
 5239:     }
 5240: 
 5241:     return 1;
 5242: }
 5243: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
 5244: 
 5245: #
 5246: #  Process the tmpdel command.  This command deletes a temp resource
 5247: #  created by the tmpput command.
 5248: #
 5249: # Parameters:
 5250: #   $cmd      - Command that got us here.
 5251: #   $id       - Id of the temporary resource created.
 5252: #   $client   - socket open on the client process.
 5253: #
 5254: # Returns:
 5255: #   1     - Indicating processing should continue.
 5256: # Side Effects:
 5257: #   A file is deleted
 5258: #   A reply is sent to the client.
 5259: sub tmp_del_handler {
 5260:     my ($cmd, $id, $client) = @_;
 5261:     
 5262:     my $userinput= "$cmd:$id";
 5263:     
 5264:     chomp($id);
 5265:     $id=~s/\W/\_/g;
 5266:     my $execdir=$perlvar{'lonDaemons'};
 5267:     if (unlink("$execdir/tmp/$id.tmp")) {
 5268: 	&Reply($client, "ok\n", $userinput);
 5269:     } else {
 5270: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
 5271: 		  "while attempting tmpdel\n", $userinput);
 5272:     }
 5273:     
 5274:     return 1;
 5275: 
 5276: }
 5277: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
 5278: 
 5279: #
 5280: #   Processes the setannounce command.  This command
 5281: #   creates a file named announce.txt in the top directory of
 5282: #   the documentn root and sets its contents.  The announce.txt file is
 5283: #   printed in its entirety at the LonCAPA login page.  Note:
 5284: #   once the announcement.txt fileis created it cannot be deleted.
 5285: #   However, setting the contents of the file to empty removes the
 5286: #   announcement from the login page of loncapa so who cares.
 5287: #
 5288: # Parameters:
 5289: #    $cmd          - The command that got us dispatched.
 5290: #    $announcement - The text of the announcement.
 5291: #    $client       - Socket open on the client process.
 5292: # Retunrns:
 5293: #   1             - Indicating request processing should continue
 5294: # Side Effects:
 5295: #   The file {DocRoot}/announcement.txt is created.
 5296: #   A reply is sent to $client.
 5297: #
 5298: sub set_announce_handler {
 5299:     my ($cmd, $announcement, $client) = @_;
 5300:   
 5301:     my $userinput    = "$cmd:$announcement";
 5302: 
 5303:     chomp($announcement);
 5304:     $announcement=&unescape($announcement);
 5305:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
 5306: 				'/announcement.txt')) {
 5307: 	print $store $announcement;
 5308: 	close $store;
 5309: 	&Reply($client, "ok\n", $userinput);
 5310:     } else {
 5311: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
 5312:     }
 5313: 
 5314:     return 1;
 5315: }
 5316: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
 5317: 
 5318: #
 5319: #  Return the version of the daemon.  This can be used to determine
 5320: #  the compatibility of cross version installations or, alternatively to
 5321: #  simply know who's out of date and who isn't.  Note that the version
 5322: #  is returned concatenated with the tail.
 5323: # Parameters:
 5324: #   $cmd        - the request that dispatched to us.
 5325: #   $tail       - Tail of the request (client's version?).
 5326: #   $client     - Socket open on the client.
 5327: #Returns:
 5328: #   1 - continue processing requests.
 5329: # Side Effects:
 5330: #   Replies with version to $client.
 5331: sub get_version_handler {
 5332:     my ($cmd, $tail, $client) = @_;
 5333: 
 5334:     my $userinput  = $cmd.$tail;
 5335:     
 5336:     &Reply($client, &version($userinput)."\n", $userinput);
 5337: 
 5338: 
 5339:     return 1;
 5340: }
 5341: &register_handler("version", \&get_version_handler, 0, 1, 0);
 5342: 
 5343: #  Set the current host and domain.  This is used to support
 5344: #  multihomed systems.  Each IP of the system, or even separate daemons
 5345: #  on the same IP can be treated as handling a separate lonCAPA virtual
 5346: #  machine.  This command selects the virtual lonCAPA.  The client always
 5347: #  knows the right one since it is lonc and it is selecting the domain/system
 5348: #  from the hosts.tab file.
 5349: # Parameters:
 5350: #    $cmd      - Command that dispatched us.
 5351: #    $tail     - Tail of the command (domain/host requested).
 5352: #    $socket   - Socket open on the client.
 5353: #
 5354: # Returns:
 5355: #     1   - Indicates the program should continue to process requests.
 5356: # Side-effects:
 5357: #     The default domain/system context is modified for this daemon.
 5358: #     a reply is sent to the client.
 5359: #
 5360: sub set_virtual_host_handler {
 5361:     my ($cmd, $tail, $socket) = @_;
 5362:   
 5363:     my $userinput  ="$cmd:$tail";
 5364: 
 5365:     &Reply($client, &sethost($userinput)."\n", $userinput);
 5366: 
 5367: 
 5368:     return 1;
 5369: }
 5370: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
 5371: 
 5372: #  Process a request to exit:
 5373: #   - "bye" is sent to the client.
 5374: #   - The client socket is shutdown and closed.
 5375: #   - We indicate to the caller that we should exit.
 5376: # Formal Parameters:
 5377: #   $cmd                - The command that got us here.
 5378: #   $tail               - Tail of the command (empty).
 5379: #   $client             - Socket open on the tail.
 5380: # Returns:
 5381: #   0      - Indicating the program should exit!!
 5382: #
 5383: sub exit_handler {
 5384:     my ($cmd, $tail, $client) = @_;
 5385: 
 5386:     my $userinput = "$cmd:$tail";
 5387: 
 5388:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
 5389:     &Reply($client, "bye\n", $userinput);
 5390:     $client->shutdown(2);        # shutdown the socket forcibly.
 5391:     $client->close();
 5392: 
 5393:     return 0;
 5394: }
 5395: &register_handler("exit", \&exit_handler, 0,1,1);
 5396: &register_handler("init", \&exit_handler, 0,1,1);
 5397: &register_handler("quit", \&exit_handler, 0,1,1);
 5398: 
 5399: #  Determine if auto-enrollment is enabled.
 5400: #  Note that the original had what I believe to be a defect.
 5401: #  The original returned 0 if the requestor was not a registerd client.
 5402: #  It should return "refused".
 5403: # Formal Parameters:
 5404: #   $cmd       - The command that invoked us.
 5405: #   $tail      - The tail of the command (Extra command parameters.
 5406: #   $client    - The socket open on the client that issued the request.
 5407: # Returns:
 5408: #    1         - Indicating processing should continue.
 5409: #
 5410: sub enrollment_enabled_handler {
 5411:     my ($cmd, $tail, $client) = @_;
 5412:     my $userinput = $cmd.":".$tail; # For logging purposes.
 5413: 
 5414:     
 5415:     my ($cdom) = split(/:/, $tail, 2);   # Domain we're asking about.
 5416: 
 5417:     my $outcome  = &localenroll::run($cdom);
 5418:     &Reply($client, \$outcome, $userinput);
 5419: 
 5420:     return 1;
 5421: }
 5422: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
 5423: 
 5424: #
 5425: #   Validate an institutional code used for a LON-CAPA course.          
 5426: #
 5427: # Formal Parameters:
 5428: #   $cmd          - The command request that got us dispatched.
 5429: #   $tail         - The tail of the command.  In this case,
 5430: #                   this is a colon separated set of words that will be split
 5431: #                   into:
 5432: #                        $dom      - The domain for which the check of 
 5433: #                                    institutional course code will occur.
 5434: #
 5435: #                        $instcode - The institutional code for the course
 5436: #                                    being requested, or validated for rights
 5437: #                                    to request.
 5438: #
 5439: #                        $owner    - The course requestor (who will be the
 5440: #                                    course owner, in the form username:domain
 5441: #
 5442: #   $client       - Socket open on the client.
 5443: # Returns:
 5444: #    1           - Indicating processing should continue.
 5445: #
 5446: sub validate_instcode_handler {
 5447:     my ($cmd, $tail, $client) = @_;
 5448:     my $userinput = "$cmd:$tail";
 5449:     my ($dom,$instcode,$owner) = split(/:/, $tail);
 5450:     $instcode = &unescape($instcode);
 5451:     $owner = &unescape($owner);
 5452:     my ($outcome,$description,$credits) = 
 5453:         &localenroll::validate_instcode($dom,$instcode,$owner);
 5454:     my $result = &escape($outcome).'&'.&escape($description).'&'.
 5455:                  &escape($credits);
 5456:     &Reply($client, \$result, $userinput);
 5457: 
 5458:     return 1;
 5459: }
 5460: &register_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
 5461: 
 5462: #   Get the official sections for which auto-enrollment is possible.
 5463: #   Since the admin people won't know about 'unofficial sections' 
 5464: #   we cannot auto-enroll on them.
 5465: # Formal Parameters:
 5466: #    $cmd     - The command request that got us dispatched here.
 5467: #    $tail    - The remainder of the request.  In our case this
 5468: #               will be split into:
 5469: #               $coursecode   - The course name from the admin point of view.
 5470: #               $cdom         - The course's domain(?).
 5471: #    $client  - Socket open on the client.
 5472: # Returns:
 5473: #    1    - Indiciting processing should continue.
 5474: #
 5475: sub get_sections_handler {
 5476:     my ($cmd, $tail, $client) = @_;
 5477:     my $userinput = "$cmd:$tail";
 5478: 
 5479:     my ($coursecode, $cdom) = split(/:/, $tail);
 5480:     my @secs = &localenroll::get_sections($coursecode,$cdom);
 5481:     my $seclist = &escape(join(':',@secs));
 5482: 
 5483:     &Reply($client, \$seclist, $userinput);
 5484:     
 5485: 
 5486:     return 1;
 5487: }
 5488: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
 5489: 
 5490: #   Validate the owner of a new course section.  
 5491: #
 5492: # Formal Parameters:
 5493: #   $cmd      - Command that got us dispatched.
 5494: #   $tail     - the remainder of the command.  For us this consists of a
 5495: #               colon separated string containing:
 5496: #                  $inst    - Course Id from the institutions point of view.
 5497: #                  $owner   - Proposed owner of the course.
 5498: #                  $cdom    - Domain of the course (from the institutions
 5499: #                             point of view?)..
 5500: #   $client   - Socket open on the client.
 5501: #
 5502: # Returns:
 5503: #   1        - Processing should continue.
 5504: #
 5505: sub validate_course_owner_handler {
 5506:     my ($cmd, $tail, $client)  = @_;
 5507:     my $userinput = "$cmd:$tail";
 5508:     my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
 5509:     
 5510:     $owner = &unescape($owner);
 5511:     $coowners = &unescape($coowners);
 5512:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
 5513:     &Reply($client, \$outcome, $userinput);
 5514: 
 5515: 
 5516: 
 5517:     return 1;
 5518: }
 5519: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
 5520: 
 5521: #
 5522: #   Validate a course section in the official schedule of classes
 5523: #   from the institutions point of view (part of autoenrollment).
 5524: #
 5525: # Formal Parameters:
 5526: #   $cmd          - The command request that got us dispatched.
 5527: #   $tail         - The tail of the command.  In this case,
 5528: #                   this is a colon separated set of words that will be split
 5529: #                   into:
 5530: #                        $inst_course_id - The course/section id from the
 5531: #                                          institutions point of view.
 5532: #                        $cdom           - The domain from the institutions
 5533: #                                          point of view.
 5534: #   $client       - Socket open on the client.
 5535: # Returns:
 5536: #    1           - Indicating processing should continue.
 5537: #
 5538: sub validate_course_section_handler {
 5539:     my ($cmd, $tail, $client) = @_;
 5540:     my $userinput = "$cmd:$tail";
 5541:     my ($inst_course_id, $cdom) = split(/:/, $tail);
 5542: 
 5543:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
 5544:     &Reply($client, \$outcome, $userinput);
 5545: 
 5546: 
 5547:     return 1;
 5548: }
 5549: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
 5550: 
 5551: #
 5552: #   Validate course owner's access to enrollment data for specific class section. 
 5553: #   
 5554: #
 5555: # Formal Parameters:
 5556: #    $cmd     - The command request that got us dispatched.
 5557: #    $tail    - The tail of the command.   In this case this is a colon separated
 5558: #               set of words that will be split into:
 5559: #               $inst_class  - Institutional code for the specific class section   
 5560: #               $courseowner - The escaped username:domain of the course owner 
 5561: #               $cdom        - The domain of the course from the institution's
 5562: #                              point of view.
 5563: #    $client  - The socket open on the client.
 5564: # Returns:
 5565: #    1 - continue processing.
 5566: #
 5567: 
 5568: sub validate_class_access_handler {
 5569:     my ($cmd, $tail, $client) = @_;
 5570:     my $userinput = "$cmd:$tail";
 5571:     my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
 5572:     my $owners = &unescape($ownerlist);
 5573:     my $outcome;
 5574:     eval {
 5575: 	local($SIG{__DIE__})='DEFAULT';
 5576: 	$outcome=&localenroll::check_section($inst_class,$owners,$cdom);
 5577:     };
 5578:     &Reply($client,\$outcome, $userinput);
 5579: 
 5580:     return 1;
 5581: }
 5582: &register_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
 5583: 
 5584: #
 5585: #   Create a password for a new LON-CAPA user added by auto-enrollment.
 5586: #   Only used for case where authentication method for new user is localauth
 5587: #
 5588: # Formal Parameters:
 5589: #    $cmd     - The command request that got us dispatched.
 5590: #    $tail    - The tail of the command.   In this case this is a colon separated
 5591: #               set of words that will be split into:
 5592: #               $authparam - An authentication parameter (localauth parameter).
 5593: #               $cdom      - The domain of the course from the institution's
 5594: #                            point of view.
 5595: #    $client  - The socket open on the client.
 5596: # Returns:
 5597: #    1 - continue processing.
 5598: #
 5599: sub create_auto_enroll_password_handler {
 5600:     my ($cmd, $tail, $client) = @_;
 5601:     my $userinput = "$cmd:$tail";
 5602: 
 5603:     my ($authparam, $cdom) = split(/:/, $userinput);
 5604: 
 5605:     my ($create_passwd,$authchk);
 5606:     ($authparam,
 5607:      $create_passwd,
 5608:      $authchk) = &localenroll::create_password($authparam,$cdom);
 5609: 
 5610:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
 5611: 	   $userinput);
 5612: 
 5613: 
 5614:     return 1;
 5615: }
 5616: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
 5617: 		  0, 1, 0);
 5618: 
 5619: sub auto_export_grades_handler {
 5620:     my ($cmd, $tail, $client) = @_;
 5621:     my $userinput = "$cmd:$tail";
 5622:     my ($cdom,$cnum,$info,$data) = split(/:/,$tail);
 5623:     my $inforef = &Apache::lonnet::thaw_unescape($info);
 5624:     my $dataref = &Apache::lonnet::thaw_unescape($data);
 5625:     my ($outcome,$result);;
 5626:     eval {
 5627:         local($SIG{__DIE__})='DEFAULT';
 5628:         my %rtnhash;
 5629:         $outcome=&localenroll::export_grades($cdom,$cnum,$inforef,$dataref,\%rtnhash);
 5630:         if ($outcome eq 'ok') {
 5631:             foreach my $key (keys(%rtnhash)) {
 5632:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
 5633:             }
 5634:             $result =~ s/\&$//;
 5635:         }
 5636:     };
 5637:     if (!$@) {
 5638:         if ($outcome eq 'ok') {
 5639:             if ($cipher) {
 5640:                 my $cmdlength=length($result);
 5641:                 $result.="         ";
 5642:                 my $encresult='';
 5643:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 5644:                     $encresult.= unpack("H16",
 5645:                                         $cipher->encrypt(substr($result,
 5646:                                                                 $encidx,
 5647:                                                                 8)));
 5648:                 }
 5649:                 &Reply( $client, "enc:$cmdlength:$encresult\n", $userinput);
 5650:             } else {
 5651:                 &Failure( $client, "error:no_key\n", $userinput);
 5652:             }
 5653:         } else {
 5654:             &Reply($client, "$outcome\n", $userinput);
 5655:         }
 5656:     } else {
 5657:         &Failure($client,"export_error\n",$userinput);
 5658:     }
 5659:     return 1;
 5660: }
 5661: &register_handler("autoexportgrades", \&auto_export_grades_handler,
 5662:                   0, 1, 0);
 5663: 
 5664: #   Retrieve and remove temporary files created by/during autoenrollment.
 5665: #
 5666: # Formal Parameters:
 5667: #    $cmd      - The command that got us dispatched.
 5668: #    $tail     - The tail of the command.  In our case this is a colon 
 5669: #                separated list that will be split into:
 5670: #                $filename - The name of the file to remove.
 5671: #                            The filename is given as a path relative to
 5672: #                            the LonCAPA temp file directory.
 5673: #    $client   - Socket open on the client.
 5674: #
 5675: # Returns:
 5676: #   1     - Continue processing.
 5677: sub retrieve_auto_file_handler {
 5678:     my ($cmd, $tail, $client)    = @_;
 5679:     my $userinput                = "cmd:$tail";
 5680: 
 5681:     my ($filename)   = split(/:/, $tail);
 5682: 
 5683:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
 5684: 
 5685:     if ($filename =~m{/\.\./}) {
 5686:         &Failure($client, "refused\n", $userinput);
 5687:     } elsif ( (-e $source) && ($filename ne '') ) {
 5688: 	my $reply = '';
 5689: 	if (open(my $fh,$source)) {
 5690: 	    while (<$fh>) {
 5691: 		chomp($_);
 5692: 		$_ =~ s/^\s+//g;
 5693: 		$_ =~ s/\s+$//g;
 5694: 		$reply .= $_;
 5695: 	    }
 5696: 	    close($fh);
 5697: 	    &Reply($client, &escape($reply)."\n", $userinput);
 5698: 
 5699: #   Does this have to be uncommented??!?  (RF).
 5700: #
 5701: #                                unlink($source);
 5702: 	} else {
 5703: 	    &Failure($client, "error\n", $userinput);
 5704: 	}
 5705:     } else {
 5706: 	&Failure($client, "error\n", $userinput);
 5707:     }
 5708:     
 5709: 
 5710:     return 1;
 5711: }
 5712: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
 5713: 
 5714: sub crsreq_checks_handler {
 5715:     my ($cmd, $tail, $client) = @_;
 5716:     my $userinput = "$cmd:$tail";
 5717:     my $dom = $tail;
 5718:     my $result;
 5719:     my @reqtypes = ('official','unofficial','community','textbook','placement');
 5720:     eval {
 5721:         local($SIG{__DIE__})='DEFAULT';
 5722:         my %validations;
 5723:         my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
 5724:                                                    \%validations);
 5725:         if ($response eq 'ok') { 
 5726:             foreach my $key (keys(%validations)) {
 5727:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
 5728:             }
 5729:             $result =~ s/\&$//;
 5730:         } else {
 5731:             $result = 'error';
 5732:         }
 5733:     };
 5734:     if (!$@) {
 5735:         &Reply($client, \$result, $userinput);
 5736:     } else {
 5737:         &Failure($client,"unknown_cmd\n",$userinput);
 5738:     }
 5739:     return 1;
 5740: }
 5741: &register_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
 5742: 
 5743: sub validate_crsreq_handler {
 5744:     my ($cmd, $tail, $client) = @_;
 5745:     my $userinput = "$cmd:$tail";
 5746:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
 5747:     $instcode = &unescape($instcode);
 5748:     $owner = &unescape($owner);
 5749:     $crstype = &unescape($crstype);
 5750:     $inststatuslist = &unescape($inststatuslist);
 5751:     $instcode = &unescape($instcode);
 5752:     $instseclist = &unescape($instseclist);
 5753:     my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
 5754:     my $outcome;
 5755:     eval {
 5756:         local($SIG{__DIE__})='DEFAULT';
 5757:         $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
 5758:                                                  $inststatuslist,$instcode,
 5759:                                                  $instseclist,$custominfo);
 5760:     };
 5761:     if (!$@) {
 5762:         &Reply($client, \$outcome, $userinput);
 5763:     } else {
 5764:         &Failure($client,"unknown_cmd\n",$userinput);
 5765:     }
 5766:     return 1;
 5767: }
 5768: &register_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
 5769: 
 5770: sub crsreq_update_handler {
 5771:     my ($cmd, $tail, $client) = @_;
 5772:     my $userinput = "$cmd:$tail";
 5773:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
 5774:         $accessstart,$accessend,$infohashref) =
 5775:         split(/:/, $tail);
 5776:     $crstype = &unescape($crstype);
 5777:     $action = &unescape($action);
 5778:     $ownername = &unescape($ownername);
 5779:     $ownerdomain = &unescape($ownerdomain);
 5780:     $fullname = &unescape($fullname);
 5781:     $title = &unescape($title);
 5782:     $code = &unescape($code);
 5783:     $accessstart = &unescape($accessstart);
 5784:     $accessend = &unescape($accessend);
 5785:     my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
 5786:     my ($result,$outcome);
 5787:     eval {
 5788:         local($SIG{__DIE__})='DEFAULT';
 5789:         my %rtnhash;
 5790:         $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
 5791:                                                 $ownername,$ownerdomain,$fullname,
 5792:                                                 $title,$code,$accessstart,$accessend,
 5793:                                                 $incoming,\%rtnhash);
 5794:         if ($outcome eq 'ok') {
 5795:             my @posskeys = qw(createdweb createdmsg createdcustomized createdactions queuedweb queuedmsg formitems reviewweb validationjs onload javascript);
 5796:             foreach my $key (keys(%rtnhash)) {
 5797:                 if (grep(/^\Q$key\E/,@posskeys)) {
 5798:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
 5799:                 }
 5800:             }
 5801:             $result =~ s/\&$//;
 5802:         }
 5803:     };
 5804:     if (!$@) {
 5805:         if ($outcome eq 'ok') {
 5806:             &Reply($client, \$result, $userinput);
 5807:         } else {
 5808:             &Reply($client, "format_error\n", $userinput);
 5809:         }
 5810:     } else {
 5811:         &Failure($client,"unknown_cmd\n",$userinput);
 5812:     }
 5813:     return 1;
 5814: }
 5815: &register_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
 5816: 
 5817: #
 5818: #   Read and retrieve institutional code format (for support form).
 5819: # Formal Parameters:
 5820: #    $cmd        - Command that dispatched us.
 5821: #    $tail       - Tail of the command.  In this case it conatins 
 5822: #                  the course domain and the coursename.
 5823: #    $client     - Socket open on the client.
 5824: # Returns:
 5825: #    1     - Continue processing.
 5826: #
 5827: sub get_institutional_code_format_handler {
 5828:     my ($cmd, $tail, $client)   = @_;
 5829:     my $userinput               = "$cmd:$tail";
 5830: 
 5831:     my $reply;
 5832:     my($cdom,$course) = split(/:/,$tail);
 5833:     my @pairs = split/\&/,$course;
 5834:     my %instcodes = ();
 5835:     my %codes = ();
 5836:     my @codetitles = ();
 5837:     my %cat_titles = ();
 5838:     my %cat_order = ();
 5839:     foreach (@pairs) {
 5840: 	my ($key,$value) = split/=/,$_;
 5841: 	$instcodes{&unescape($key)} = &unescape($value);
 5842:     }
 5843:     my $formatreply = &localenroll::instcode_format($cdom,
 5844: 						    \%instcodes,
 5845: 						    \%codes,
 5846: 						    \@codetitles,
 5847: 						    \%cat_titles,
 5848: 						    \%cat_order);
 5849:     if ($formatreply eq 'ok') {
 5850: 	my $codes_str = &Apache::lonnet::hash2str(%codes);
 5851: 	my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
 5852: 	my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
 5853: 	my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
 5854: 	&Reply($client,
 5855: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
 5856: 	       .$cat_order_str."\n",
 5857: 	       $userinput);
 5858:     } else {
 5859: 	# this else branch added by RF since if not ok, lonc will
 5860: 	# hang waiting on reply until timeout.
 5861: 	#
 5862: 	&Reply($client, "format_error\n", $userinput);
 5863:     }
 5864:     
 5865:     return 1;
 5866: }
 5867: &register_handler("autoinstcodeformat",
 5868: 		  \&get_institutional_code_format_handler,0,1,0);
 5869: 
 5870: sub get_institutional_defaults_handler {
 5871:     my ($cmd, $tail, $client)   = @_;
 5872:     my $userinput               = "$cmd:$tail";
 5873: 
 5874:     my $dom = $tail;
 5875:     my %defaults_hash;
 5876:     my @code_order;
 5877:     my $outcome;
 5878:     eval {
 5879:         local($SIG{__DIE__})='DEFAULT';
 5880:         $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
 5881:                                                    \@code_order);
 5882:     };
 5883:     if (!$@) {
 5884:         if ($outcome eq 'ok') {
 5885:             my $result='';
 5886:             while (my ($key,$value) = each(%defaults_hash)) {
 5887:                 $result.=&escape($key).'='.&escape($value).'&';
 5888:             }
 5889:             $result .= 'code_order='.&escape(join('&',@code_order));
 5890:             &Reply($client,\$result,$userinput);
 5891:         } else {
 5892:             &Reply($client,"error\n", $userinput);
 5893:         }
 5894:     } else {
 5895:         &Failure($client,"unknown_cmd\n",$userinput);
 5896:     }
 5897: }
 5898: &register_handler("autoinstcodedefaults",
 5899:                   \&get_institutional_defaults_handler,0,1,0);
 5900: 
 5901: sub get_possible_instcodes_handler {
 5902:     my ($cmd, $tail, $client)   = @_;
 5903:     my $userinput               = "$cmd:$tail";
 5904: 
 5905:     my $reply;
 5906:     my $cdom = $tail;
 5907:     my (@codetitles,%cat_titles,%cat_order,@code_order);
 5908:     my $formatreply = &localenroll::possible_instcodes($cdom,
 5909:                                                        \@codetitles,
 5910:                                                        \%cat_titles,
 5911:                                                        \%cat_order,
 5912:                                                        \@code_order);
 5913:     if ($formatreply eq 'ok') {
 5914:         my $result = join('&',map {&escape($_);} (@codetitles)).':';
 5915:         $result .= join('&',map {&escape($_);} (@code_order)).':';
 5916:         foreach my $key (keys(%cat_titles)) {
 5917:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
 5918:         }
 5919:         $result =~ s/\&$//;
 5920:         $result .= ':';
 5921:         foreach my $key (keys(%cat_order)) {
 5922:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
 5923:         }
 5924:         $result =~ s/\&$//;
 5925:         &Reply($client,\$result,$userinput);
 5926:     } else {
 5927:         &Reply($client, "format_error\n", $userinput);
 5928:     }
 5929:     return 1;
 5930: }
 5931: &register_handler("autopossibleinstcodes",
 5932:                   \&get_possible_instcodes_handler,0,1,0);
 5933: 
 5934: sub get_institutional_user_rules {
 5935:     my ($cmd, $tail, $client)   = @_;
 5936:     my $userinput               = "$cmd:$tail";
 5937:     my $dom = &unescape($tail);
 5938:     my (%rules_hash,@rules_order);
 5939:     my $outcome;
 5940:     eval {
 5941:         local($SIG{__DIE__})='DEFAULT';
 5942:         $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
 5943:     };
 5944:     if (!$@) {
 5945:         if ($outcome eq 'ok') {
 5946:             my $result;
 5947:             foreach my $key (keys(%rules_hash)) {
 5948:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
 5949:             }
 5950:             $result =~ s/\&$//;
 5951:             $result .= ':';
 5952:             if (@rules_order > 0) {
 5953:                 foreach my $item (@rules_order) {
 5954:                     $result .= &escape($item).'&';
 5955:                 }
 5956:             }
 5957:             $result =~ s/\&$//;
 5958:             &Reply($client,\$result,$userinput);
 5959:         } else {
 5960:             &Reply($client,"error\n", $userinput);
 5961:         }
 5962:     } else {
 5963:         &Failure($client,"unknown_cmd\n",$userinput);
 5964:     }
 5965: }
 5966: &register_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
 5967: 
 5968: sub get_institutional_id_rules {
 5969:     my ($cmd, $tail, $client)   = @_;
 5970:     my $userinput               = "$cmd:$tail";
 5971:     my $dom = &unescape($tail);
 5972:     my (%rules_hash,@rules_order);
 5973:     my $outcome;
 5974:     eval {
 5975:         local($SIG{__DIE__})='DEFAULT';
 5976:         $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
 5977:     };
 5978:     if (!$@) {
 5979:         if ($outcome eq 'ok') {
 5980:             my $result;
 5981:             foreach my $key (keys(%rules_hash)) {
 5982:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
 5983:             }
 5984:             $result =~ s/\&$//;
 5985:             $result .= ':';
 5986:             if (@rules_order > 0) {
 5987:                 foreach my $item (@rules_order) {
 5988:                     $result .= &escape($item).'&';
 5989:                 }
 5990:             }
 5991:             $result =~ s/\&$//;
 5992:             &Reply($client,\$result,$userinput);
 5993:         } else {
 5994:             &Reply($client,"error\n", $userinput);
 5995:         }
 5996:     } else {
 5997:         &Failure($client,"unknown_cmd\n",$userinput);
 5998:     }
 5999: }
 6000: &register_handler("instidrules",\&get_institutional_id_rules,0,1,0);
 6001: 
 6002: sub get_institutional_selfcreate_rules {
 6003:     my ($cmd, $tail, $client)   = @_;
 6004:     my $userinput               = "$cmd:$tail";
 6005:     my $dom = &unescape($tail);
 6006:     my (%rules_hash,@rules_order);
 6007:     my $outcome;
 6008:     eval {
 6009:         local($SIG{__DIE__})='DEFAULT';
 6010:         $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
 6011:     };
 6012:     if (!$@) {
 6013:         if ($outcome eq 'ok') {
 6014:             my $result;
 6015:             foreach my $key (keys(%rules_hash)) {
 6016:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
 6017:             }
 6018:             $result =~ s/\&$//;
 6019:             $result .= ':';
 6020:             if (@rules_order > 0) {
 6021:                 foreach my $item (@rules_order) {
 6022:                     $result .= &escape($item).'&';
 6023:                 }
 6024:             }
 6025:             $result =~ s/\&$//;
 6026:             &Reply($client,\$result,$userinput);
 6027:         } else {
 6028:             &Reply($client,"error\n", $userinput);
 6029:         }
 6030:     } else {
 6031:         &Failure($client,"unknown_cmd\n",$userinput);
 6032:     }
 6033: }
 6034: &register_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
 6035: 
 6036: 
 6037: sub institutional_username_check {
 6038:     my ($cmd, $tail, $client)   = @_;
 6039:     my $userinput               = "$cmd:$tail";
 6040:     my %rulecheck;
 6041:     my $outcome;
 6042:     my ($udom,$uname,@rules) = split(/:/,$tail);
 6043:     $udom = &unescape($udom);
 6044:     $uname = &unescape($uname);
 6045:     @rules = map {&unescape($_);} (@rules);
 6046:     eval {
 6047:         local($SIG{__DIE__})='DEFAULT';
 6048:         $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
 6049:     };
 6050:     if (!$@) {
 6051:         if ($outcome eq 'ok') {
 6052:             my $result='';
 6053:             foreach my $key (keys(%rulecheck)) {
 6054:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
 6055:             }
 6056:             &Reply($client,\$result,$userinput);
 6057:         } else {
 6058:             &Reply($client,"error\n", $userinput);
 6059:         }
 6060:     } else {
 6061:         &Failure($client,"unknown_cmd\n",$userinput);
 6062:     }
 6063: }
 6064: &register_handler("instrulecheck",\&institutional_username_check,0,1,0);
 6065: 
 6066: sub institutional_id_check {
 6067:     my ($cmd, $tail, $client)   = @_;
 6068:     my $userinput               = "$cmd:$tail";
 6069:     my %rulecheck;
 6070:     my $outcome;
 6071:     my ($udom,$id,@rules) = split(/:/,$tail);
 6072:     $udom = &unescape($udom);
 6073:     $id = &unescape($id);
 6074:     @rules = map {&unescape($_);} (@rules);
 6075:     eval {
 6076:         local($SIG{__DIE__})='DEFAULT';
 6077:         $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
 6078:     };
 6079:     if (!$@) {
 6080:         if ($outcome eq 'ok') {
 6081:             my $result='';
 6082:             foreach my $key (keys(%rulecheck)) {
 6083:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
 6084:             }
 6085:             &Reply($client,\$result,$userinput);
 6086:         } else {
 6087:             &Reply($client,"error\n", $userinput);
 6088:         }
 6089:     } else {
 6090:         &Failure($client,"unknown_cmd\n",$userinput);
 6091:     }
 6092: }
 6093: &register_handler("instidrulecheck",\&institutional_id_check,0,1,0);
 6094: 
 6095: sub institutional_selfcreate_check {
 6096:     my ($cmd, $tail, $client)   = @_;
 6097:     my $userinput               = "$cmd:$tail";
 6098:     my %rulecheck;
 6099:     my $outcome;
 6100:     my ($udom,$email,@rules) = split(/:/,$tail);
 6101:     $udom = &unescape($udom);
 6102:     $email = &unescape($email);
 6103:     @rules = map {&unescape($_);} (@rules);
 6104:     eval {
 6105:         local($SIG{__DIE__})='DEFAULT';
 6106:         $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
 6107:     };
 6108:     if (!$@) {
 6109:         if ($outcome eq 'ok') {
 6110:             my $result='';
 6111:             foreach my $key (keys(%rulecheck)) {
 6112:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
 6113:             }
 6114:             &Reply($client,\$result,$userinput);
 6115:         } else {
 6116:             &Reply($client,"error\n", $userinput);
 6117:         }
 6118:     } else {
 6119:         &Failure($client,"unknown_cmd\n",$userinput);
 6120:     }
 6121: }
 6122: &register_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
 6123: 
 6124: # Get domain specific conditions for import of student photographs to a course
 6125: #
 6126: # Retrieves information from photo_permission subroutine in localenroll.
 6127: # Returns outcome (ok) if no processing errors, and whether course owner is 
 6128: # required to accept conditions of use (yes/no).
 6129: #
 6130: #    
 6131: sub photo_permission_handler {
 6132:     my ($cmd, $tail, $client)   = @_;
 6133:     my $userinput               = "$cmd:$tail";
 6134:     my $cdom = $tail;
 6135:     my ($perm_reqd,$conditions);
 6136:     my $outcome;
 6137:     eval {
 6138: 	local($SIG{__DIE__})='DEFAULT';
 6139: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
 6140: 						  \$conditions);
 6141:     };
 6142:     if (!$@) {
 6143: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
 6144: 	       $userinput);
 6145:     } else {
 6146: 	&Failure($client,"unknown_cmd\n",$userinput);
 6147:     }
 6148:     return 1;
 6149: }
 6150: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
 6151: 
 6152: #
 6153: # Checks if student photo is available for a user in the domain, in the user's
 6154: # directory (in /userfiles/internal/studentphoto.jpg).
 6155: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
 6156: # the student's photo.   
 6157: 
 6158: sub photo_check_handler {
 6159:     my ($cmd, $tail, $client)   = @_;
 6160:     my $userinput               = "$cmd:$tail";
 6161:     my ($udom,$uname,$pid) = split(/:/,$tail);
 6162:     $udom = &unescape($udom);
 6163:     $uname = &unescape($uname);
 6164:     $pid = &unescape($pid);
 6165:     my $path=&propath($udom,$uname).'/userfiles/internal/';
 6166:     if (!-e $path) {
 6167:         &mkpath($path);
 6168:     }
 6169:     my $response;
 6170:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
 6171:     $result .= ':'.$response;
 6172:     &Reply($client, &escape($result)."\n",$userinput);
 6173:     return 1;
 6174: }
 6175: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
 6176: 
 6177: #
 6178: # Retrieve information from localenroll about whether to provide a button     
 6179: # for users who have enbled import of student photos to initiate an 
 6180: # update of photo files for registered students. Also include 
 6181: # comment to display alongside button.  
 6182: 
 6183: sub photo_choice_handler {
 6184:     my ($cmd, $tail, $client) = @_;
 6185:     my $userinput             = "$cmd:$tail";
 6186:     my $cdom                  = &unescape($tail);
 6187:     my ($update,$comment);
 6188:     eval {
 6189: 	local($SIG{__DIE__})='DEFAULT';
 6190: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
 6191:     };
 6192:     if (!$@) {
 6193: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
 6194:     } else {
 6195: 	&Failure($client,"unknown_cmd\n",$userinput);
 6196:     }
 6197:     return 1;
 6198: }
 6199: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
 6200: 
 6201: #
 6202: # Gets a student's photo to exist (in the correct image type) in the user's 
 6203: # directory.
 6204: # Formal Parameters:
 6205: #    $cmd     - The command request that got us dispatched.
 6206: #    $tail    - A colon separated set of words that will be split into:
 6207: #               $domain - student's domain
 6208: #               $uname  - student username
 6209: #               $type   - image type desired
 6210: #    $client  - The socket open on the client.
 6211: # Returns:
 6212: #    1 - continue processing.
 6213: 
 6214: sub student_photo_handler {
 6215:     my ($cmd, $tail, $client) = @_;
 6216:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
 6217: 
 6218:     my $path=&propath($domain,$uname). '/userfiles/internal/';
 6219:     my $filename = 'studentphoto.'.$ext;
 6220:     if ($type eq 'thumbnail') {
 6221:         $filename = 'studentphoto_tn.'.$ext;
 6222:     }
 6223:     if (-e $path.$filename) {
 6224: 	&Reply($client,"ok\n","$cmd:$tail");
 6225: 	return 1;
 6226:     }
 6227:     &mkpath($path);
 6228:     my $file;
 6229:     if ($type eq 'thumbnail') {
 6230: 	eval {
 6231: 	    local($SIG{__DIE__})='DEFAULT';
 6232: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
 6233: 	};
 6234:     } else {
 6235:         $file=&localstudentphoto::fetch($domain,$uname);
 6236:     }
 6237:     if (!$file) {
 6238: 	&Failure($client,"unavailable\n","$cmd:$tail");
 6239: 	return 1;
 6240:     }
 6241:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
 6242:     if (-e $path.$filename) {
 6243: 	&Reply($client,"ok\n","$cmd:$tail");
 6244: 	return 1;
 6245:     }
 6246:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
 6247:     return 1;
 6248: }
 6249: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
 6250: 
 6251: sub inst_usertypes_handler {
 6252:     my ($cmd, $domain, $client) = @_;
 6253:     my $res;
 6254:     my $userinput = $cmd.":".$domain; # For logging purposes.
 6255:     my (%typeshash,@order,$result);
 6256:     eval {
 6257: 	local($SIG{__DIE__})='DEFAULT';
 6258: 	$result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
 6259:     };
 6260:     if ($result eq 'ok') {
 6261:         if (keys(%typeshash) > 0) {
 6262:             foreach my $key (keys(%typeshash)) {
 6263:                 $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
 6264:             }
 6265:         }
 6266:         $res=~s/\&$//;
 6267:         $res .= ':';
 6268:         if (@order > 0) {
 6269:             foreach my $item (@order) {
 6270:                 $res .= &escape($item).'&';
 6271:             }
 6272:         }
 6273:         $res=~s/\&$//;
 6274:     }
 6275:     &Reply($client, \$res, $userinput);
 6276:     return 1;
 6277: }
 6278: &register_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
 6279: 
 6280: # mkpath makes all directories for a file, expects an absolute path with a
 6281: # file or a trailing / if just a dir is passed
 6282: # returns 1 on success 0 on failure
 6283: sub mkpath {
 6284:     my ($file)=@_;
 6285:     my @parts=split(/\//,$file,-1);
 6286:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
 6287:     for (my $i=3;$i<= ($#parts-1);$i++) {
 6288: 	$now.='/'.$parts[$i]; 
 6289: 	if (!-e $now) {
 6290: 	    if  (!mkdir($now,0770)) { return 0; }
 6291: 	}
 6292:     }
 6293:     return 1;
 6294: }
 6295: 
 6296: #---------------------------------------------------------------
 6297: #
 6298: #   Getting, decoding and dispatching requests:
 6299: #
 6300: #
 6301: #   Get a Request:
 6302: #   Gets a Request message from the client.  The transaction
 6303: #   is defined as a 'line' of text.  We remove the new line
 6304: #   from the text line.  
 6305: #
 6306: sub get_request {
 6307:     my $input = <$client>;
 6308:     chomp($input);
 6309: 
 6310:     &Debug("get_request: Request = $input\n");
 6311: 
 6312:     &status('Processing '.$clientname.':'.$input);
 6313: 
 6314:     return $input;
 6315: }
 6316: #---------------------------------------------------------------
 6317: #
 6318: #  Process a request.  This sub should shrink as each action
 6319: #  gets farmed out into a separat sub that is registered 
 6320: #  with the dispatch hash.  
 6321: #
 6322: # Parameters:
 6323: #    user_input   - The request received from the client (lonc).
 6324: #
 6325: # Returns:
 6326: #    true to keep processing, false if caller should exit.
 6327: #
 6328: sub process_request {
 6329:     my ($userinput) = @_; # Easier for now to break style than to
 6330:                           # fix all the userinput -> user_input.
 6331:     my $wasenc    = 0;		# True if request was encrypted.
 6332: # ------------------------------------------------------------ See if encrypted
 6333:     # for command
 6334:     # sethost:<server>
 6335:     # <command>:<args>
 6336:     #   we just send it to the processor
 6337:     # for
 6338:     # sethost:<server>:<command>:<args>
 6339:     #  we do the implict set host and then do the command
 6340:     if ($userinput =~ /^sethost:/) {
 6341: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
 6342: 	if (defined($userinput)) {
 6343: 	    &sethost("$cmd:$newid");
 6344: 	} else {
 6345: 	    $userinput = "$cmd:$newid";
 6346: 	}
 6347:     }
 6348: 
 6349:     if ($userinput =~ /^enc/) {
 6350: 	$userinput = decipher($userinput);
 6351: 	$wasenc=1;
 6352: 	if(!$userinput) {	# Cipher not defined.
 6353: 	    &Failure($client, "error: Encrypted data without negotated key\n");
 6354: 	    return 0;
 6355: 	}
 6356:     }
 6357:     Debug("process_request: $userinput\n");
 6358:     
 6359:     #  
 6360:     #   The 'correct way' to add a command to lond is now to
 6361:     #   write a sub to execute it and Add it to the command dispatch
 6362:     #   hash via a call to register_handler..  The comments to that
 6363:     #   sub should give you enough to go on to show how to do this
 6364:     #   along with the examples that are building up as this code
 6365:     #   is getting refactored.   Until all branches of the
 6366:     #   if/elseif monster below have been factored out into
 6367:     #   separate procesor subs, if the dispatch hash is missing
 6368:     #   the command keyword, we will fall through to the remainder
 6369:     #   of the if/else chain below in order to keep this thing in 
 6370:     #   working order throughout the transmogrification.
 6371: 
 6372:     my ($command, $tail) = split(/:/, $userinput, 2);
 6373:     chomp($command);
 6374:     chomp($tail);
 6375:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
 6376:     $command =~ s/(\r)//;	# And this too for parameterless commands.
 6377:     if(!$tail) {
 6378: 	$tail ="";		# defined but blank.
 6379:     }
 6380: 
 6381:     &Debug("Command received: $command, encoded = $wasenc");
 6382: 
 6383:     if(defined $Dispatcher{$command}) {
 6384: 
 6385: 	my $dispatch_info = $Dispatcher{$command};
 6386: 	my $handler       = $$dispatch_info[0];
 6387: 	my $need_encode   = $$dispatch_info[1];
 6388: 	my $client_types  = $$dispatch_info[2];
 6389: 	Debug("Matched dispatch hash: mustencode: $need_encode "
 6390: 	      ."ClientType $client_types");
 6391:       
 6392: 	#  Validate the request:
 6393:       
 6394: 	my $ok = 1;
 6395: 	my $requesterprivs = 0;
 6396: 	if(&isClient()) {
 6397: 	    $requesterprivs |= $CLIENT_OK;
 6398: 	}
 6399: 	if(&isManager()) {
 6400: 	    $requesterprivs |= $MANAGER_OK;
 6401: 	}
 6402: 	if($need_encode && (!$wasenc)) {
 6403: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
 6404: 	    $ok = 0;
 6405: 	}
 6406: 	if(($client_types & $requesterprivs) == 0) {
 6407: 	    Debug("Client not privileged to do this operation");
 6408: 	    $ok = 0;
 6409: 	}
 6410:         if ($ok) {
 6411:             if (ref($trust{$command}) eq 'HASH') {
 6412:                 my $donechecks;
 6413:                 if ($trust{$command}{'anywhere'}) {
 6414:                    $donechecks = 1;
 6415:                 } elsif ($trust{$command}{'manageronly'}) {
 6416:                     unless (&isManager()) {
 6417:                         $ok = 0;
 6418:                     }
 6419:                     $donechecks = 1;
 6420:                 } elsif ($trust{$command}{'institutiononly'}) {
 6421:                     unless ($clientsameinst) {
 6422:                         $ok = 0;
 6423:                     }
 6424:                     $donechecks = 1;
 6425:                 } elsif ($clientsameinst) {
 6426:                     $donechecks = 1;
 6427:                 }
 6428:                 unless ($donechecks) {
 6429:                     foreach my $rule (keys(%{$trust{$command}})) {
 6430:                         next if ($rule eq 'remote');
 6431:                         if ($trust{$command}{$rule}) {
 6432:                             if ($clientprohibited{$rule}) {
 6433:                                 $ok = 0;
 6434:                             } else {
 6435:                                 $ok = 1;
 6436:                                 $donechecks = 1;
 6437:                                 last;
 6438:                             }
 6439:                         }
 6440:                     }
 6441:                 }
 6442:                 unless ($donechecks) {
 6443:                     if ($trust{$command}{'remote'}) {
 6444:                         if ($clientremoteok) {
 6445:                             $ok = 1;
 6446:                         } else {
 6447:                             $ok = 0;
 6448:                         } 
 6449:                     }
 6450:                 }
 6451:             }
 6452:         }
 6453: 
 6454: 	if($ok) {
 6455: 	    Debug("Dispatching to handler $command $tail");
 6456: 	    my $keep_going = &$handler($command, $tail, $client);
 6457: 	    return $keep_going;
 6458: 	} else {
 6459: 	    Debug("Refusing to dispatch because client did not match requirements");
 6460: 	    Failure($client, "refused\n", $userinput);
 6461: 	    return 1;
 6462: 	}
 6463:     }
 6464: 
 6465:     print $client "unknown_cmd\n";
 6466: # -------------------------------------------------------------------- complete
 6467:     Debug("process_request - returning 1");
 6468:     return 1;
 6469: }
 6470: #
 6471: #   Decipher encoded traffic
 6472: #  Parameters:
 6473: #     input      - Encoded data.
 6474: #  Returns:
 6475: #     Decoded data or undef if encryption key was not yet negotiated.
 6476: #  Implicit input:
 6477: #     cipher  - This global holds the negotiated encryption key.
 6478: #
 6479: sub decipher {
 6480:     my ($input)  = @_;
 6481:     my $output = '';
 6482:     
 6483:     
 6484:     if($cipher) {
 6485: 	my($enc, $enclength, $encinput) = split(/:/, $input);
 6486: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
 6487: 	    $output .= 
 6488: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
 6489: 	}
 6490: 	return substr($output, 0, $enclength);
 6491:     } else {
 6492: 	return undef;
 6493:     }
 6494: }
 6495: 
 6496: #
 6497: #   Register a command processor.  This function is invoked to register a sub
 6498: #   to process a request.  Once registered, the ProcessRequest sub can automatically
 6499: #   dispatch requests to an appropriate sub, and do the top level validity checking
 6500: #   as well:
 6501: #    - Is the keyword recognized.
 6502: #    - Is the proper client type attempting the request.
 6503: #    - Is the request encrypted if it has to be.
 6504: #   Parameters:
 6505: #    $request_name         - Name of the request being registered.
 6506: #                           This is the command request that will match
 6507: #                           against the hash keywords to lookup the information
 6508: #                           associated with the dispatch information.
 6509: #    $procedure           - Reference to a sub to call to process the request.
 6510: #                           All subs get called as follows:
 6511: #                             Procedure($cmd, $tail, $replyfd, $key)
 6512: #                             $cmd    - the actual keyword that invoked us.
 6513: #                             $tail   - the tail of the request that invoked us.
 6514: #                             $replyfd- File descriptor connected to the client
 6515: #    $must_encode          - True if the request must be encoded to be good.
 6516: #    $client_ok            - True if it's ok for a client to request this.
 6517: #    $manager_ok           - True if it's ok for a manager to request this.
 6518: # Side effects:
 6519: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
 6520: #      - On failure, the program will die as it's a bad internal bug to try to 
 6521: #        register a duplicate command handler.
 6522: #
 6523: sub register_handler {
 6524:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
 6525: 
 6526:     #  Don't allow duplication#
 6527:    
 6528:     if (defined $Dispatcher{$request_name}) {
 6529: 	die "Attempting to define a duplicate request handler for $request_name\n";
 6530:     }
 6531:     #   Build the client type mask:
 6532:     
 6533:     my $client_type_mask = 0;
 6534:     if($client_ok) {
 6535: 	$client_type_mask  |= $CLIENT_OK;
 6536:     }
 6537:     if($manager_ok) {
 6538: 	$client_type_mask  |= $MANAGER_OK;
 6539:     }
 6540:    
 6541:     #  Enter the hash:
 6542:       
 6543:     my @entry = ($procedure, $must_encode, $client_type_mask);
 6544:    
 6545:     $Dispatcher{$request_name} = \@entry;
 6546:    
 6547: }
 6548: 
 6549: 
 6550: #------------------------------------------------------------------
 6551: 
 6552: 
 6553: 
 6554: 
 6555: #
 6556: #  Convert an error return code from lcpasswd to a string value.
 6557: #
 6558: sub lcpasswdstrerror {
 6559:     my $ErrorCode = shift;
 6560:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
 6561: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
 6562:     } else {
 6563: 	return $passwderrors[$ErrorCode];
 6564:     }
 6565: }
 6566: 
 6567: # grabs exception and records it to log before exiting
 6568: sub catchexception {
 6569:     my ($error)=@_;
 6570:     $SIG{'QUIT'}='DEFAULT';
 6571:     $SIG{__DIE__}='DEFAULT';
 6572:     &status("Catching exception");
 6573:     &logthis("<font color='red'>CRITICAL: "
 6574:      ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
 6575:      ."a crash with this error msg->[$error]</font>");
 6576:     &logthis('Famous last words: '.$status.' - '.$lastlog);
 6577:     if ($client) { print $client "error: $error\n"; }
 6578:     $server->close();
 6579:     die($error);
 6580: }
 6581: sub timeout {
 6582:     &status("Handling Timeout");
 6583:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
 6584:     &catchexception('Timeout');
 6585: }
 6586: # -------------------------------- Set signal handlers to record abnormal exits
 6587: 
 6588: 
 6589: $SIG{'QUIT'}=\&catchexception;
 6590: $SIG{__DIE__}=\&catchexception;
 6591: 
 6592: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
 6593: &status("Read loncapa.conf and loncapa_apache.conf");
 6594: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
 6595: %perlvar=%{$perlvarref};
 6596: undef $perlvarref;
 6597: 
 6598: # ----------------------------- Make sure this process is running from user=www
 6599: my $wwwid=getpwnam('www');
 6600: if ($wwwid!=$<) {
 6601:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
 6602:    my $subj="LON: $currenthostid User ID mismatch";
 6603:    system("echo 'User ID mismatch.  lond must be run as user www.' |\
 6604:  mailto $emailto -s '$subj' > /dev/null");
 6605:    exit 1;
 6606: }
 6607: 
 6608: # --------------------------------------------- Check if other instance running
 6609: 
 6610: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
 6611: 
 6612: if (-e $pidfile) {
 6613:    my $lfh=IO::File->new("$pidfile");
 6614:    my $pide=<$lfh>;
 6615:    chomp($pide);
 6616:    if (kill 0 => $pide) { die "already running"; }
 6617: }
 6618: 
 6619: # ------------------------------------------------------------- Read hosts file
 6620: 
 6621: 
 6622: 
 6623: # establish SERVER socket, bind and listen.
 6624: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
 6625:                                 Type      => SOCK_STREAM,
 6626:                                 Proto     => 'tcp',
 6627:                                 ReuseAddr     => 1,
 6628:                                 Listen    => 10 )
 6629:   or die "making socket: $@\n";
 6630: 
 6631: # --------------------------------------------------------- Do global variables
 6632: 
 6633: # global variables
 6634: 
 6635: my %children               = ();       # keys are current child process IDs
 6636: 
 6637: sub REAPER {                        # takes care of dead children
 6638:     $SIG{CHLD} = \&REAPER;
 6639:     &status("Handling child death");
 6640:     my $pid;
 6641:     do {
 6642: 	$pid = waitpid(-1,&WNOHANG());
 6643: 	if (defined($children{$pid})) {
 6644: 	    &logthis("Child $pid died");
 6645: 	    delete($children{$pid});
 6646: 	} elsif ($pid > 0) {
 6647: 	    &logthis("Unknown Child $pid died");
 6648: 	}
 6649:     } while ( $pid > 0 );
 6650:     foreach my $child (keys(%children)) {
 6651: 	$pid = waitpid($child,&WNOHANG());
 6652: 	if ($pid > 0) {
 6653: 	    &logthis("Child $child - $pid looks like we missed it's death");
 6654: 	    delete($children{$pid});
 6655: 	}
 6656:     }
 6657:     &status("Finished Handling child death");
 6658: }
 6659: 
 6660: sub HUNTSMAN {                      # signal handler for SIGINT
 6661:     &status("Killing children (INT)");
 6662:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
 6663:     kill 'INT' => keys %children;
 6664:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
 6665:     my $execdir=$perlvar{'lonDaemons'};
 6666:     unlink("$execdir/logs/lond.pid");
 6667:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
 6668:     &status("Done killing children");
 6669:     exit;                           # clean up with dignity
 6670: }
 6671: 
 6672: sub HUPSMAN {                      # signal handler for SIGHUP
 6673:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
 6674:     &status("Killing children for restart (HUP)");
 6675:     kill 'INT' => keys %children;
 6676:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
 6677:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
 6678:     my $execdir=$perlvar{'lonDaemons'};
 6679:     unlink("$execdir/logs/lond.pid");
 6680:     &status("Restarting self (HUP)");
 6681:     exec("$execdir/lond");         # here we go again
 6682: }
 6683: 
 6684: #
 6685: #  Reload the Apache daemon's state.
 6686: #  This is done by invoking /home/httpd/perl/apachereload
 6687: #  a setuid perl script that can be root for us to do this job.
 6688: #
 6689: sub ReloadApache {
 6690: # --------------------------- Handle case of another apachereload process (locking)
 6691:     if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
 6692:         my $execdir = $perlvar{'lonDaemons'};
 6693:         my $script  = $execdir."/apachereload";
 6694:         system($script);
 6695:         unlink('/tmp/lock_apachereload'); #  Remove the lock file.
 6696:     }
 6697: }
 6698: 
 6699: #
 6700: #   Called in response to a USR2 signal.
 6701: #   - Reread hosts.tab
 6702: #   - All children connected to hosts that were removed from hosts.tab
 6703: #     are killed via SIGINT
 6704: #   - All children connected to previously existing hosts are sent SIGUSR1
 6705: #   - Our internal hosts hash is updated to reflect the new contents of
 6706: #     hosts.tab causing connections from hosts added to hosts.tab to
 6707: #     now be honored.
 6708: #
 6709: sub UpdateHosts {
 6710:     &status("Reload hosts.tab");
 6711:     logthis('<font color="blue"> Updating connections </font>');
 6712:     #
 6713:     #  The %children hash has the set of IP's we currently have children
 6714:     #  on.  These need to be matched against records in the hosts.tab
 6715:     #  Any ip's no longer in the table get killed off they correspond to
 6716:     #  either dropped or changed hosts.  Note that the re-read of the table
 6717:     #  will take care of new and changed hosts as connections come into being.
 6718: 
 6719:     &Apache::lonnet::reset_hosts_info();
 6720: 
 6721:     foreach my $child (keys(%children)) {
 6722: 	my $childip = $children{$child};
 6723: 	if ($childip ne '127.0.0.1'
 6724: 	    && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
 6725: 	    logthis('<font color="blue"> UpdateHosts killing child '
 6726: 		    ." $child for ip $childip </font>");
 6727: 	    kill('INT', $child);
 6728: 	} else {
 6729: 	    logthis('<font color="green"> keeping child for ip '
 6730: 		    ." $childip (pid=$child) </font>");
 6731: 	}
 6732:     }
 6733:     ReloadApache;
 6734:     &status("Finished reloading hosts.tab");
 6735: }
 6736: 
 6737: 
 6738: sub checkchildren {
 6739:     &status("Checking on the children (sending signals)");
 6740:     &initnewstatus();
 6741:     &logstatus();
 6742:     &logthis('Going to check on the children');
 6743:     my $docdir=$perlvar{'lonDocRoot'};
 6744:     foreach (sort keys %children) {
 6745: 	#sleep 1;
 6746:         unless (kill 'USR1' => $_) {
 6747: 	    &logthis ('Child '.$_.' is dead');
 6748:             &logstatus($$.' is dead');
 6749: 	    delete($children{$_});
 6750:         } 
 6751:     }
 6752:     sleep 5;
 6753:     $SIG{ALRM} = sub { Debug("timeout"); 
 6754: 		       die "timeout";  };
 6755:     $SIG{__DIE__} = 'DEFAULT';
 6756:     &status("Checking on the children (waiting for reports)");
 6757:     foreach (sort keys %children) {
 6758:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
 6759:           eval {
 6760:             alarm(300);
 6761: 	    &logthis('Child '.$_.' did not respond');
 6762: 	    kill 9 => $_;
 6763: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
 6764: 	    #$subj="LON: $currenthostid killed lond process $_";
 6765: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
 6766: 	    #$execdir=$perlvar{'lonDaemons'};
 6767: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
 6768: 	    delete($children{$_});
 6769: 	    alarm(0);
 6770: 	  }
 6771:         }
 6772:     }
 6773:     $SIG{ALRM} = 'DEFAULT';
 6774:     $SIG{__DIE__} = \&catchexception;
 6775:     &status("Finished checking children");
 6776:     &logthis('Finished Checking children');
 6777: }
 6778: 
 6779: # --------------------------------------------------------------------- Logging
 6780: 
 6781: sub logthis {
 6782:     my $message=shift;
 6783:     my $execdir=$perlvar{'lonDaemons'};
 6784:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
 6785:     my $now=time;
 6786:     my $local=localtime($now);
 6787:     $lastlog=$local.': '.$message;
 6788:     print $fh "$local ($$): $message\n";
 6789: }
 6790: 
 6791: # ------------------------- Conditional log if $DEBUG true.
 6792: sub Debug {
 6793:     my $message = shift;
 6794:     if($DEBUG) {
 6795: 	&logthis($message);
 6796:     }
 6797: }
 6798: 
 6799: #
 6800: #   Sub to do replies to client.. this gives a hook for some
 6801: #   debug tracing too:
 6802: #  Parameters:
 6803: #     fd      - File open on client.
 6804: #     reply   - Text to send to client.
 6805: #     request - Original request from client.
 6806: #
 6807: #NOTE $reply must be terminated by exactly *one* \n. If $reply is a reference
 6808: #this is done automatically ($$reply must not contain any \n in this case). 
 6809: #If $reply is a string the caller has to ensure this.
 6810: sub Reply {
 6811:     my ($fd, $reply, $request) = @_;
 6812:     if (ref($reply)) {
 6813: 	print $fd $$reply;
 6814: 	print $fd "\n";
 6815: 	if ($DEBUG) { Debug("Request was $request  Reply was $$reply"); }
 6816:     } else {
 6817: 	print $fd $reply;
 6818: 	if ($DEBUG) { Debug("Request was $request  Reply was $reply"); }
 6819:     }
 6820:     $Transactions++;
 6821: }
 6822: 
 6823: 
 6824: #
 6825: #    Sub to report a failure.
 6826: #    This function:
 6827: #     -   Increments the failure statistic counters.
 6828: #     -   Invokes Reply to send the error message to the client.
 6829: # Parameters:
 6830: #    fd       - File descriptor open on the client
 6831: #    reply    - Reply text to emit.
 6832: #    request  - The original request message (used by Reply
 6833: #               to debug if that's enabled.
 6834: # Implicit outputs:
 6835: #    $Failures- The number of failures is incremented.
 6836: #    Reply (invoked here) sends a message to the 
 6837: #    client:
 6838: #
 6839: sub Failure {
 6840:     my $fd      = shift;
 6841:     my $reply   = shift;
 6842:     my $request = shift;
 6843:    
 6844:     $Failures++;
 6845:     Reply($fd, $reply, $request);      # That's simple eh?
 6846: }
 6847: # ------------------------------------------------------------------ Log status
 6848: 
 6849: sub logstatus {
 6850:     &status("Doing logging");
 6851:     my $docdir=$perlvar{'lonDocRoot'};
 6852:     {
 6853: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
 6854:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
 6855:         $fh->close();
 6856:     }
 6857:     &status("Finished $$.txt");
 6858:     {
 6859: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
 6860: 	flock(LOG,LOCK_EX);
 6861: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
 6862: 	    .$status."\t".$lastlog."\t $keymode\n";
 6863: 	flock(LOG,LOCK_UN);
 6864: 	close(LOG);
 6865:     }
 6866:     &status("Finished logging");
 6867: }
 6868: 
 6869: sub initnewstatus {
 6870:     my $docdir=$perlvar{'lonDocRoot'};
 6871:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
 6872:     my $now=time();
 6873:     my $local=localtime($now);
 6874:     print $fh "LOND status $local - parent $$\n\n";
 6875:     opendir(DIR,"$docdir/lon-status/londchld");
 6876:     while (my $filename=readdir(DIR)) {
 6877:         unlink("$docdir/lon-status/londchld/$filename");
 6878:     }
 6879:     closedir(DIR);
 6880: }
 6881: 
 6882: # -------------------------------------------------------------- Status setting
 6883: 
 6884: sub status {
 6885:     my $what=shift;
 6886:     my $now=time;
 6887:     my $local=localtime($now);
 6888:     $status=$local.': '.$what;
 6889:     $0='lond: '.$what.' '.$local;
 6890: }
 6891: 
 6892: # -------------------------------------------------------------- Talk to lonsql
 6893: 
 6894: sub sql_reply {
 6895:     my ($cmd)=@_;
 6896:     my $answer=&sub_sql_reply($cmd);
 6897:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
 6898:     return $answer;
 6899: }
 6900: 
 6901: sub sub_sql_reply {
 6902:     my ($cmd)=@_;
 6903:     my $unixsock="mysqlsock";
 6904:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
 6905:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
 6906:                                       Type    => SOCK_STREAM,
 6907:                                       Timeout => 10)
 6908:        or return "con_lost";
 6909:     print $sclient "$cmd:$currentdomainid\n";
 6910:     my $answer=<$sclient>;
 6911:     chomp($answer);
 6912:     if (!$answer) { $answer="con_lost"; }
 6913:     return $answer;
 6914: }
 6915: 
 6916: # --------------------------------------- Is this the home server of an author?
 6917: 
 6918: sub ishome {
 6919:     my $author=shift;
 6920:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 6921:     my ($udom,$uname)=split(/\//,$author);
 6922:     my $proname=propath($udom,$uname);
 6923:     if (-e $proname) {
 6924: 	return 'owner';
 6925:     } else {
 6926:         return 'not_owner';
 6927:     }
 6928: }
 6929: 
 6930: # ======================================================= Continue main program
 6931: # ---------------------------------------------------- Fork once and dissociate
 6932: 
 6933: my $fpid=fork;
 6934: exit if $fpid;
 6935: die "Couldn't fork: $!" unless defined ($fpid);
 6936: 
 6937: POSIX::setsid() or die "Can't start new session: $!";
 6938: 
 6939: # ------------------------------------------------------- Write our PID on disk
 6940: 
 6941: my $execdir=$perlvar{'lonDaemons'};
 6942: open (PIDSAVE,">$execdir/logs/lond.pid");
 6943: print PIDSAVE "$$\n";
 6944: close(PIDSAVE);
 6945: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
 6946: &status('Starting');
 6947: 
 6948: 
 6949: 
 6950: # ----------------------------------------------------- Install signal handlers
 6951: 
 6952: 
 6953: $SIG{CHLD} = \&REAPER;
 6954: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 6955: $SIG{HUP}  = \&HUPSMAN;
 6956: $SIG{USR1} = \&checkchildren;
 6957: $SIG{USR2} = \&UpdateHosts;
 6958: 
 6959: #  Read the host hashes:
 6960: &Apache::lonnet::load_hosts_tab();
 6961: my %iphost = &Apache::lonnet::get_iphost(1);
 6962: 
 6963: $dist=`$perlvar{'lonDaemons'}/distprobe`;
 6964: 
 6965: my $arch = `uname -i`;
 6966: chomp($arch);
 6967: if ($arch eq 'unknown') {
 6968:     $arch = `uname -m`;
 6969:     chomp($arch);
 6970: }
 6971: 
 6972: # --------------------------------------------------------------
 6973: #   Accept connections.  When a connection comes in, it is validated
 6974: #   and if good, a child process is created to process transactions
 6975: #   along the connection.
 6976: 
 6977: while (1) {
 6978:     &status('Starting accept');
 6979:     $client = $server->accept() or next;
 6980:     &status('Accepted '.$client.' off to spawn');
 6981:     make_new_child($client);
 6982:     &status('Finished spawning');
 6983: }
 6984: 
 6985: sub make_new_child {
 6986:     my $pid;
 6987: #    my $cipher;     # Now global
 6988:     my $sigset;
 6989: 
 6990:     $client = shift;
 6991:     &status('Starting new child '.$client);
 6992:     &logthis('<font color="green"> Attempting to start child ('.$client.
 6993: 	     ")</font>");    
 6994:     # block signal for fork
 6995:     $sigset = POSIX::SigSet->new(SIGINT);
 6996:     sigprocmask(SIG_BLOCK, $sigset)
 6997:         or die "Can't block SIGINT for fork: $!\n";
 6998: 
 6999:     die "fork: $!" unless defined ($pid = fork);
 7000: 
 7001:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
 7002: 	                               # connection liveness.
 7003: 
 7004:     #
 7005:     #  Figure out who we're talking to so we can record the peer in 
 7006:     #  the pid hash.
 7007:     #
 7008:     my $caller = getpeername($client);
 7009:     my ($port,$iaddr);
 7010:     if (defined($caller) && length($caller) > 0) {
 7011: 	($port,$iaddr)=unpack_sockaddr_in($caller);
 7012:     } else {
 7013: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
 7014:     }
 7015:     if (defined($iaddr)) {
 7016: 	$clientip  = inet_ntoa($iaddr);
 7017: 	Debug("Connected with $clientip");
 7018:     } else {
 7019: 	&logthis("Unable to determine clientip");
 7020: 	$clientip='Unavailable';
 7021:     }
 7022:     
 7023:     if ($pid) {
 7024:         # Parent records the child's birth and returns.
 7025:         sigprocmask(SIG_UNBLOCK, $sigset)
 7026:             or die "Can't unblock SIGINT for fork: $!\n";
 7027:         $children{$pid} = $clientip;
 7028:         &status('Started child '.$pid);
 7029: 	close($client);
 7030:         return;
 7031:     } else {
 7032:         # Child can *not* return from this subroutine.
 7033:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
 7034:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
 7035:                                 #don't get intercepted
 7036:         $SIG{USR1}= \&logstatus;
 7037:         $SIG{ALRM}= \&timeout;
 7038: 	#
 7039: 	# Block sigpipe as it gets thrownon socket disconnect and we want to 
 7040: 	# deal with that as a read faiure instead.
 7041: 	#
 7042: 	my $blockset = POSIX::SigSet->new(SIGPIPE);
 7043: 	sigprocmask(SIG_BLOCK, $blockset);
 7044: 
 7045:         $lastlog='Forked ';
 7046:         $status='Forked';
 7047: 
 7048:         # unblock signals
 7049:         sigprocmask(SIG_UNBLOCK, $sigset)
 7050:             or die "Can't unblock SIGINT for fork: $!\n";
 7051: 
 7052: #        my $tmpsnum=0;            # Now global
 7053: #---------------------------------------------------- kerberos 5 initialization
 7054:         &Authen::Krb5::init_context();
 7055: 
 7056:         my $no_ets;
 7057:         if ($dist =~ /^(?:centos|rhes|scientific)(\d+)$/) {
 7058:             if ($1 >= 7) {
 7059:                 $no_ets = 1;
 7060:             }
 7061:         } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
 7062:             if (($1 eq '9.3') || ($1 >= 12.2)) {
 7063:                 $no_ets = 1; 
 7064:             }
 7065:         } elsif ($dist =~ /^sles(\d+)$/) {
 7066:             if ($1 > 11) {
 7067:                 $no_ets = 1;
 7068:             }
 7069:         } elsif ($dist =~ /^fedora(\d+)$/) {
 7070:             if ($1 < 7) {
 7071:                 $no_ets = 1;
 7072:             }
 7073:         }
 7074:         unless ($no_ets) {
 7075: 	    &Authen::Krb5::init_ets();
 7076: 	}
 7077: 
 7078: 	&status('Accepted connection');
 7079: # =============================================================================
 7080:             # do something with the connection
 7081: # -----------------------------------------------------------------------------
 7082: 	# see if we know client and 'check' for spoof IP by ineffective challenge
 7083: 
 7084: 	my $outsideip=$clientip;
 7085: 	if ($clientip eq '127.0.0.1') {
 7086: 	    $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
 7087: 	}
 7088: 	&ReadManagerTable();
 7089: 	my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
 7090: 	my $ismanager=($managers{$outsideip}    ne undef);
 7091: 	$clientname  = "[unknown]";
 7092: 	if($clientrec) {	# Establish client type.
 7093: 	    $ConnectionType = "client";
 7094: 	    $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
 7095: 	    if($ismanager) {
 7096: 		$ConnectionType = "both";
 7097: 	    }
 7098: 	} else {
 7099: 	    $ConnectionType = "manager";
 7100: 	    $clientname = $managers{$outsideip};
 7101: 	}
 7102: 	my $clientok;
 7103: 
 7104: 	if ($clientrec || $ismanager) {
 7105: 	    &status("Waiting for init from $clientip $clientname");
 7106: 	    &logthis('<font color="yellow">INFO: Connection, '.
 7107: 		     $clientip.
 7108: 		  " ($clientname) connection type = $ConnectionType </font>" );
 7109: 	    &status("Connecting $clientip  ($clientname))"); 
 7110: 	    my $remotereq=<$client>;
 7111: 	    chomp($remotereq);
 7112: 	    Debug("Got init: $remotereq");
 7113: 
 7114: 	    if ($remotereq =~ /^init/) {
 7115: 		&sethost("sethost:$perlvar{'lonHostID'}");
 7116: 		#
 7117: 		#  If the remote is attempting a local init... give that a try:
 7118: 		#
 7119: 		(my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
 7120:         # For LON-CAPA 2.9, the  client session will have sent its LON-CAPA
 7121:         # version when initiating the connection. For LON-CAPA 2.8 and older,
 7122:         # the version is retrieved from the global %loncaparevs in lonnet.pm.            
 7123:         # $clientversion contains path to keyfile if $inittype eq 'local'
 7124:         # it's overridden below in this case
 7125:         $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
 7126: 
 7127: 		# If the connection type is ssl, but I didn't get my
 7128: 		# certificate files yet, then I'll drop  back to 
 7129: 		# insecure (if allowed).
 7130: 		
 7131: 		if($inittype eq "ssl") {
 7132: 		    my ($ca, $cert) = lonssl::CertificateFile;
 7133: 		    my $kfile       = lonssl::KeyFile;
 7134: 		    if((!$ca)   || 
 7135: 		       (!$cert) || 
 7136: 		       (!$kfile)) {
 7137: 			$inittype = ""; # This forces insecure attempt.
 7138: 			&logthis("<font color=\"blue\"> Certificates not "
 7139: 				 ."installed -- trying insecure auth</font>");
 7140: 		    } else {	# SSL certificates are in place so
 7141: 		    }		# Leave the inittype alone.
 7142: 		}
 7143: 
 7144: 		if($inittype eq "local") {
 7145:                     $clientversion = $perlvar{'lonVersion'};
 7146: 		    my $key = LocalConnection($client, $remotereq);
 7147: 		    if($key) {
 7148: 			Debug("Got local key $key");
 7149: 			$clientok     = 1;
 7150: 			my $cipherkey = pack("H32", $key);
 7151: 			$cipher       = new IDEA($cipherkey);
 7152: 			print $client "ok:local\n";
 7153: 			&logthis('<font color="green">'
 7154: 				 . "Successful local authentication </font>");
 7155: 			$keymode = "local"
 7156: 		    } else {
 7157: 			Debug("Failed to get local key");
 7158: 			$clientok = 0;
 7159: 			shutdown($client, 3);
 7160: 			close $client;
 7161: 		    }
 7162: 		} elsif ($inittype eq "ssl") {
 7163: 		    my $key = SSLConnection($client);
 7164: 		    if ($key) {
 7165: 			$clientok = 1;
 7166: 			my $cipherkey = pack("H32", $key);
 7167: 			$cipher       = new IDEA($cipherkey);
 7168: 			&logthis('<font color="green">'
 7169: 				 ."Successfull ssl authentication with $clientname </font>");
 7170: 			$keymode = "ssl";
 7171: 	     
 7172: 		    } else {
 7173: 			$clientok = 0;
 7174: 			close $client;
 7175: 		    }
 7176: 	   
 7177: 		} else {
 7178: 		    my $ok = InsecureConnection($client);
 7179: 		    if($ok) {
 7180: 			$clientok = 1;
 7181: 			&logthis('<font color="green">'
 7182: 				 ."Successful insecure authentication with $clientname </font>");
 7183: 			print $client "ok\n";
 7184: 			$keymode = "insecure";
 7185: 		    } else {
 7186: 			&logthis('<font color="yellow">'
 7187: 				  ."Attempted insecure connection disallowed </font>");
 7188: 			close $client;
 7189: 			$clientok = 0;
 7190: 			
 7191: 		    }
 7192: 		}
 7193: 	    } else {
 7194: 		&logthis(
 7195: 			 "<font color='blue'>WARNING: "
 7196: 			 ."$clientip failed to initialize: >$remotereq< </font>");
 7197: 		&status('No init '.$clientip);
 7198: 	    }
 7199: 	    
 7200: 	} else {
 7201: 	    &logthis(
 7202: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
 7203: 	    &status('Hung up on '.$clientip);
 7204: 	}
 7205:  
 7206: 	if ($clientok) {
 7207: # ---------------- New known client connecting, could mean machine online again
 7208: 	    if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip 
 7209: 		&& $clientip ne '127.0.0.1') {
 7210: 		&Apache::lonnet::reconlonc($clientname);
 7211: 	    }
 7212: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
 7213: 	    &status('Will listen to '.$clientname);
 7214: # ------------------------------------------------------------ Process requests
 7215: 	    my $keep_going = 1;
 7216: 	    my $user_input;
 7217:             my $clienthost = &Apache::lonnet::hostname($clientname);
 7218:             my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
 7219:             $clienthomedom = &Apache::lonnet::host_domain($clientserverhomeID);
 7220:             $clientintdom = &Apache::lonnet::internet_dom($clientserverhomeID);
 7221:             $clientsameinst = 0;
 7222:             if ($clientintdom ne '') {
 7223:                 my $internet_names = &Apache::lonnet::get_internet_names($currenthostid);
 7224:                 if (ref($internet_names) eq 'ARRAY') {
 7225:                     if (grep(/^\Q$clientintdom\E$/,@{$internet_names})) {
 7226:                         $clientsameinst = 1;
 7227:                     }
 7228:                 }
 7229:             }
 7230:             $clientremoteok = 0;
 7231:             unless ($clientsameinst) {
 7232:                 $clientremoteok = 1;
 7233:                 my $defdom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
 7234:                 %clientprohibited = &get_prohibited($defdom);
 7235:                 if ($clientintdom) {
 7236:                     my $remsessconf = &get_usersession_config($defdom,'remotesession');
 7237:                     if (ref($remsessconf) eq 'HASH') {
 7238:                         if (ref($remsessconf->{'remote'}) eq 'HASH') {
 7239:                             if (ref($remsessconf->{'remote'}->{'excludedomain'}) eq 'ARRAY') {
 7240:                                 if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'excludedomain'}})) {
 7241:                                     $clientremoteok = 0;
 7242:                                 }
 7243:                             }
 7244:                             if (ref($remsessconf->{'remote'}->{'includedomain'}) eq 'ARRAY') {
 7245:                                 if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'includedomain'}})) {
 7246:                                     $clientremoteok = 1;
 7247:                                 } else {
 7248:                                     $clientremoteok = 0;
 7249:                                 }
 7250:                             }
 7251:                         }
 7252:                     }
 7253:                 }
 7254:             }
 7255: 	    while(($user_input = get_request) && $keep_going) {
 7256: 		alarm(120);
 7257: 		Debug("Main: Got $user_input\n");
 7258: 		$keep_going = &process_request($user_input);
 7259: 		alarm(0);
 7260: 		&status('Listening to '.$clientname." ($keymode)");	   
 7261: 	    }
 7262: 
 7263: # --------------------------------------------- client unknown or fishy, refuse
 7264: 	}  else {
 7265: 	    print $client "refused\n";
 7266: 	    $client->close();
 7267: 	    &logthis("<font color='blue'>WARNING: "
 7268: 		     ."Rejected client $clientip, closing connection</font>");
 7269: 	}
 7270:     }
 7271:     
 7272: # =============================================================================
 7273:     
 7274:     &logthis("<font color='red'>CRITICAL: "
 7275: 	     ."Disconnect from $clientip ($clientname)</font>");    
 7276:     
 7277:     
 7278:     # this exit is VERY important, otherwise the child will become
 7279:     # a producer of more and more children, forking yourself into
 7280:     # process death.
 7281:     exit;
 7282:     
 7283: }
 7284: #
 7285: #   Determine if a user is an author for the indicated domain.
 7286: #
 7287: # Parameters:
 7288: #    domain          - domain to check in .
 7289: #    user            - Name of user to check.
 7290: #
 7291: # Return:
 7292: #     1             - User is an author for domain.
 7293: #     0             - User is not an author for domain.
 7294: sub is_author {
 7295:     my ($domain, $user) = @_;
 7296: 
 7297:     &Debug("is_author: $user @ $domain");
 7298: 
 7299:     my $hashref = &tie_user_hash($domain, $user, "roles",
 7300: 				 &GDBM_READER());
 7301: 
 7302:     #  Author role should show up as a key /domain/_au
 7303: 
 7304:     my $value;
 7305:     if ($hashref) {
 7306: 
 7307: 	my $key    = "/$domain/_au";
 7308: 	if (defined($hashref)) {
 7309: 	    $value = $hashref->{$key};
 7310: 	    if(!untie_user_hash($hashref)) {
 7311: 		return 'error: ' .  ($!+0)." untie (GDBM) Failed";
 7312: 	    }
 7313: 	}
 7314: 	
 7315: 	if(defined($value)) {
 7316: 	    &Debug("$user @ $domain is an author");
 7317: 	}
 7318:     } else {
 7319: 	return 'error: '.($!+0)." tie (GDBM) Failed";
 7320:     }
 7321: 
 7322:     return defined($value);
 7323: }
 7324: #
 7325: #   Checks to see if the input roleput request was to set
 7326: # an author role.  If so, creates construction space 
 7327: # Parameters:
 7328: #    request   - The request sent to the rolesput subchunk.
 7329: #                We're looking for  /domain/_au
 7330: #    domain    - The domain in which the user is having roles doctored.
 7331: #    user      - Name of the user for which the role is being put.
 7332: #    authtype  - The authentication type associated with the user.
 7333: #
 7334: sub manage_permissions {
 7335:     my ($request, $domain, $user, $authtype) = @_;
 7336:     # See if the request is of the form /$domain/_au
 7337:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
 7338:         my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
 7339:         unless (-e $path) {        
 7340:            mkdir($path);
 7341:         }
 7342:         unless (-e $path.'/'.$user) {
 7343:            mkdir($path.'/'.$user);
 7344:         }
 7345:     }
 7346: }
 7347: 
 7348: 
 7349: #
 7350: #  Return the full path of a user password file, whether it exists or not.
 7351: # Parameters:
 7352: #   domain     - Domain in which the password file lives.
 7353: #   user       - name of the user.
 7354: # Returns:
 7355: #    Full passwd path:
 7356: #
 7357: sub password_path {
 7358:     my ($domain, $user) = @_;
 7359:     return &propath($domain, $user).'/passwd';
 7360: }
 7361: 
 7362: #   Password Filename
 7363: #   Returns the path to a passwd file given domain and user... only if
 7364: #  it exists.
 7365: # Parameters:
 7366: #   domain    - Domain in which to search.
 7367: #   user      - username.
 7368: # Returns:
 7369: #   - If the password file exists returns its path.
 7370: #   - If the password file does not exist, returns undefined.
 7371: #
 7372: sub password_filename {
 7373:     my ($domain, $user) = @_;
 7374: 
 7375:     Debug ("PasswordFilename called: dom = $domain user = $user");
 7376: 
 7377:     my $path  = &password_path($domain, $user);
 7378:     Debug("PasswordFilename got path: $path");
 7379:     if(-e $path) {
 7380: 	return $path;
 7381:     } else {
 7382: 	return undef;
 7383:     }
 7384: }
 7385: 
 7386: #
 7387: #   Rewrite the contents of the user's passwd file.
 7388: #  Parameters:
 7389: #    domain    - domain of the user.
 7390: #    name      - User's name.
 7391: #    contents  - New contents of the file.
 7392: # Returns:
 7393: #   0    - Failed.
 7394: #   1    - Success.
 7395: #
 7396: sub rewrite_password_file {
 7397:     my ($domain, $user, $contents) = @_;
 7398: 
 7399:     my $file = &password_filename($domain, $user);
 7400:     if (defined $file) {
 7401: 	my $pf = IO::File->new(">$file");
 7402: 	if($pf) {
 7403: 	    print $pf "$contents\n";
 7404: 	    return 1;
 7405: 	} else {
 7406: 	    return 0;
 7407: 	}
 7408:     } else {
 7409: 	return 0;
 7410:     }
 7411: 
 7412: }
 7413: 
 7414: #
 7415: #   get_auth_type - Determines the authorization type of a user in a domain.
 7416: 
 7417: #     Returns the authorization type or nouser if there is no such user.
 7418: #
 7419: sub get_auth_type {
 7420:     my ($domain, $user)  = @_;
 7421: 
 7422:     Debug("get_auth_type( $domain, $user ) \n");
 7423:     my $proname    = &propath($domain, $user); 
 7424:     my $passwdfile = "$proname/passwd";
 7425:     if( -e $passwdfile ) {
 7426: 	my $pf = IO::File->new($passwdfile);
 7427: 	my $realpassword = <$pf>;
 7428: 	chomp($realpassword);
 7429: 	Debug("Password info = $realpassword\n");
 7430: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
 7431: 	Debug("Authtype = $authtype, content = $contentpwd\n");
 7432: 	return "$authtype:$contentpwd";     
 7433:     } else {
 7434: 	Debug("Returning nouser");
 7435: 	return "nouser";
 7436:     }
 7437: }
 7438: 
 7439: #
 7440: #  Validate a user given their domain, name and password.  This utility
 7441: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
 7442: #  to validate the login credentials of a user.
 7443: # Parameters:
 7444: #    $domain    - The domain being logged into (this is required due to
 7445: #                 the capability for multihomed systems.
 7446: #    $user      - The name of the user being validated.
 7447: #    $password  - The user's propoposed password.
 7448: #
 7449: # Returns:
 7450: #     1        - The domain,user,pasword triplet corresponds to a valid
 7451: #                user.
 7452: #     0        - The domain,user,password triplet is not a valid user.
 7453: #
 7454: sub validate_user {
 7455:     my ($domain, $user, $password, $checkdefauth) = @_;
 7456: 
 7457:     # Why negative ~pi you may well ask?  Well this function is about
 7458:     # authentication, and therefore very important to get right.
 7459:     # I've initialized the flag that determines whether or not I've 
 7460:     # validated correctly to a value it's not supposed to get.
 7461:     # At the end of this function. I'll ensure that it's not still that
 7462:     # value so we don't just wind up returning some accidental value
 7463:     # as a result of executing an unforseen code path that
 7464:     # did not set $validated.  At the end of valid execution paths,
 7465:     # validated shoule be 1 for success or 0 for failuer.
 7466: 
 7467:     my $validated = -3.14159;
 7468: 
 7469:     #  How we authenticate is determined by the type of authentication
 7470:     #  the user has been assigned.  If the authentication type is
 7471:     #  "nouser", the user does not exist so we will return 0.
 7472: 
 7473:     my $contents = &get_auth_type($domain, $user);
 7474:     my ($howpwd, $contentpwd) = split(/:/, $contents);
 7475: 
 7476:     my $null = pack("C",0);	# Used by kerberos auth types.
 7477: 
 7478:     if ($howpwd eq 'nouser') {
 7479:         if ($checkdefauth) {
 7480:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 7481:             if ($domdefaults{'auth_def'} eq 'localauth') {
 7482:                 $howpwd = $domdefaults{'auth_def'};
 7483:                 $contentpwd = $domdefaults{'auth_arg_def'};
 7484:             } elsif ((($domdefaults{'auth_def'} eq 'krb4') || 
 7485:                       ($domdefaults{'auth_def'} eq 'krb5')) &&
 7486:                      ($domdefaults{'auth_arg_def'} ne '')) {
 7487:                 $howpwd = $domdefaults{'auth_def'};
 7488:                 $contentpwd = $domdefaults{'auth_arg_def'}; 
 7489:             }
 7490:         }
 7491:     } 
 7492:     if ($howpwd ne 'nouser') {
 7493: 	if($howpwd eq "internal") { # Encrypted is in local password file.
 7494:             if (length($contentpwd) == 13) {
 7495:                 $validated = (crypt($password,$contentpwd) eq $contentpwd);
 7496:                 if ($validated) {
 7497:                     my $ncpass = &hash_passwd($domain,$password);
 7498:                     if (&rewrite_password_file($domain,$user,"$howpwd:$ncpass")) {
 7499:                         &update_passwd_history($user,$domain,$howpwd,'conversion');
 7500:                         &logthis("Validated password hashed with bcrypt for $user:$domain");
 7501:                     }
 7502:                 }
 7503:             } else {
 7504:                 $validated = &check_internal_passwd($password,$contentpwd,$domain);
 7505:             }
 7506: 	}
 7507: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
 7508: 	    $contentpwd = (getpwnam($user))[1];
 7509: 	    if($contentpwd) {
 7510: 		if($contentpwd eq 'x') { # Shadow password file...
 7511: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
 7512: 		    open PWAUTH,  "|$pwauth_path" or
 7513: 			die "Cannot invoke authentication";
 7514: 		    print PWAUTH "$user\n$password\n";
 7515: 		    close PWAUTH;
 7516: 		    $validated = ! $?;
 7517: 
 7518: 		} else { 	         # Passwords in /etc/passwd. 
 7519: 		    $validated = (crypt($password,
 7520: 					$contentpwd) eq $contentpwd);
 7521: 		}
 7522: 	    } else {
 7523: 		$validated = 0;
 7524: 	    }
 7525: 	} elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
 7526:             my $checkwithkrb5 = 0;
 7527:             if ($dist =~/^fedora(\d+)$/) {
 7528:                 if ($1 > 11) {
 7529:                     $checkwithkrb5 = 1;
 7530:                 }
 7531:             } elsif ($dist =~ /^suse([\d.]+)$/) {
 7532:                 if ($1 > 11.1) {
 7533:                     $checkwithkrb5 = 1; 
 7534:                 }
 7535:             }
 7536:             if ($checkwithkrb5) {
 7537:                 $validated = &krb5_authen($password,$null,$user,$contentpwd);
 7538:             } else {
 7539:                 $validated = &krb4_authen($password,$null,$user,$contentpwd);
 7540:             }
 7541: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
 7542:             $validated = &krb5_authen($password,$null,$user,$contentpwd);
 7543: 	} elsif ($howpwd eq "localauth") { 
 7544: 	    #  Authenticate via installation specific authentcation method:
 7545: 	    $validated = &localauth::localauth($user, 
 7546: 					       $password, 
 7547: 					       $contentpwd,
 7548: 					       $domain);
 7549: 	    if ($validated < 0) {
 7550: 		&logthis("localauth for $contentpwd $user:$domain returned a $validated");
 7551: 		$validated = 0;
 7552: 	    }
 7553: 	} else {			# Unrecognized auth is also bad.
 7554: 	    $validated = 0;
 7555: 	}
 7556:     } else {
 7557: 	$validated = 0;
 7558:     }
 7559:     #
 7560:     #  $validated has the correct stat of the authentication:
 7561:     #
 7562: 
 7563:     unless ($validated != -3.14159) {
 7564: 	#  I >really really< want to know if this happens.
 7565: 	#  since it indicates that user authentication is badly
 7566: 	#  broken in some code path.
 7567:         #
 7568: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
 7569:     }
 7570:     return $validated;
 7571: }
 7572: 
 7573: sub check_internal_passwd {
 7574:     my ($plainpass,$stored,$domain) = @_;
 7575:     my (undef,$method,@rest) = split(/!/,$stored);
 7576:     if ($method eq "bcrypt") {
 7577:         my $result = &hash_passwd($domain,$plainpass,@rest);
 7578:         if ($result ne $stored) {
 7579:             return 0;
 7580:         }
 7581:         # Upgrade to a larger number of rounds if necessary
 7582:         my $defaultcost;
 7583:         my %domconfig =
 7584:             &Apache::lonnet::get_dom('configuration',['password'],$domain);
 7585:         if (ref($domconfig{'password'}) eq 'HASH') {
 7586:             $defaultcost = $domconfig{'password'}{'cost'};
 7587:         }
 7588:         if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
 7589:             $defaultcost = 10;
 7590:         }
 7591:         return 1 unless($rest[0]<$defaultcost);
 7592:     }
 7593:     return 0;
 7594: }
 7595: 
 7596: sub get_last_authchg {
 7597:     my ($domain,$user) = @_;
 7598:     my $lastmod;
 7599:     my $logname = &propath($domain,$user).'/passwd.log';
 7600:     if (-e "$logname") {
 7601:         $lastmod = (stat("$logname"))[9];
 7602:     }
 7603:     return $lastmod;
 7604: }
 7605: 
 7606: sub krb4_authen {
 7607:     my ($password,$null,$user,$contentpwd) = @_;
 7608:     my $validated = 0;
 7609:     if (!($password =~ /$null/) ) {  # Null password not allowed.
 7610:         eval {
 7611:             require Authen::Krb4;
 7612:         };
 7613:         if (!$@) {
 7614:             my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
 7615:                                                        "",
 7616:                                                        $contentpwd,,
 7617:                                                        'krbtgt',
 7618:                                                        $contentpwd,
 7619:                                                        1,
 7620:                                                        $password);
 7621:             if(!$k4error) {
 7622:                 $validated = 1;
 7623:             } else {
 7624:                 $validated = 0;
 7625:                 &logthis('krb4: '.$user.', '.$contentpwd.', '.
 7626:                           &Authen::Krb4::get_err_txt($Authen::Krb4::error));
 7627:             }
 7628:         } else {
 7629:             $validated = krb5_authen($password,$null,$user,$contentpwd);
 7630:         }
 7631:     }
 7632:     return $validated;
 7633: }
 7634: 
 7635: sub krb5_authen {
 7636:     my ($password,$null,$user,$contentpwd) = @_;
 7637:     my $validated = 0;
 7638:     if(!($password =~ /$null/)) { # Null password not allowed.
 7639:         my $krbclient = &Authen::Krb5::parse_name($user.'@'
 7640:                                                   .$contentpwd);
 7641:         my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
 7642:         my $krbserver  = &Authen::Krb5::parse_name($krbservice);
 7643:         my $credentials= &Authen::Krb5::cc_default();
 7644:         $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
 7645:                                                             .$contentpwd));
 7646:         my $krbreturn;
 7647:         if (exists(&Authen::Krb5::get_init_creds_password)) {
 7648:             $krbreturn =
 7649:                 &Authen::Krb5::get_init_creds_password($krbclient,$password,
 7650:                                                           $krbservice);
 7651:             $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
 7652:         } else {
 7653:             $krbreturn  =
 7654:                 &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
 7655:                                                          $password,$credentials);
 7656:             $validated = ($krbreturn == 1);
 7657:         }
 7658:         if (!$validated) {
 7659:             &logthis('krb5: '.$user.', '.$contentpwd.', '.
 7660:                      &Authen::Krb5::error());
 7661:         }
 7662:     }
 7663:     return $validated;
 7664: }
 7665: 
 7666: sub addline {
 7667:     my ($fname,$hostid,$ip,$newline)=@_;
 7668:     my $contents;
 7669:     my $found=0;
 7670:     my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
 7671:     my $sh;
 7672:     if ($sh=IO::File->new("$fname.subscription")) {
 7673: 	while (my $subline=<$sh>) {
 7674: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
 7675: 	}
 7676: 	$sh->close();
 7677:     }
 7678:     $sh=IO::File->new(">$fname.subscription");
 7679:     if ($contents) { print $sh $contents; }
 7680:     if ($newline) { print $sh $newline; }
 7681:     $sh->close();
 7682:     return $found;
 7683: }
 7684: 
 7685: sub get_chat {
 7686:     my ($cdom,$cname,$udom,$uname,$group)=@_;
 7687: 
 7688:     my @entries=();
 7689:     my $namespace = 'nohist_chatroom';
 7690:     my $namespace_inroom = 'nohist_inchatroom';
 7691:     if ($group ne '') {
 7692:         $namespace .= '_'.$group;
 7693:         $namespace_inroom .= '_'.$group;
 7694:     }
 7695:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
 7696: 				 &GDBM_READER());
 7697:     if ($hashref) {
 7698: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
 7699: 	&untie_user_hash($hashref);
 7700:     }
 7701:     my @participants=();
 7702:     my $cutoff=time-60;
 7703:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
 7704: 			      &GDBM_WRCREAT());
 7705:     if ($hashref) {
 7706:         $hashref->{$uname.':'.$udom}=time;
 7707:         foreach my $user (sort(keys(%$hashref))) {
 7708: 	    if ($hashref->{$user}>$cutoff) {
 7709: 		push(@participants, 'active_participant:'.$user);
 7710:             }
 7711:         }
 7712:         &untie_user_hash($hashref);
 7713:     }
 7714:     return (@participants,@entries);
 7715: }
 7716: 
 7717: sub chat_add {
 7718:     my ($cdom,$cname,$newchat,$group)=@_;
 7719:     my @entries=();
 7720:     my $time=time;
 7721:     my $namespace = 'nohist_chatroom';
 7722:     my $logfile = 'chatroom.log';
 7723:     if ($group ne '') {
 7724:         $namespace .= '_'.$group;
 7725:         $logfile = 'chatroom_'.$group.'.log';
 7726:     }
 7727:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
 7728: 				 &GDBM_WRCREAT());
 7729:     if ($hashref) {
 7730: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
 7731: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
 7732: 	my ($thentime,$idnum)=split(/\_/,$lastid);
 7733: 	my $newid=$time.'_000000';
 7734: 	if ($thentime==$time) {
 7735: 	    $idnum=~s/^0+//;
 7736: 	    $idnum++;
 7737: 	    $idnum=substr('000000'.$idnum,-6,6);
 7738: 	    $newid=$time.'_'.$idnum;
 7739: 	}
 7740: 	$hashref->{$newid}=$newchat;
 7741: 	my $expired=$time-3600;
 7742: 	foreach my $comment (keys(%$hashref)) {
 7743: 	    my ($thistime) = ($comment=~/(\d+)\_/);
 7744: 	    if ($thistime<$expired) {
 7745: 		delete $hashref->{$comment};
 7746: 	    }
 7747: 	}
 7748: 	{
 7749: 	    my $proname=&propath($cdom,$cname);
 7750: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
 7751: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
 7752: 	    }
 7753: 	    close(CHATLOG);
 7754: 	}
 7755: 	&untie_user_hash($hashref);
 7756:     }
 7757: }
 7758: 
 7759: sub unsub {
 7760:     my ($fname,$clientip)=@_;
 7761:     my $result;
 7762:     my $unsubs = 0;		# Number of successful unsubscribes:
 7763: 
 7764: 
 7765:     # An old way subscriptions were handled was to have a 
 7766:     # subscription marker file:
 7767: 
 7768:     Debug("Attempting unlink of $fname.$clientname");
 7769:     if (unlink("$fname.$clientname")) {
 7770: 	$unsubs++;		# Successful unsub via marker file.
 7771:     } 
 7772: 
 7773:     # The more modern way to do it is to have a subscription list
 7774:     # file:
 7775: 
 7776:     if (-e "$fname.subscription") {
 7777: 	my $found=&addline($fname,$clientname,$clientip,'');
 7778: 	if ($found) { 
 7779: 	    $unsubs++;
 7780: 	}
 7781:     } 
 7782: 
 7783:     #  If either or both of these mechanisms succeeded in unsubscribing a 
 7784:     #  resource we can return ok:
 7785: 
 7786:     if($unsubs) {
 7787: 	$result = "ok\n";
 7788:     } else {
 7789: 	$result = "not_subscribed\n";
 7790:     }
 7791: 
 7792:     return $result;
 7793: }
 7794: 
 7795: sub currentversion {
 7796:     my $fname=shift;
 7797:     my $version=-1;
 7798:     my $ulsdir='';
 7799:     if ($fname=~/^(.+)\/[^\/]+$/) {
 7800:        $ulsdir=$1;
 7801:     }
 7802:     my ($fnamere1,$fnamere2);
 7803:     # remove version if already specified
 7804:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
 7805:     # get the bits that go before and after the version number
 7806:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
 7807: 	$fnamere1=$1;
 7808: 	$fnamere2='.'.$2;
 7809:     }
 7810:     if (-e $fname) { $version=1; }
 7811:     if (-e $ulsdir) {
 7812: 	if(-d $ulsdir) {
 7813: 	    if (opendir(LSDIR,$ulsdir)) {
 7814: 		my $ulsfn;
 7815: 		while ($ulsfn=readdir(LSDIR)) {
 7816: # see if this is a regular file (ignore links produced earlier)
 7817: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
 7818: 		    unless (-l $thisfile) {
 7819: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
 7820: 			    if ($1>$version) { $version=$1; }
 7821: 			}
 7822: 		    }
 7823: 		}
 7824: 		closedir(LSDIR);
 7825: 		$version++;
 7826: 	    }
 7827: 	}
 7828:     }
 7829:     return $version;
 7830: }
 7831: 
 7832: sub thisversion {
 7833:     my $fname=shift;
 7834:     my $version=-1;
 7835:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
 7836: 	$version=$1;
 7837:     }
 7838:     return $version;
 7839: }
 7840: 
 7841: sub subscribe {
 7842:     my ($userinput,$clientip)=@_;
 7843:     my $result;
 7844:     my ($cmd,$fname)=split(/:/,$userinput,2);
 7845:     my $ownership=&ishome($fname);
 7846:     if ($ownership eq 'owner') {
 7847: # explitly asking for the current version?
 7848:         unless (-e $fname) {
 7849:             my $currentversion=&currentversion($fname);
 7850: 	    if (&thisversion($fname)==$currentversion) {
 7851:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
 7852: 		    my $root=$1;
 7853:                     my $extension=$2;
 7854:                     symlink($root.'.'.$extension,
 7855:                             $root.'.'.$currentversion.'.'.$extension);
 7856:                     unless ($extension=~/\.meta$/) {
 7857:                        symlink($root.'.'.$extension.'.meta',
 7858:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
 7859: 		    }
 7860:                 }
 7861:             }
 7862:         }
 7863: 	if (-e $fname) {
 7864: 	    if (-d $fname) {
 7865: 		$result="directory\n";
 7866: 	    } else {
 7867: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
 7868: 		my $now=time;
 7869: 		my $found=&addline($fname,$clientname,$clientip,
 7870: 				   "$clientname:$clientip:$now\n");
 7871: 		if ($found) { $result="$fname\n"; }
 7872: 		# if they were subscribed to only meta data, delete that
 7873:                 # subscription, when you subscribe to a file you also get
 7874:                 # the metadata
 7875: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
 7876: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
 7877:                 my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
 7878:                 $protocol = 'http' if ($protocol ne 'https');
 7879: 		$fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
 7880: 		$result="$fname\n";
 7881: 	    }
 7882: 	} else {
 7883: 	    $result="not_found\n";
 7884: 	}
 7885:     } else {
 7886: 	$result="rejected\n";
 7887:     }
 7888:     return $result;
 7889: }
 7890: #  Change the passwd of a unix user.  The caller must have
 7891: #  first verified that the user is a loncapa user.
 7892: #
 7893: # Parameters:
 7894: #    user      - Unix user name to change.
 7895: #    pass      - New password for the user.
 7896: # Returns:
 7897: #    ok    - if success
 7898: #    other - Some meaningfule error message string.
 7899: # NOTE:
 7900: #    invokes a setuid script to change the passwd.
 7901: sub change_unix_password {
 7902:     my ($user, $pass) = @_;
 7903: 
 7904:     &Debug("change_unix_password");
 7905:     my $execdir=$perlvar{'lonDaemons'};
 7906:     &Debug("Opening lcpasswd pipeline");
 7907:     my $pf = IO::File->new("|$execdir/lcpasswd > "
 7908: 			   ."$perlvar{'lonDaemons'}"
 7909: 			   ."/logs/lcpasswd.log");
 7910:     print $pf "$user\n$pass\n$pass\n";
 7911:     close $pf;
 7912:     my $err = $?;
 7913:     return ($err < @passwderrors) ? $passwderrors[$err] : 
 7914: 	"pwchange_falure - unknown error";
 7915: 
 7916:     
 7917: }
 7918: 
 7919: 
 7920: sub make_passwd_file {
 7921:     my ($uname,$udom,$umode,$npass,$passfilename,$action)=@_;
 7922:     my $result="ok";
 7923:     if ($umode eq 'krb4' or $umode eq 'krb5') {
 7924: 	{
 7925: 	    my $pf = IO::File->new(">$passfilename");
 7926: 	    if ($pf) {
 7927: 		print $pf "$umode:$npass\n";
 7928:                 &update_passwd_history($uname,$udom,$umode,$action);
 7929: 	    } else {
 7930: 		$result = "pass_file_failed_error";
 7931: 	    }
 7932: 	}
 7933:     } elsif ($umode eq 'internal') {
 7934:         my $ncpass = &hash_passwd($udom,$npass);
 7935: 	{
 7936: 	    &Debug("Creating internal auth");
 7937: 	    my $pf = IO::File->new(">$passfilename");
 7938: 	    if($pf) {
 7939: 		print $pf "internal:$ncpass\n";
 7940:                 &update_passwd_history($uname,$udom,$umode,$action); 
 7941: 	    } else {
 7942: 		$result = "pass_file_failed_error";
 7943: 	    }
 7944: 	}
 7945:     } elsif ($umode eq 'localauth') {
 7946: 	{
 7947: 	    my $pf = IO::File->new(">$passfilename");
 7948: 	    if($pf) {
 7949: 		print $pf "localauth:$npass\n";
 7950:                 &update_passwd_history($uname,$udom,$umode,$action);
 7951: 	    } else {
 7952: 		$result = "pass_file_failed_error";
 7953: 	    }
 7954: 	}
 7955:     } elsif ($umode eq 'unix') {
 7956: 	&logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
 7957: 	$result="no_new_unix_accounts";
 7958:     } elsif ($umode eq 'none') {
 7959: 	{
 7960: 	    my $pf = IO::File->new("> $passfilename");
 7961: 	    if($pf) {
 7962: 		print $pf "none:\n";
 7963: 	    } else {
 7964: 		$result = "pass_file_failed_error";
 7965: 	    }
 7966: 	}
 7967:     } else {
 7968: 	$result="auth_mode_error";
 7969:     }
 7970:     return $result;
 7971: }
 7972: 
 7973: sub convert_photo {
 7974:     my ($start,$dest)=@_;
 7975:     system("convert $start $dest");
 7976: }
 7977: 
 7978: sub sethost {
 7979:     my ($remotereq) = @_;
 7980:     my (undef,$hostid)=split(/:/,$remotereq);
 7981:     # ignore sethost if we are already correct
 7982:     if ($hostid eq $currenthostid) {
 7983: 	return 'ok';
 7984:     }
 7985: 
 7986:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
 7987:     if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'}) 
 7988: 	eq &Apache::lonnet::get_host_ip($hostid)) {
 7989: 	$currenthostid  =$hostid;
 7990: 	$currentdomainid=&Apache::lonnet::host_domain($hostid);
 7991: #	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
 7992:     } else {
 7993: 	&logthis("Requested host id $hostid not an alias of ".
 7994: 		 $perlvar{'lonHostID'}." refusing connection");
 7995: 	return 'unable_to_set';
 7996:     }
 7997:     return 'ok';
 7998: }
 7999: 
 8000: sub version {
 8001:     my ($userinput)=@_;
 8002:     $remoteVERSION=(split(/:/,$userinput))[1];
 8003:     return "version:$VERSION";
 8004: }
 8005: 
 8006: sub get_usersession_config {
 8007:     my ($dom,$name) = @_;
 8008:     my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
 8009:     if (defined($cached)) {
 8010:         return $usersessionconf;
 8011:     } else {
 8012:         my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
 8013:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
 8014:         return $domconfig{'usersessions'};
 8015:     }
 8016:     return;
 8017: }
 8018: 
 8019: sub get_prohibited {
 8020:     my ($dom) = @_;
 8021:     my $name = 'trust';
 8022:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
 8023:     unless (defined($cached)) {
 8024:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$dom);
 8025:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'trust'},3600);
 8026:         $trustconfig = $domconfig{'trust'};
 8027:     }
 8028:     my %prohibited;
 8029:     if (ref($trustconfig)) {
 8030:         foreach my $prefix (keys(%{$trustconfig})) {
 8031:             if (ref($trustconfig->{$prefix}) eq 'HASH') {
 8032:                 my $reject;
 8033:                 if (ref($trustconfig->{$prefix}->{'exc'}) eq 'ARRAY') {
 8034:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'exc'}})) {
 8035:                         $reject = 1;
 8036:                     }
 8037:                 }
 8038:                 if (ref($trustconfig->{$prefix}->{'inc'}) eq 'ARRAY') {
 8039:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'inc'}})) {
 8040:                         $reject = 0;
 8041:                     } else {
 8042:                         $reject = 1;
 8043:                     }
 8044:                 }
 8045:                 if ($reject) {
 8046:                     $prohibited{$prefix} = 1;
 8047:                 }
 8048:             }
 8049:         }
 8050:     }
 8051:     return %prohibited;
 8052: }
 8053: 
 8054: sub distro_and_arch {
 8055:     return $dist.':'.$arch;
 8056: }
 8057: 
 8058: # ----------------------------------- POD (plain old documentation, CPAN style)
 8059: 
 8060: =head1 NAME
 8061: 
 8062: lond - "LON Daemon" Server (port "LOND" 5663)
 8063: 
 8064: =head1 SYNOPSIS
 8065: 
 8066: Usage: B<lond>
 8067: 
 8068: Should only be run as user=www.  This is a command-line script which
 8069: is invoked by B<loncron>.  There is no expectation that a typical user
 8070: will manually start B<lond> from the command-line.  (In other words,
 8071: DO NOT START B<lond> YOURSELF.)
 8072: 
 8073: =head1 DESCRIPTION
 8074: 
 8075: There are two characteristics associated with the running of B<lond>,
 8076: PROCESS MANAGEMENT (starting, stopping, handling child processes)
 8077: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
 8078: subscriptions, etc).  These are described in two large
 8079: sections below.
 8080: 
 8081: B<PROCESS MANAGEMENT>
 8082: 
 8083: Preforker - server who forks first. Runs as a daemon. HUPs.
 8084: Uses IDEA encryption
 8085: 
 8086: B<lond> forks off children processes that correspond to the other servers
 8087: in the network.  Management of these processes can be done at the
 8088: parent process level or the child process level.
 8089: 
 8090: B<logs/lond.log> is the location of log messages.
 8091: 
 8092: The process management is now explained in terms of linux shell commands,
 8093: subroutines internal to this code, and signal assignments:
 8094: 
 8095: =over 4
 8096: 
 8097: =item *
 8098: 
 8099: PID is stored in B<logs/lond.pid>
 8100: 
 8101: This is the process id number of the parent B<lond> process.
 8102: 
 8103: =item *
 8104: 
 8105: SIGTERM and SIGINT
 8106: 
 8107: Parent signal assignment:
 8108:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 8109: 
 8110: Child signal assignment:
 8111:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
 8112: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
 8113:  to restart a new child.)
 8114: 
 8115: Command-line invocations:
 8116:  B<kill> B<-s> SIGTERM I<PID>
 8117:  B<kill> B<-s> SIGINT I<PID>
 8118: 
 8119: Subroutine B<HUNTSMAN>:
 8120:  This is only invoked for the B<lond> parent I<PID>.
 8121: This kills all the children, and then the parent.
 8122: The B<lonc.pid> file is cleared.
 8123: 
 8124: =item *
 8125: 
 8126: SIGHUP
 8127: 
 8128: Current bug:
 8129:  This signal can only be processed the first time
 8130: on the parent process.  Subsequent SIGHUP signals
 8131: have no effect.
 8132: 
 8133: Parent signal assignment:
 8134:  $SIG{HUP}  = \&HUPSMAN;
 8135: 
 8136: Child signal assignment:
 8137:  none (nothing happens)
 8138: 
 8139: Command-line invocations:
 8140:  B<kill> B<-s> SIGHUP I<PID>
 8141: 
 8142: Subroutine B<HUPSMAN>:
 8143:  This is only invoked for the B<lond> parent I<PID>,
 8144: This kills all the children, and then the parent.
 8145: The B<lond.pid> file is cleared.
 8146: 
 8147: =item *
 8148: 
 8149: SIGUSR1
 8150: 
 8151: Parent signal assignment:
 8152:  $SIG{USR1} = \&USRMAN;
 8153: 
 8154: Child signal assignment:
 8155:  $SIG{USR1}= \&logstatus;
 8156: 
 8157: Command-line invocations:
 8158:  B<kill> B<-s> SIGUSR1 I<PID>
 8159: 
 8160: Subroutine B<USRMAN>:
 8161:  When invoked for the B<lond> parent I<PID>,
 8162: SIGUSR1 is sent to all the children, and the status of
 8163: each connection is logged.
 8164: 
 8165: =item *
 8166: 
 8167: SIGUSR2
 8168: 
 8169: Parent Signal assignment:
 8170:     $SIG{USR2} = \&UpdateHosts
 8171: 
 8172: Child signal assignment:
 8173:     NONE
 8174: 
 8175: 
 8176: =item *
 8177: 
 8178: SIGCHLD
 8179: 
 8180: Parent signal assignment:
 8181:  $SIG{CHLD} = \&REAPER;
 8182: 
 8183: Child signal assignment:
 8184:  none
 8185: 
 8186: Command-line invocations:
 8187:  B<kill> B<-s> SIGCHLD I<PID>
 8188: 
 8189: Subroutine B<REAPER>:
 8190:  This is only invoked for the B<lond> parent I<PID>.
 8191: Information pertaining to the child is removed.
 8192: The socket port is cleaned up.
 8193: 
 8194: =back
 8195: 
 8196: B<SERVER-SIDE ACTIVITIES>
 8197: 
 8198: Server-side information can be accepted in an encrypted or non-encrypted
 8199: method.
 8200: 
 8201: =over 4
 8202: 
 8203: =item ping
 8204: 
 8205: Query a client in the hosts.tab table; "Are you there?"
 8206: 
 8207: =item pong
 8208: 
 8209: Respond to a ping query.
 8210: 
 8211: =item ekey
 8212: 
 8213: Read in encrypted key, make cipher.  Respond with a buildkey.
 8214: 
 8215: =item load
 8216: 
 8217: Respond with CPU load based on a computation upon /proc/loadavg.
 8218: 
 8219: =item currentauth
 8220: 
 8221: Reply with current authentication information (only over an
 8222: encrypted channel).
 8223: 
 8224: =item auth
 8225: 
 8226: Only over an encrypted channel, reply as to whether a user's
 8227: authentication information can be validated.
 8228: 
 8229: =item passwd
 8230: 
 8231: Allow for a password to be set.
 8232: 
 8233: =item makeuser
 8234: 
 8235: Make a user.
 8236: 
 8237: =item changeuserauth
 8238: 
 8239: Allow for authentication mechanism and password to be changed.
 8240: 
 8241: =item home
 8242: 
 8243: Respond to a question "are you the home for a given user?"
 8244: 
 8245: =item update
 8246: 
 8247: Update contents of a subscribed resource.
 8248: 
 8249: =item unsubscribe
 8250: 
 8251: The server is unsubscribing from a resource.
 8252: 
 8253: =item subscribe
 8254: 
 8255: The server is subscribing to a resource.
 8256: 
 8257: =item log
 8258: 
 8259: Place in B<logs/lond.log>
 8260: 
 8261: =item put
 8262: 
 8263: stores hash in namespace
 8264: 
 8265: =item rolesput
 8266: 
 8267: put a role into a user's environment
 8268: 
 8269: =item get
 8270: 
 8271: returns hash with keys from array
 8272: reference filled in from namespace
 8273: 
 8274: =item eget
 8275: 
 8276: returns hash with keys from array
 8277: reference filled in from namesp (encrypts the return communication)
 8278: 
 8279: =item rolesget
 8280: 
 8281: get a role from a user's environment
 8282: 
 8283: =item del
 8284: 
 8285: deletes keys out of array from namespace
 8286: 
 8287: =item keys
 8288: 
 8289: returns namespace keys
 8290: 
 8291: =item dump
 8292: 
 8293: dumps the complete (or key matching regexp) namespace into a hash
 8294: 
 8295: =item store
 8296: 
 8297: stores hash permanently
 8298: for this url; hashref needs to be given and should be a \%hashname; the
 8299: remaining args aren't required and if they aren't passed or are '' they will
 8300: be derived from the ENV
 8301: 
 8302: =item restore
 8303: 
 8304: returns a hash for a given url
 8305: 
 8306: =item querysend
 8307: 
 8308: Tells client about the lonsql process that has been launched in response
 8309: to a sent query.
 8310: 
 8311: =item queryreply
 8312: 
 8313: Accept information from lonsql and make appropriate storage in temporary
 8314: file space.
 8315: 
 8316: =item idput
 8317: 
 8318: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
 8319: for each student, defined perhaps by the institutional Registrar.)
 8320: 
 8321: =item idget
 8322: 
 8323: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
 8324: for each student, defined perhaps by the institutional Registrar.)
 8325: 
 8326: =item iddel
 8327: 
 8328: Deletes one or more ids in a domain's id database.
 8329: 
 8330: =item tmpput
 8331: 
 8332: Accept and store information in temporary space.
 8333: 
 8334: =item tmpget
 8335: 
 8336: Send along temporarily stored information.
 8337: 
 8338: =item ls
 8339: 
 8340: List part of a user's directory.
 8341: 
 8342: =item pushtable
 8343: 
 8344: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
 8345: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
 8346: must be restored manually in case of a problem with the new table file.
 8347: pushtable requires that the request be encrypted and validated via
 8348: ValidateManager.  The form of the command is:
 8349: enc:pushtable tablename <tablecontents> \n
 8350: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
 8351: cleartext newline.
 8352: 
 8353: =item Hanging up (exit or init)
 8354: 
 8355: What to do when a client tells the server that they (the client)
 8356: are leaving the network.
 8357: 
 8358: =item unknown command
 8359: 
 8360: If B<lond> is sent an unknown command (not in the list above),
 8361: it replys to the client "unknown_cmd".
 8362: 
 8363: 
 8364: =item UNKNOWN CLIENT
 8365: 
 8366: If the anti-spoofing algorithm cannot verify the client,
 8367: the client is rejected (with a "refused" message sent
 8368: to the client, and the connection is closed.
 8369: 
 8370: =back
 8371: 
 8372: =head1 PREREQUISITES
 8373: 
 8374: IO::Socket
 8375: IO::File
 8376: Apache::File
 8377: POSIX
 8378: Crypt::IDEA
 8379: LWP::UserAgent()
 8380: GDBM_File
 8381: Authen::Krb4
 8382: Authen::Krb5
 8383: 
 8384: =head1 COREQUISITES
 8385: 
 8386: none
 8387: 
 8388: =head1 OSNAMES
 8389: 
 8390: linux
 8391: 
 8392: =head1 SCRIPT CATEGORIES
 8393: 
 8394: Server/Process
 8395: 
 8396: =cut
 8397: 
 8398: 
 8399: =pod
 8400: 
 8401: =head1 LOG MESSAGES
 8402: 
 8403: The messages below can be emitted in the lond log.  This log is located
 8404: in ~httpd/perl/logs/lond.log  Many log messages have HTML encapsulation
 8405: to provide coloring if examined from inside a web page. Some do not.
 8406: Where color is used, the colors are; Red for sometihhng to get excited
 8407: about and to follow up on. Yellow for something to keep an eye on to
 8408: be sure it does not get worse, Green,and Blue for informational items.
 8409: 
 8410: In the discussions below, sometimes reference is made to ~httpd
 8411: when describing file locations.  There isn't really an httpd 
 8412: user, however there is an httpd directory that gets installed in the
 8413: place that user home directories go.  On linux, this is usually
 8414: (always?) /home/httpd.
 8415: 
 8416: 
 8417: Some messages are colorless.  These are usually (not always)
 8418: Green/Blue color level messages.
 8419: 
 8420: =over 2
 8421: 
 8422: =item (Red)  LocalConnection rejecting non local: <ip> ne 127.0.0.1
 8423: 
 8424: A local connection negotiation was attempted by
 8425: a host whose IP address was not 127.0.0.1.
 8426: The socket is closed and the child will exit.
 8427: lond has three ways to establish an encyrption
 8428: key with a client:
 8429: 
 8430: =over 2
 8431: 
 8432: =item local 
 8433: 
 8434: The key is written and read from a file.
 8435: This is only valid for connections from localhost.
 8436: 
 8437: =item insecure 
 8438: 
 8439: The key is generated by the server and
 8440: transmitted to the client.
 8441: 
 8442: =item  ssl (secure)
 8443: 
 8444: An ssl connection is negotiated with the client,
 8445: the key is generated by the server and sent to the 
 8446: client across this ssl connection before the
 8447: ssl connectionis terminated and clear text
 8448: transmission resumes.
 8449: 
 8450: =back
 8451: 
 8452: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
 8453: 
 8454: The client is local but has not sent an initialization
 8455: string that is the literal "init:local"  The connection
 8456: is closed and the child exits.
 8457: 
 8458: =item Red CRITICAL Can't get key file <error>        
 8459: 
 8460: SSL key negotiation is being attempted but the call to
 8461: lonssl::KeyFile  failed.  This usually means that the
 8462: configuration file is not correctly defining or protecting
 8463: the directories/files lonCertificateDirectory or
 8464: lonnetPrivateKey
 8465: <error> is a string that describes the reason that
 8466: the key file could not be located.
 8467: 
 8468: =item (Red) CRITICAL  Can't get certificates <error>  
 8469: 
 8470: SSL key negotiation failed because we were not able to retrives our certificate
 8471: or the CA's certificate in the call to lonssl::CertificateFile
 8472: <error> is the textual reason this failed.  Usual reasons:
 8473: 
 8474: =over 2
 8475: 
 8476: =item Apache config file for loncapa  incorrect:
 8477: 
 8478: one of the variables 
 8479: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
 8480: undefined or incorrect
 8481: 
 8482: =item Permission error:
 8483: 
 8484: The directory pointed to by lonCertificateDirectory is not readable by lond
 8485: 
 8486: =item Permission error:
 8487: 
 8488: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
 8489: 
 8490: =item Installation error:                         
 8491: 
 8492: Either the certificate authority file or the certificate have not
 8493: been installed in lonCertificateDirectory.
 8494: 
 8495: =item (Red) CRITICAL SSL Socket promotion failed:  <err> 
 8496: 
 8497: The promotion of the connection from plaintext to SSL failed
 8498: <err> is the reason for the failure.  There are two
 8499: system calls involved in the promotion (one of which failed), 
 8500: a dup to produce
 8501: a second fd on the raw socket over which the encrypted data
 8502: will flow and IO::SOcket::SSL->new_from_fd which creates
 8503: the SSL connection on the duped fd.
 8504: 
 8505: =item (Blue)   WARNING client did not respond to challenge 
 8506: 
 8507: This occurs on an insecure (non SSL) connection negotiation request.
 8508: lond generates some number from the time, the PID and sends it to
 8509: the client.  The client must respond by echoing this information back.
 8510: If the client does not do so, that's a violation of the challenge
 8511: protocols and the connection will be failed.
 8512: 
 8513: =item (Red) No manager table. Nobody can manage!!    
 8514: 
 8515: lond has the concept of privileged hosts that
 8516: can perform remote management function such
 8517: as update the hosts.tab.   The manager hosts
 8518: are described in the 
 8519: ~httpd/lonTabs/managers.tab file.
 8520: this message is logged if this file is missing.
 8521: 
 8522: 
 8523: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
 8524: 
 8525: Reports the successful parse and registration
 8526: of a specific manager. 
 8527: 
 8528: =item Green existing host <clustername:dnsname>  
 8529: 
 8530: The manager host is already defined in the hosts.tab
 8531: the information in that table, rather than the info in the
 8532: manager table will be used to determine the manager's ip.
 8533: 
 8534: =item (Red) Unable to craete <filename>                 
 8535: 
 8536: lond has been asked to create new versions of an administrative
 8537: file (by a manager).  When this is done, the new file is created
 8538: in a temp file and then renamed into place so that there are always
 8539: usable administrative files, even if the update fails.  This failure
 8540: message means that the temp file could not be created.
 8541: The update is abandoned, and the old file is available for use.
 8542: 
 8543: =item (Green) CopyFile from <oldname> to <newname> failed
 8544: 
 8545: In an update of administrative files, the copy of the existing file to a
 8546: backup file failed.  The installation of the new file may still succeed,
 8547: but there will not be a back up file to rever to (this should probably
 8548: be yellow).
 8549: 
 8550: =item (Green) Pushfile: backed up <oldname> to <newname>
 8551: 
 8552: See above, the backup of the old administrative file succeeded.
 8553: 
 8554: =item (Red)  Pushfile: Unable to install <filename> <reason>
 8555: 
 8556: The new administrative file could not be installed.  In this case,
 8557: the old administrative file is still in use.
 8558: 
 8559: =item (Green) Installed new < filename>.                      
 8560: 
 8561: The new administrative file was successfullly installed.                                               
 8562: 
 8563: =item (Red) Reinitializing lond pid=<pid>                    
 8564: 
 8565: The lonc child process <pid> will be sent a USR2 
 8566: signal.
 8567: 
 8568: =item (Red) Reinitializing self                                    
 8569: 
 8570: We've been asked to re-read our administrative files,and
 8571: are doing so.
 8572: 
 8573: =item (Yellow) error:Invalid process identifier <ident>  
 8574: 
 8575: A reinit command was received, but the target part of the 
 8576: command was not valid.  It must be either
 8577: 'lond' or 'lonc' but was <ident>
 8578: 
 8579: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
 8580: 
 8581: Checking to see if lond has been handed a valid edit
 8582: command.  It is possible the edit command is not valid
 8583: in that case there are no log messages to indicate that.
 8584: 
 8585: =item Result of password change for  <username> pwchange_success
 8586: 
 8587: The password for <username> was
 8588: successfully changed.
 8589: 
 8590: =item Unable to open <user> passwd to change password
 8591: 
 8592: Could not rewrite the 
 8593: internal password file for a user
 8594: 
 8595: =item Result of password change for <user> : <result>
 8596: 
 8597: A unix password change for <user> was attempted 
 8598: and the pipe returned <result>  
 8599: 
 8600: =item LWP GET: <message> for <fname> (<remoteurl>)
 8601: 
 8602: The lightweight process fetch for a resource failed
 8603: with <message> the local filename that should
 8604: have existed/been created was  <fname> the
 8605: corresponding URI: <remoteurl>  This is emitted in several
 8606: places.
 8607: 
 8608: =item Unable to move <transname> to <destname>     
 8609: 
 8610: From fetch_user_file_handler - the user file was replicated but could not
 8611: be mv'd to its final location.
 8612: 
 8613: =item Looking for <domain> <username>              
 8614: 
 8615: From user_has_session_handler - This should be a Debug call instead
 8616: it indicates lond is about to check whether the specified user has a 
 8617: session active on the specified domain on the local host.
 8618: 
 8619: =item Client <ip> (<name>) hanging up: <input>     
 8620: 
 8621: lond has been asked to exit by its client.  The <ip> and <name> identify the
 8622: client systemand <input> is the full exit command sent to the server.
 8623: 
 8624: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
 8625: 
 8626: A lond child terminated.  NOte that this termination can also occur when the
 8627: child receives the QUIT or DIE signals.  <pid> is the process id of the child,
 8628: <hostname> the host lond is working for, and <message> the reason the child died
 8629: to the best of our ability to get it (I would guess that any numeric value
 8630: represents and errno value).  This is immediately followed by
 8631: 
 8632: =item  Famous last words: Catching exception - <log> 
 8633: 
 8634: Where log is some recent information about the state of the child.
 8635: 
 8636: =item Red CRITICAL: TIME OUT <pid>                     
 8637: 
 8638: Some timeout occured for server <pid>.  THis is normally a timeout on an LWP
 8639: doing an HTTP::GET.
 8640: 
 8641: =item child <pid> died                              
 8642: 
 8643: The reaper caught a SIGCHILD for the lond child process <pid>
 8644: This should be modified to also display the IP of the dying child
 8645: $children{$pid}
 8646: 
 8647: =item Unknown child 0 died                           
 8648: A child died but the wait for it returned a pid of zero which really should not
 8649: ever happen. 
 8650: 
 8651: =item Child <which> - <pid> looks like we missed it's death 
 8652: 
 8653: When a sigchild is received, the reaper process checks all children to see if they are
 8654: alive.  If children are dying quite quickly, the lack of signal queuing can mean
 8655: that a signal hearalds the death of more than one child.  If so this message indicates
 8656: which other one died. <which> is the ip of a dead child
 8657: 
 8658: =item Free socket: <shutdownretval>                
 8659: 
 8660: The HUNTSMAN sub was called due to a SIGINT in a child process.  The socket is being shutdown.
 8661: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
 8662: to return anything. This is followed by: 
 8663: 
 8664: =item Red CRITICAL: Shutting down                       
 8665: 
 8666: Just prior to exit.
 8667: 
 8668: =item Free socket: <shutdownretval>                 
 8669: 
 8670: The HUPSMAN sub was called due to a SIGHUP.  all children get killsed, and lond execs itself.
 8671: This is followed by:
 8672: 
 8673: =item (Red) CRITICAL: Restarting                         
 8674: 
 8675: lond is about to exec itself to restart.
 8676: 
 8677: =item (Blue) Updating connections                        
 8678: 
 8679: (In response to a USR2).  All the children (except the one for localhost)
 8680: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
 8681: 
 8682: =item (Blue) UpdateHosts killing child <pid> for ip <ip>   
 8683: 
 8684: Due to USR2 as above.
 8685: 
 8686: =item (Green) keeping child for ip <ip> (pid = <pid>)    
 8687: 
 8688: In response to USR2 as above, the child indicated is not being restarted because
 8689: it's assumed that we'll always need a child for the localhost.
 8690: 
 8691: 
 8692: =item Going to check on the children                
 8693: 
 8694: Parent is about to check on the health of the child processes.
 8695: Note that this is in response to a USR1 sent to the parent lond.
 8696: there may be one or more of the next two messages:
 8697: 
 8698: =item <pid> is dead                                 
 8699: 
 8700: A child that we have in our child hash as alive has evidently died.
 8701: 
 8702: =item  Child <pid> did not respond                   
 8703: 
 8704: In the health check the child <pid> did not update/produce a pid_.txt
 8705: file when sent it's USR1 signal.  That process is killed with a 9 signal, as it's
 8706: assumed to be hung in some un-fixable way.
 8707: 
 8708: =item Finished checking children                   
 8709: 
 8710: Master processs's USR1 processing is cojmplete.
 8711: 
 8712: =item (Red) CRITICAL: ------- Starting ------            
 8713: 
 8714: (There are more '-'s on either side).  Lond has forked itself off to 
 8715: form a new session and is about to start actual initialization.
 8716: 
 8717: =item (Green) Attempting to start child (<client>)       
 8718: 
 8719: Started a new child process for <client>.  Client is IO::Socket object
 8720: connected to the child.  This was as a result of a TCP/IP connection from a client.
 8721: 
 8722: =item Unable to determine who caller was, getpeername returned nothing
 8723: 
 8724: In child process initialization.  either getpeername returned undef or
 8725: a zero sized object was returned.  Processing continues, but in my opinion,
 8726: this should be cause for the child to exit.
 8727: 
 8728: =item Unable to determine clientip                  
 8729: 
 8730: In child process initialization.  The peer address from getpeername was not defined.
 8731: The client address is stored as "Unavailable" and processing continues.
 8732: 
 8733: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
 8734: 
 8735: In child initialization.  A good connectionw as received from <ip>.
 8736: 
 8737: =over 2
 8738: 
 8739: =item <name> 
 8740: 
 8741: is the name of the client from hosts.tab.
 8742: 
 8743: =item <type> 
 8744: 
 8745: Is the connection type which is either 
 8746: 
 8747: =over 2
 8748: 
 8749: =item manager 
 8750: 
 8751: The connection is from a manager node, not in hosts.tab
 8752: 
 8753: =item client  
 8754: 
 8755: the connection is from a non-manager in the hosts.tab
 8756: 
 8757: =item both
 8758: 
 8759: The connection is from a manager in the hosts.tab.
 8760: 
 8761: =back
 8762: 
 8763: =back
 8764: 
 8765: =item (Blue) Certificates not installed -- trying insecure auth
 8766: 
 8767: One of the certificate file, key file or
 8768: certificate authority file could not be found for a client attempting
 8769: SSL connection intiation.  COnnection will be attemptied in in-secure mode.
 8770: (this would be a system with an up to date lond that has not gotten a 
 8771: certificate from us).
 8772: 
 8773: =item (Green)  Successful local authentication            
 8774: 
 8775: A local connection successfully negotiated the encryption key. 
 8776: In this case the IDEA key is in a file (that is hopefully well protected).
 8777: 
 8778: =item (Green) Successful ssl authentication with <client>  
 8779: 
 8780: The client (<client> is the peer's name in hosts.tab), has successfully
 8781: negotiated an SSL connection with this child process.
 8782: 
 8783: =item (Green) Successful insecure authentication with <client>
 8784: 
 8785: 
 8786: The client has successfully negotiated an  insecure connection withthe child process.
 8787: 
 8788: =item (Yellow) Attempted insecure connection disallowed    
 8789: 
 8790: The client attempted and failed to successfully negotiate a successful insecure
 8791: connection.  This can happen either because the variable londAllowInsecure is false
 8792: or undefined, or becuse the child did not successfully echo back the challenge
 8793: string.
 8794: 
 8795: 
 8796: =back
 8797: 
 8798: =back
 8799: 
 8800: 
 8801: =cut

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