File:  [LON-CAPA] / loncom / lond
Revision 1.544: download - view: text, annotated - select for diffs
Sun Jul 29 03:03:36 2018 UTC (5 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Include verification of common name when creating SSL tunnel. Fall back
  to insecure connection (if allowed) if verification fails.

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

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