File:  [LON-CAPA] / loncom / lond
Revision 1.551: download - view: text, annotated - select for diffs
Sat Nov 24 16:19:09 2018 UTC (5 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Domain config for load balancer to use cookie to record offload target.
  Subsequent requests by same user/browser will send requests to same target
  if remote session still active, and remote node not overloaded.

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

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