File:  [LON-CAPA] / loncom / lond
Revision 1.553: download - view: text, annotated - select for diffs
Mon Dec 3 13:20:21 2018 UTC (5 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Trust settings

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

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