File:  [LON-CAPA] / loncom / lond
Revision 1.546: download - view: text, annotated - select for diffs
Thu Aug 9 13:27:55 2018 UTC (5 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Compatibility with pre-2.12 LON-CAPA versions of loncnew.

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

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