File:  [LON-CAPA] / loncom / lond
Revision 1.545: download - view: text, annotated - select for diffs
Tue Aug 7 17:12:09 2018 UTC (5 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Support Certificate Revocation List checking when using SSL channel
  for key exchange during negotiation of connection to remote lond.

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

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