File:  [LON-CAPA] / loncom / lond
Revision 1.534: download - view: text, annotated - select for diffs
Mon Mar 20 03:19:37 2017 UTC (7 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- If LON-CAPA Directory searches are disabled for other domains, enforce
  that on the lond side, in case user session is hosted on a 2.11.1 (or earlier)
- Expire 60 minutes caches of 'usersessions' and 'directorysrch' settings
  (used by lond) on domain's servers when domain configuration changes.

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

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