File:  [LON-CAPA] / loncom / lond
Revision 1.531: download - view: text, annotated - select for diffs
Tue Feb 7 18:14:13 2017 UTC (7 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Include lonAdmEMail and lonSupportEMail in data from conf files which is
  accessible via lond::read_lonnet_global().

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

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