File:  [LON-CAPA] / loncom / lond
Revision 1.574: download - view: text, annotated - select for diffs
Fri Feb 25 09:38:47 2022 UTC (2 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Sanity checking

    1: #!/usr/bin/perl
    2: # The LearningOnline Network
    3: # lond "LON Daemon" Server (port "LOND" 5663)
    4: #
    5: # $Id: lond,v 1.574 2022/02/25 09:38:47 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.574 $'; #' 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;             # Current domain permits hosting on client
   84:                                 # (not set if host and client share "internet domain").
   85:                                 # Values are 0 or 1; 1 if allowed.
   86: my %clientprohibited;           # Commands from client prohibited for domain's
   87:                                 # users.
   88: 
   89: my $server;
   90: 
   91: my $keymode;
   92: 
   93: my $cipher;			# Cipher key negotiated with client
   94: my $tmpsnum = 0;		# Id of tmpputs.
   95: 
   96: # 
   97: #   Connection type is:
   98: #      client                   - All client actions are allowed
   99: #      manager                  - only management functions allowed.
  100: #      both                     - Both management and client actions are allowed
  101: #
  102: 
  103: my $ConnectionType;
  104: 
  105: my %managers;			# Ip -> manager names
  106: 
  107: my %perlvar;			# Will have the apache conf defined perl vars.
  108: 
  109: my %secureconf;                 # Will have requirements for security 
  110:                                 # of lond connections
  111: 
  112: my %crlchecked;                 # Will contain clients for which the client's SSL
  113:                                 # has been checked against the cluster's Certificate
  114:                                 # Revocation List.
  115: 
  116: my $dist;
  117: 
  118: #
  119: #   The hash below is used for command dispatching, and is therefore keyed on the request keyword.
  120: #    Each element of the hash contains a reference to an array that contains:
  121: #          A reference to a sub that executes the request corresponding to the keyword.
  122: #          A flag that is true if the request must be encoded to be acceptable.
  123: #          A mask with bits as follows:
  124: #                      CLIENT_OK    - Set when the function is allowed by ordinary clients
  125: #                      MANAGER_OK   - Set when the function is allowed to manager clients.
  126: #
  127: my $CLIENT_OK  = 1;
  128: my $MANAGER_OK = 2;
  129: my %Dispatcher;
  130: 
  131: 
  132: #
  133: #  The array below are password error strings."
  134: #
  135: my $lastpwderror    = 13;		# Largest error number from lcpasswd.
  136: my @passwderrors = ("ok",
  137: 		   "pwchange_failure - lcpasswd must be run as user 'www'",
  138: 		   "pwchange_failure - lcpasswd got incorrect number of arguments",
  139: 		   "pwchange_failure - lcpasswd did not get the right nubmer of input text lines",
  140: 		   "pwchange_failure - lcpasswd too many simultaneous pwd changes in progress",
  141: 		   "pwchange_failure - lcpasswd User does not exist.",
  142: 		   "pwchange_failure - lcpasswd Incorrect current passwd",
  143: 		   "pwchange_failure - lcpasswd Unable to su to root.",
  144: 		   "pwchange_failure - lcpasswd Cannot set new passwd.",
  145: 		   "pwchange_failure - lcpasswd Username has invalid characters",
  146: 		   "pwchange_failure - lcpasswd Invalid characters in password",
  147: 		   "pwchange_failure - lcpasswd User already exists", 
  148:                    "pwchange_failure - lcpasswd Something went wrong with user addition.",
  149: 		   "pwchange_failure - lcpasswd Password mismatch",
  150: 		   "pwchange_failure - lcpasswd Error filename is invalid");
  151: 
  152: 
  153: # This array are the errors from lcinstallfile:
  154: 
  155: my @installerrors = ("ok",
  156: 		     "Initial user id of client not that of www",
  157: 		     "Usage error, not enough command line arguments",
  158: 		     "Source filename does not exist",
  159: 		     "Destination filename does not exist",
  160: 		     "Some file operation failed",
  161: 		     "Invalid table filename."
  162: 		     );
  163: 
  164: #
  165: # The %trust hash classifies commands according to type of trust 
  166: # required for execution of the command.
  167: #
  168: # When clients from a different institution request execution of a
  169: # particular command, the trust settings for that institution set
  170: # for this domain (or default domain for a multi-domain server) will
  171: # be checked to see if running the command is allowed.
  172: #
  173: # Trust types which depend on the "Trust" domain configuration
  174: # for the machine's default domain are:
  175: #
  176: # content   ("Access to this domain's content by others")
  177: # shared    ("Access to other domain's content by this domain")
  178: # enroll    ("Enrollment in this domain's courses by others")
  179: # coaurem   ("Co-author roles for this domain's users elsewhere")
  180: # othcoau   ("Co-author roles in this domain for others")
  181: # domroles  ("Domain roles in this domain assignable to others")
  182: # catalog   ("Course Catalog for this domain displayed elsewhere")
  183: # reqcrs    ("Requests for creation of courses in this domain by others")
  184: # msg       ("Users in other domains can send messages to this domain")
  185: # 
  186: # Trust type which depends on the User Session Hosting (remote) 
  187: # domain configuration for machine's default domain is: "remote".
  188: #
  189: # Trust types which depend on contents of manager.tab in 
  190: # /home/httpd/lonTabs is: "manageronly".
  191: # 
  192: # Trust type which requires client to share the same LON-CAPA
  193: # "internet domain" (i.e., same institution as this server) is:
  194: # "institutiononly".
  195: #
  196: 
  197: my %trust = (
  198:                auth => {remote => 1},
  199:                autocreatepassword => {remote => 1},
  200:                autocrsreqchecks => {remote => 1, reqcrs => 1},
  201:                autocrsrequpdate => {remote => 1},
  202:                autocrsreqvalidation => {remote => 1},
  203:                autogetsections => {remote => 1},
  204:                autoinstcodedefaults => {remote => 1, catalog => 1},
  205:                autoinstcodeformat => {remote => 1, catalog => 1},
  206:                autonewcourse => {remote => 1, reqcrs => 1},
  207:                autophotocheck => {remote => 1, enroll => 1},
  208:                autophotochoice => {remote => 1},
  209:                autophotopermission => {remote => 1, enroll => 1},
  210:                autopossibleinstcodes => {remote => 1, reqcrs => 1},
  211:                autoretrieve => {remote => 1, enroll => 1, catalog => 1},
  212:                autorun => {remote => 1, enroll => 1, reqcrs => 1},
  213:                autovalidateclass_sec => {catalog => 1},
  214:                autovalidatecourse => {remote => 1, enroll => 1},
  215:                autovalidateinstcode => {domroles => 1, remote => 1, enroll => 1},
  216:                autovalidateinstcrosslist => {remote => 1, enroll => 1},
  217:                autoinstsecreformat => {remote => 1, enroll => 1},
  218:                changeuserauth => {remote => 1, domroles => 1},
  219:                chatretr => {remote => 1, enroll => 1},
  220:                chatsend => {remote => 1, enroll => 1},
  221:                courseiddump => {remote => 1, domroles => 1, enroll => 1},
  222:                courseidput => {remote => 1, domroles => 1, enroll => 1},
  223:                courseidputhash => {remote => 1, domroles => 1, enroll => 1},
  224:                courselastaccess => {remote => 1, domroles => 1, enroll => 1},
  225:                coursesessions => {institutiononly => 1},
  226:                currentauth => {remote => 1, domroles => 1, enroll => 1},
  227:                currentdump => {remote => 1, enroll => 1},
  228:                currentversion => {remote=> 1, content => 1},
  229:                dcmaildump => {remote => 1, domroles => 1},
  230:                dcmailput => {remote => 1, domroles => 1},
  231:                del => {remote => 1, domroles => 1, enroll => 1, content => 1},
  232:                delbalcookie => {institutiononly => 1},
  233:                delusersession => {institutiononly => 1},
  234:                deldom => {remote => 1, domroles => 1}, # not currently used
  235:                devalidatecache => {institutiononly => 1},
  236:                domroleput => {remote => 1, enroll => 1},
  237:                domrolesdump => {remote => 1, catalog => 1},
  238:                du => {remote => 1, enroll => 1},
  239:                du2 => {remote => 1, enroll => 1},
  240:                dump => {remote => 1, enroll => 1, domroles => 1},
  241:                edit => {institutiononly => 1},  #not used currently
  242:                edump => {remote => 1, enroll => 1, domroles => 1},
  243:                eget => {remote => 1, domroles => 1, enroll => 1}, #not used currently
  244:                egetdom => {remote => 1, domroles => 1, enroll => 1, },
  245:                ekey => {anywhere => 1},
  246:                exit => {anywhere => 1},
  247:                fetchuserfile => {remote => 1, enroll => 1},
  248:                get => {remote => 1, domroles => 1, enroll => 1},
  249:                getdom => {anywhere => 1},
  250:                home => {anywhere => 1},
  251:                iddel => {remote => 1, enroll => 1},
  252:                idget => {remote => 1, enroll => 1},
  253:                idput => {remote => 1, domroles => 1, enroll => 1},
  254:                inc => {remote => 1, enroll => 1},
  255:                init => {anywhere => 1},
  256:                inst_usertypes => {remote => 1, domroles => 1, enroll => 1},
  257:                instemailrules => {remote => 1, domroles => 1},
  258:                instidrulecheck => {remote => 1, domroles => 1,},
  259:                instidrules => {remote => 1, domroles => 1,},
  260:                instrulecheck => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
  261:                instselfcreatecheck => {institutiononly => 1},
  262:                instuserrules => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
  263:                keys => {remote => 1,},
  264:                load => {anywhere => 1},
  265:                log => {anywhere => 1},
  266:                ls => {remote => 1, enroll => 1, content => 1,},
  267:                ls2 => {remote => 1, enroll => 1, content => 1,},
  268:                ls3 => {remote => 1, enroll => 1, content => 1,},
  269:                lti => {institutiononly => 1},
  270:                makeuser => {remote => 1, enroll => 1, domroles => 1,},
  271:                mkdiruserfile => {remote => 1, enroll => 1,},
  272:                newput => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1,},
  273:                passwd => {remote => 1},
  274:                ping => {anywhere => 1},
  275:                pong => {anywhere => 1},
  276:                pushfile => {manageronly => 1},
  277:                put => {remote => 1, enroll => 1, domroles => 1, msg => 1, content => 1, shared => 1},
  278:                putdom => {remote => 1, domroles => 1,},
  279:                putstore => {remote => 1, enroll => 1},
  280:                queryreply => {anywhere => 1},
  281:                querysend => {anywhere => 1},
  282:                querysend_activitylog => {remote => 1},
  283:                querysend_allusers => {remote => 1, domroles => 1},
  284:                querysend_courselog => {remote => 1},
  285:                querysend_fetchenrollment => {remote => 1},
  286:                querysend_getinstuser => {remote => 1},
  287:                querysend_getmultinstusers => {remote => 1},
  288:                querysend_instdirsearch => {remote => 1, domroles => 1, coaurem => 1},
  289:                querysend_institutionalphotos => {remote => 1},
  290:                querysend_portfolio_metadata => {remote => 1, content => 1},
  291:                querysend_userlog => {remote => 1, domroles => 1},
  292:                querysend_usersearch => {remote => 1, enroll => 1, coaurem => 1},
  293:                quit => {anywhere => 1},
  294:                readlonnetglobal => {institutiononly => 1},
  295:                reinit => {manageronly => 1}, #not used currently
  296:                removeuserfile => {remote => 1, enroll => 1},
  297:                renameuserfile => {remote => 1,},
  298:                restore => {remote => 1, enroll => 1, reqcrs => 1,},
  299:                rolesdel => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
  300:                rolesput => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
  301:                servercerts => {institutiononly => 1},
  302:                serverdistarch => {anywhere => 1},
  303:                serverhomeID => {anywhere => 1},
  304:                serverloncaparev => {anywhere => 1},
  305:                servertimezone => {remote => 1, enroll => 1},
  306:                setannounce => {remote => 1, domroles => 1},
  307:                sethost => {anywhere => 1},
  308:                store => {remote => 1, enroll => 1, reqcrs => 1,},
  309:                studentphoto => {remote => 1, enroll => 1},
  310:                sub => {content => 1,},
  311:                tmpdel => {institutiononly => 1},
  312:                tmpget => {institutiononly => 1},
  313:                tmpput => {remote => 1, othcoau => 1},
  314:                tokenauthuserfile => {anywhere => 1},
  315:                unsub => {content => 1,},
  316:                update => {shared => 1},
  317:                updatebalcookie => {institutiononly => 1},
  318:                updateclickers => {remote => 1},
  319:                userhassession => {anywhere => 1},
  320:                userload => {anywhere => 1},
  321:                version => {anywhere => 1}, #not used
  322:             );
  323: 
  324: #
  325: #   Statistics that are maintained and dislayed in the status line.
  326: #
  327: my $Transactions = 0;		# Number of attempted transactions.
  328: my $Failures     = 0;		# Number of transcations failed.
  329: 
  330: #   ResetStatistics: 
  331: #      Resets the statistics counters:
  332: #
  333: sub ResetStatistics {
  334:     $Transactions = 0;
  335:     $Failures     = 0;
  336: }
  337: 
  338: #------------------------------------------------------------------------
  339: #
  340: #   LocalConnection
  341: #     Completes the formation of a locally authenticated connection.
  342: #     This function will ensure that the 'remote' client is really the
  343: #     local host.  If not, the connection is closed, and the function fails.
  344: #     If so, initcmd is parsed for the name of a file containing the
  345: #     IDEA session key.  The fie is opened, read, deleted and the session
  346: #     key returned to the caller.
  347: #
  348: # Parameters:
  349: #   $Socket      - Socket open on client.
  350: #   $initcmd     - The full text of the init command.
  351: #
  352: # Returns:
  353: #     IDEA session key on success.
  354: #     undef on failure.
  355: #
  356: sub LocalConnection {
  357:     my ($Socket, $initcmd) = @_;
  358:     Debug("Attempting local connection: $initcmd client: $clientip");
  359:     if($clientip ne "127.0.0.1") {
  360: 	&logthis('<font color="red"> LocalConnection rejecting non local: '
  361: 		 ."$clientip ne 127.0.0.1 </font>");
  362: 	close $Socket;
  363: 	return undef;
  364:     }  else {
  365: 	chomp($initcmd);	# Get rid of \n in filename.
  366: 	my ($init, $type, $name) = split(/:/, $initcmd);
  367: 	Debug(" Init command: $init $type $name ");
  368: 
  369: 	# Require that $init = init, and $type = local:  Otherwise
  370: 	# the caller is insane:
  371: 
  372: 	if(($init ne "init") && ($type ne "local")) {
  373: 	    &logthis('<font color = "red"> LocalConnection: caller is insane! '
  374: 		     ."init = $init, and type = $type </font>");
  375: 	    close($Socket);;
  376: 	    return undef;
  377: 		
  378: 	}
  379: 	#  Now get the key filename:
  380: 
  381: 	my $IDEAKey = lonlocal::ReadKeyFile($name);
  382: 	return $IDEAKey;
  383:     }
  384: }
  385: #------------------------------------------------------------------------------
  386: #
  387: #  SSLConnection
  388: #   Completes the formation of an ssh authenticated connection. The
  389: #   socket is promoted to an ssl socket.  If this promotion and the associated
  390: #   certificate exchange are successful, the IDEA key is generated and sent
  391: #   to the remote peer via the SSL tunnel. The IDEA key is also returned to
  392: #   the caller after the SSL tunnel is torn down.
  393: #
  394: # Parameters:
  395: #   Name              Type             Purpose
  396: #   $Socket          IO::Socket::INET  Plaintext socket.
  397: #
  398: # Returns:
  399: #    IDEA key on success.
  400: #    undef on failure.
  401: #
  402: sub SSLConnection {
  403:     my $Socket   = shift;
  404: 
  405:     Debug("SSLConnection: ");
  406:     my $KeyFile         = lonssl::KeyFile();
  407:     if(!$KeyFile) {
  408: 	my $err = lonssl::LastError();
  409: 	&logthis("<font color=\"red\"> CRITICAL"
  410: 		 ."Can't get key file $err </font>");
  411: 	return undef;
  412:     }
  413:     my ($CACertificate,
  414: 	$Certificate) = lonssl::CertificateFile();
  415: 
  416: 
  417:     # If any of the key, certificate or certificate authority 
  418:     # certificate filenames are not defined, this can't work.
  419: 
  420:     if((!$Certificate) || (!$CACertificate)) {
  421: 	my $err = lonssl::LastError();
  422: 	&logthis("<font color=\"red\"> CRITICAL"
  423: 		 ."Can't get certificates: $err </font>");
  424: 
  425: 	return undef;
  426:     }
  427:     Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
  428: 
  429:     # Indicate to our peer that we can procede with
  430:     # a transition to ssl authentication:
  431: 
  432:     print $Socket "ok:ssl\n";
  433: 
  434:     Debug("Approving promotion -> ssl");
  435:     #  And do so:
  436: 
  437:     my $CRLFile;
  438:     unless ($crlchecked{$clientname}) {
  439:         $CRLFile = lonssl::CRLFile();
  440:         $crlchecked{$clientname} = 1;
  441:     }
  442: 
  443:     my $SSLSocket = lonssl::PromoteServerSocket($Socket,
  444: 						$CACertificate,
  445: 						$Certificate,
  446: 						$KeyFile,
  447: 						$clientname,
  448:                                                 $CRLFile,
  449:                                                 $clientversion);
  450:     if(! ($SSLSocket) ) {	# SSL socket promotion failed.
  451: 	my $err = lonssl::LastError();
  452: 	&logthis("<font color=\"red\"> CRITICAL "
  453: 		 ."SSL Socket promotion failed: $err </font>");
  454: 	return undef;
  455:     }
  456:     Debug("SSL Promotion successful");
  457: 
  458:     # 
  459:     #  The only thing we'll use the socket for is to send the IDEA key
  460:     #  to the peer:
  461: 
  462:     my $Key = lonlocal::CreateCipherKey();
  463:     print $SSLSocket "$Key\n";
  464: 
  465:     lonssl::Close($SSLSocket); 
  466: 
  467:     Debug("Key exchange complete: $Key");
  468: 
  469:     return $Key;
  470: }
  471: #
  472: #     InsecureConnection: 
  473: #        If insecure connections are allowd,
  474: #        exchange a challenge with the client to 'validate' the
  475: #        client (not really, but that's the protocol):
  476: #        We produce a challenge string that's sent to the client.
  477: #        The client must then echo the challenge verbatim to us.
  478: #
  479: #  Parameter:
  480: #      Socket      - Socket open on the client.
  481: #  Returns:
  482: #      1           - success.
  483: #      0           - failure (e.g.mismatch or insecure not allowed).
  484: #
  485: sub InsecureConnection {
  486:     my $Socket  =  shift;
  487: 
  488:     #   Don't even start if insecure connections are not allowed.
  489:     #   return 0 if Insecure connections not allowed.
  490:     #
  491:     if (ref($secureconf{'connfrom'}) eq 'HASH') {
  492:         if ($clientsamedom) {
  493:             if ($secureconf{'connfrom'}{'dom'} eq 'req') {
  494:                 return 0;
  495:             } 
  496:         } elsif ($clientsameinst) {
  497:             if ($secureconf{'connfrom'}{'intdom'} eq 'req') {
  498:                 return 0;
  499:             }
  500:         } else {
  501:             if ($secureconf{'connfrom'}{'other'} eq 'req') {
  502:                 return 0;
  503:             }
  504:         }
  505:     } elsif (!$perlvar{londAllowInsecure}) {
  506: 	return 0;
  507:     }
  508: 
  509:     #   Fabricate a challenge string and send it..
  510: 
  511:     my $challenge = "$$".time;	# pid + time.
  512:     print $Socket "$challenge\n";
  513:     &status("Waiting for challenge reply");
  514: 
  515:     my $answer = <$Socket>;
  516:     $answer    =~s/\W//g;
  517:     if($challenge eq $answer) {
  518: 	return 1;
  519:     } else {
  520: 	logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
  521: 	&status("No challenge reqply");
  522: 	return 0;
  523:     }
  524:     
  525: 
  526: }
  527: #
  528: #   Safely execute a command (as long as it's not a shel command and doesn
  529: #   not require/rely on shell escapes.   The function operates by doing a
  530: #   a pipe based fork and capturing stdout and stderr  from the pipe.
  531: #
  532: # Formal Parameters:
  533: #     $line                    - A line of text to be executed as a command.
  534: # Returns:
  535: #     The output from that command.  If the output is multiline the caller
  536: #     must know how to split up the output.
  537: #
  538: #
  539: sub execute_command {
  540:     my ($line)    = @_;
  541:     my @words     = split(/\s/, $line);	# Bust the command up into words.
  542:     my $output    = "";
  543: 
  544:     my $pid = open(CHILD, "-|");
  545:     
  546:     if($pid) {			# Parent process
  547: 	Debug("In parent process for execute_command");
  548: 	my @data = <CHILD>;	# Read the child's outupt...
  549: 	close CHILD;
  550: 	foreach my $output_line (@data) {
  551: 	    Debug("Adding $output_line");
  552: 	    $output .= $output_line; # Presumably has a \n on it.
  553: 	}
  554: 
  555:     } else {			# Child process
  556: 	close (STDERR);
  557: 	open  (STDERR, ">&STDOUT");# Combine stderr, and stdout...
  558: 	exec(@words);		# won't return.
  559:     }
  560:     return $output;
  561: }
  562: 
  563: 
  564: #   GetCertificate: Given a transaction that requires a certificate,
  565: #   this function will extract the certificate from the transaction
  566: #   request.  Note that at this point, the only concept of a certificate
  567: #   is the hostname to which we are connected.
  568: #
  569: #   Parameter:
  570: #      request   - The request sent by our client (this parameterization may
  571: #                  need to change when we really use a certificate granting
  572: #                  authority.
  573: #
  574: sub GetCertificate {
  575:     my $request = shift;
  576: 
  577:     return $clientip;
  578: }
  579: 
  580: #
  581: #   Return true if client is a manager.
  582: #
  583: sub isManager {
  584:     return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
  585: }
  586: #
  587: #   Return tru if client can do client functions
  588: #
  589: sub isClient {
  590:     return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
  591: }
  592: 
  593: 
  594: #
  595: #   ReadManagerTable: Reads in the current manager table. For now this is
  596: #                     done on each manager authentication because:
  597: #                     - These authentications are not frequent
  598: #                     - This allows dynamic changes to the manager table
  599: #                       without the need to signal to the lond.
  600: #
  601: sub ReadManagerTable {
  602: 
  603:     &Debug("Reading manager table");
  604:     #   Clean out the old table first..
  605: 
  606:    foreach my $key (keys %managers) {
  607:       delete $managers{$key};
  608:    }
  609: 
  610:    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
  611:    if (!open (MANAGERS, $tablename)) {
  612:        my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
  613:        if (&Apache::lonnet::is_LC_dns($hostname)) {
  614:            &logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
  615:        }
  616:        return;
  617:    }
  618:    while(my $host = <MANAGERS>) {
  619:       chomp($host);
  620:       if ($host =~ "^#") {                  # Comment line.
  621:          next;
  622:       }
  623:       if (!defined &Apache::lonnet::get_host_ip($host)) { # This is a non cluster member
  624: 	    #  The entry is of the form:
  625: 	    #    cluname:hostname
  626: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
  627: 	    #            the host key.
  628: 	    #  hostname- The dns name of the host.
  629: 	    #
  630:           my($cluname, $dnsname) = split(/:/, $host);
  631:           
  632:           my $ip = gethostbyname($dnsname);
  633:           if(defined($ip)) {                 # bad names don't deserve entry.
  634:             my $hostip = inet_ntoa($ip);
  635:             $managers{$hostip} = $cluname;
  636:             logthis('<font color="green"> registering manager '.
  637:                     "$dnsname as $cluname with $hostip </font>\n");
  638:          }
  639:       } else {
  640:          logthis('<font color="green"> existing host'." $host</font>\n");
  641:          $managers{&Apache::lonnet::get_host_ip($host)} = $host;  # Use info from cluster tab if cluster memeber
  642:       }
  643:    }
  644: }
  645: 
  646: #
  647: #  ValidManager: Determines if a given certificate represents a valid manager.
  648: #                in this primitive implementation, the 'certificate' is
  649: #                just the connecting loncapa client name.  This is checked
  650: #                against a valid client list in the configuration.
  651: #
  652: #                  
  653: sub ValidManager {
  654:     my $certificate = shift; 
  655: 
  656:     return isManager;
  657: }
  658: #
  659: #  CopyFile:  Called as part of the process of installing a 
  660: #             new configuration file.  This function copies an existing
  661: #             file to a backup file.
  662: # Parameters:
  663: #     oldfile  - Name of the file to backup.
  664: #     newfile  - Name of the backup file.
  665: # Return:
  666: #     0   - Failure (errno has failure reason).
  667: #     1   - Success.
  668: #
  669: sub CopyFile {
  670: 
  671:     my ($oldfile, $newfile) = @_;
  672: 
  673:     if (! copy($oldfile,$newfile)) {
  674:         return 0;
  675:     }
  676:     chmod(0660, $newfile);
  677:     return 1;
  678: }
  679: #
  680: #  Host files are passed out with externally visible host IPs.
  681: #  If, for example, we are behind a fire-wall or NAT host, our 
  682: #  internally visible IP may be different than the externally
  683: #  visible IP.  Therefore, we always adjust the contents of the
  684: #  host file so that the entry for ME is the IP that we believe
  685: #  we have.  At present, this is defined as the entry that
  686: #  DNS has for us.  If by some chance we are not able to get a
  687: #  DNS translation for us, then we assume that the host.tab file
  688: #  is correct.  
  689: #    BUGBUGBUG - in the future, we really should see if we can
  690: #       easily query the interface(s) instead.
  691: # Parameter(s):
  692: #     contents    - The contents of the host.tab to check.
  693: # Returns:
  694: #     newcontents - The adjusted contents.
  695: #
  696: #
  697: sub AdjustHostContents {
  698:     my $contents  = shift;
  699:     my $adjusted;
  700:     my $me        = $perlvar{'lonHostID'};
  701: 
  702:     foreach my $line (split(/\n/,$contents)) {
  703: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/) ||
  704:              ($line =~ /^\s*\^/))) {
  705: 	    chomp($line);
  706: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
  707: 	    if ($id eq $me) {
  708: 		my $ip = gethostbyname($name);
  709: 		my $ipnew = inet_ntoa($ip);
  710: 		$ip = $ipnew;
  711: 		#  Reconstruct the host line and append to adjusted:
  712: 		
  713: 		my $newline = "$id:$domain:$role:$name:$ip";
  714: 		if($maxcon ne "") { # Not all hosts have loncnew tuning params
  715: 		    $newline .= ":$maxcon:$idleto:$mincon";
  716: 		}
  717: 		$adjusted .= $newline."\n";
  718: 		
  719: 	    } else {		# Not me, pass unmodified.
  720: 		$adjusted .= $line."\n";
  721: 	    }
  722: 	} else {                  # Blank or comment never re-written.
  723: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
  724: 	}
  725:     }
  726:     return $adjusted;
  727: }
  728: #
  729: #   InstallFile: Called to install an administrative file:
  730: #       - The file is created int a temp directory called <name>.tmp
  731: #       - lcinstall file is called to install the file.
  732: #         since the web app has no direct write access to the table directory
  733: #
  734: #  Parameters:
  735: #       Name of the file
  736: #       File Contents.
  737: #  Return:
  738: #      nonzero - success.
  739: #      0       - failure and $! has an errno.
  740: # Assumptions:
  741: #    File installtion is a relatively infrequent
  742: #
  743: sub InstallFile {
  744: 
  745:     my ($Filename, $Contents) = @_;
  746: #     my $TempFile = $Filename.".tmp";
  747:     my $exedir = $perlvar{'lonDaemons'};
  748:     my $tmpdir = $exedir.'/tmp/';
  749:     my $TempFile = $tmpdir."TempTableFile.tmp";
  750: 
  751:     #  Open the file for write:
  752: 
  753:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
  754:     if(!(defined $fh)) {
  755: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
  756: 	return 0;
  757:     }
  758:     #  write the contents of the file:
  759: 
  760:     print $fh ($Contents); 
  761:     $fh->close;			# In case we ever have a filesystem w. locking
  762: 
  763:     chmod(0664, $TempFile);	# Everyone can write it.
  764: 
  765:     # Use lcinstall file to put the file in the table directory...
  766: 
  767:     &Debug("Opening pipe to $exedir/lcinstallfile $TempFile $Filename");
  768:     my $pf = IO::File->new("| $exedir/lcinstallfile   $TempFile $Filename > $exedir/logs/lcinstallfile.log");
  769:     close $pf;
  770:     my $err = $?;
  771:     &Debug("Status is $err");
  772:     if ($err != 0) {
  773: 	my $msg = $err;
  774: 	if ($err < @installerrors) {
  775: 	    $msg = $installerrors[$err];
  776: 	}
  777: 	&logthis("Install failed for table file $Filename : $msg");
  778: 	return 0;
  779:     }
  780: 
  781:     # Remove the temp file:
  782: 
  783:     unlink($TempFile);
  784: 
  785:     return 1;
  786: }
  787: 
  788: 
  789: #
  790: #   ConfigFileFromSelector: converts a configuration file selector
  791: #                 into a configuration file pathname.
  792: #                 Supports the following file selectors: 
  793: #                 hosts, domain, dns_hosts, dns_domain  
  794: #
  795: #
  796: #  Parameters:
  797: #      selector  - Configuration file selector.
  798: #  Returns:
  799: #      Full path to the file or undef if the selector is invalid.
  800: #
  801: sub ConfigFileFromSelector {
  802:     my $selector   = shift;
  803:     my $tablefile;
  804: 
  805:     if ($selector eq 'loncapaCAcrl') {
  806:         my $tabledir = $perlvar{'lonCertificateDirectory'};
  807:         if (-d $tabledir) {
  808:             $tablefile =  $tabledir.'/'.$selector.'.pem';
  809:         }
  810:     } else {
  811:         my $tabledir = $perlvar{'lonTabDir'}.'/';
  812:         if (($selector eq "hosts") || ($selector eq "domain") || 
  813:             ($selector eq "dns_hosts") || ($selector eq "dns_domain")) {
  814: 	    $tablefile =  $tabledir.$selector.'.tab';
  815:         }
  816:     }
  817:     return $tablefile;
  818: }
  819: #
  820: #   PushFile:  Called to do an administrative push of a file.
  821: #              - Ensure the file being pushed is one we support.
  822: #              - Backup the old file to <filename.saved>
  823: #              - Separate the contents of the new file out from the
  824: #                rest of the request.
  825: #              - Write the new file.
  826: #  Parameter:
  827: #     Request - The entire user request.  This consists of a : separated
  828: #               string pushfile:tablename:contents.
  829: #     NOTE:  The contents may have :'s in it as well making things a bit
  830: #            more interesting... but not much.
  831: #  Returns:
  832: #     String to send to client ("ok" or "refused" if bad file).
  833: #
  834: sub PushFile {
  835:     my $request = shift;
  836:     my ($command, $filename, $contents) = split(":", $request, 3);
  837:     &Debug("PushFile");
  838:     
  839:     #  At this point in time, pushes for only the following tables and
  840:     #  CRL file are supported:
  841:     #   hosts.tab  ($filename eq host).
  842:     #   domain.tab ($filename eq domain).
  843:     #   dns_hosts.tab ($filename eq dns_host).
  844:     #   dns_domain.tab ($filename eq dns_domain).
  845:     #   loncapaCAcrl.pem ($filename eq loncapaCAcrl).
  846:     # Construct the destination filename or reject the request.
  847:     #
  848:     # lonManage is supposed to ensure this, however this session could be
  849:     # part of some elaborate spoof that managed somehow to authenticate.
  850:     #
  851: 
  852: 
  853:     my $tablefile = ConfigFileFromSelector($filename);
  854:     if(! (defined $tablefile)) {
  855: 	return "refused";
  856:     }
  857: 
  858:     #  If the file being pushed is the host file, we adjust the entry for ourself so that the
  859:     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
  860:     #  to conceive of conditions where we don't have a DNS entry locally.  This is possible in a 
  861:     #  network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
  862:     #  that possibilty.
  863: 
  864:     if($filename eq "host") {
  865: 	$contents = AdjustHostContents($contents);
  866:     } elsif (($filename eq 'dns_host') || ($filename eq 'dns_domain') ||
  867:              ($filename eq 'loncapaCAcrl')) {
  868:         if ($contents eq '') {
  869:             &logthis('<font color="red"> Pushfile: unable to install '
  870:                     .$tablefile." - no data received from push. </font>");
  871:             return 'error: push had no data';
  872:         }
  873:         if (&Apache::lonnet::get_host_ip($clientname)) {
  874:             my $clienthost = &Apache::lonnet::hostname($clientname);
  875:             if ($managers{$clientip} eq $clientname) {
  876:                 my $clientprotocol = $Apache::lonnet::protocol{$clientname};
  877:                 $clientprotocol = 'http' if ($clientprotocol ne 'https');
  878:                 my $url;
  879:                 if ($filename eq 'loncapaCAcrl') {
  880:                     $url = '/adm/dns/loncapaCRL';
  881:                 } else {
  882:                     $url = '/adm/'.$filename;
  883:                     $url =~ s{_}{/};
  884:                 }
  885:                 my $request=new HTTP::Request('GET',"$clientprotocol://$clienthost$url");
  886:                 my $response = LONCAPA::LWPReq::makerequest($clientname,$request,'',\%perlvar,60,0);
  887:                 if ($response->is_error()) {
  888:                     &logthis('<font color="red"> Pushfile: unable to install '
  889:                             .$tablefile." - error attempting to pull data. </font>");
  890:                     return 'error: pull failed';
  891:                 } else {
  892:                     my $result = $response->content;
  893:                     chomp($result);
  894:                     unless ($result eq $contents) {
  895:                         &logthis('<font color="red"> Pushfile: unable to install '
  896:                                 .$tablefile." - pushed data and pulled data differ. </font>");
  897:                         my $pushleng = length($contents);
  898:                         my $pullleng = length($result);
  899:                         if ($pushleng != $pullleng) {
  900:                             return "error: $pushleng vs $pullleng bytes";
  901:                         } else {
  902:                             return "error: mismatch push and pull";
  903:                         }
  904:                     }
  905:                 }
  906:             }
  907:         }
  908:     }
  909: 
  910:     #  Install the new file:
  911: 
  912:     &logthis("Installing new $tablefile contents:\n$contents");
  913:     if(!InstallFile($tablefile, $contents)) {
  914: 	&logthis('<font color="red"> Pushfile: unable to install '
  915: 	 .$tablefile." $! </font>");
  916: 	return "error:$!";
  917:     } else {
  918: 	&logthis('<font color="green"> Installed new '.$tablefile
  919: 		 ." - transaction by: $clientname ($clientip)</font>");
  920:         my $adminmail = $perlvar{'lonAdmEMail'};
  921:         my $admindom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
  922:         if ($admindom ne '') {
  923:             my %domconfig =
  924:                 &Apache::lonnet::get_dom('configuration',['contacts'],$admindom);
  925:             if (ref($domconfig{'contacts'}) eq 'HASH') {
  926:                 if ($domconfig{'contacts'}{'adminemail'} ne '') {
  927:                     $adminmail = $domconfig{'contacts'}{'adminemail'};
  928:                 }
  929:             }
  930:         }
  931:         if ($adminmail =~ /^[^\@]+\@[^\@]+$/) {
  932:             my $msg = new Mail::Send;
  933:             $msg->to($adminmail);
  934:             $msg->subject('LON-CAPA DNS update on '.$perlvar{'lonHostID'});
  935:             $msg->add('Content-type','text/plain; charset=UTF-8');
  936:             if (my $fh = $msg->open()) {
  937:                 print $fh 'Update to '.$tablefile.' from Cluster Manager '.
  938:                           "$clientname ($clientip)\n";
  939:                 $fh->close;
  940:             }
  941:         }
  942:     }
  943: 
  944:     #  Indicate success:
  945:  
  946:     return "ok";
  947: 
  948: }
  949: 
  950: #
  951: #  Called to re-init either lonc or lond.
  952: #
  953: #  Parameters:
  954: #    request   - The full request by the client.  This is of the form
  955: #                reinit:<process>  
  956: #                where <process> is allowed to be either of 
  957: #                lonc or lond
  958: #
  959: #  Returns:
  960: #     The string to be sent back to the client either:
  961: #   ok         - Everything worked just fine.
  962: #   error:why  - There was a failure and why describes the reason.
  963: #
  964: #
  965: sub ReinitProcess {
  966:     my $request = shift;
  967: 
  968: 
  969:     # separate the request (reinit) from the process identifier and
  970:     # validate it producing the name of the .pid file for the process.
  971:     #
  972:     #
  973:     my ($junk, $process) = split(":", $request);
  974:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
  975:     if($process eq 'lonc') {
  976: 	$processpidfile = $processpidfile."lonc.pid";
  977: 	if (!open(PIDFILE, "< $processpidfile")) {
  978: 	    return "error:Open failed for $processpidfile";
  979: 	}
  980: 	my $loncpid = <PIDFILE>;
  981: 	close(PIDFILE);
  982: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
  983: 		."</font>");
  984: 	kill("USR2", $loncpid);
  985:     } elsif ($process eq 'lond') {
  986: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
  987: 	&UpdateHosts;			# Lond is us!!
  988:     } else {
  989: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
  990: 		 ."</font>");
  991: 	return "error:Invalid process identifier $process";
  992:     }
  993:     return 'ok';
  994: }
  995: #   Validate a line in a configuration file edit script:
  996: #   Validation includes:
  997: #     - Ensuring the command is valid.
  998: #     - Ensuring the command has sufficient parameters
  999: #   Parameters:
 1000: #     scriptline - A line to validate (\n has been stripped for what it's worth).
 1001: #
 1002: #   Return:
 1003: #      0     - Invalid scriptline.
 1004: #      1     - Valid scriptline
 1005: #  NOTE:
 1006: #     Only the command syntax is checked, not the executability of the
 1007: #     command.
 1008: #
 1009: sub isValidEditCommand {
 1010:     my $scriptline = shift;
 1011: 
 1012:     #   Line elements are pipe separated:
 1013: 
 1014:     my ($command, $key, $newline)  = split(/\|/, $scriptline);
 1015:     &logthis('<font color="green"> isValideditCommand checking: '.
 1016: 	     "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
 1017:     
 1018:     if ($command eq "delete") {
 1019: 	#
 1020: 	#   key with no newline.
 1021: 	#
 1022: 	if( ($key eq "") || ($newline ne "")) {
 1023: 	    return 0;		# Must have key but no newline.
 1024: 	} else {
 1025: 	    return 1;		# Valid syntax.
 1026: 	}
 1027:     } elsif ($command eq "replace") {
 1028: 	#
 1029: 	#   key and newline:
 1030: 	#
 1031: 	if (($key eq "") || ($newline eq "")) {
 1032: 	    return 0;
 1033: 	} else {
 1034: 	    return 1;
 1035: 	}
 1036:     } elsif ($command eq "append") {
 1037: 	if (($key ne "") && ($newline eq "")) {
 1038: 	    return 1;
 1039: 	} else {
 1040: 	    return 0;
 1041: 	}
 1042:     } else {
 1043: 	return 0;		# Invalid command.
 1044:     }
 1045:     return 0;			# Should not get here!!!
 1046: }
 1047: #
 1048: #   ApplyEdit - Applies an edit command to a line in a configuration 
 1049: #               file.  It is the caller's responsiblity to validate the
 1050: #               edit line.
 1051: #   Parameters:
 1052: #      $directive - A single edit directive to apply.  
 1053: #                   Edit directives are of the form:
 1054: #                  append|newline      - Appends a new line to the file.
 1055: #                  replace|key|newline - Replaces the line with key value 'key'
 1056: #                  delete|key          - Deletes the line with key value 'key'.
 1057: #      $editor   - A config file editor object that contains the
 1058: #                  file being edited.
 1059: #
 1060: sub ApplyEdit {
 1061: 
 1062:     my ($directive, $editor) = @_;
 1063: 
 1064:     # Break the directive down into its command and its parameters
 1065:     # (at most two at this point.  The meaning of the parameters, if in fact
 1066:     #  they exist depends on the command).
 1067: 
 1068:     my ($command, $p1, $p2) = split(/\|/, $directive);
 1069: 
 1070:     if($command eq "append") {
 1071: 	$editor->Append($p1);	          # p1 - key p2 null.
 1072:     } elsif ($command eq "replace") {
 1073: 	$editor->ReplaceLine($p1, $p2);   # p1 - key p2 = newline.
 1074:     } elsif ($command eq "delete") {
 1075: 	$editor->DeleteLine($p1);         # p1 - key p2 null.
 1076:     } else {			          # Should not get here!!!
 1077: 	die "Invalid command given to ApplyEdit $command"
 1078:     }
 1079: }
 1080: #
 1081: # AdjustOurHost:
 1082: #           Adjusts a host file stored in a configuration file editor object
 1083: #           for the true IP address of this host. This is necessary for hosts
 1084: #           that live behind a firewall.
 1085: #           Those hosts have a publicly distributed IP of the firewall, but
 1086: #           internally must use their actual IP.  We assume that a given
 1087: #           host only has a single IP interface for now.
 1088: # Formal Parameters:
 1089: #     editor   - The configuration file editor to adjust.  This
 1090: #                editor is assumed to contain a hosts.tab file.
 1091: # Strategy:
 1092: #    - Figure out our hostname.
 1093: #    - Lookup the entry for this host.
 1094: #    - Modify the line to contain our IP
 1095: #    - Do a replace for this host.
 1096: sub AdjustOurHost {
 1097:     my $editor        = shift;
 1098: 
 1099:     # figure out who I am.
 1100: 
 1101:     my $myHostName    = $perlvar{'lonHostID'}; # LonCAPA hostname.
 1102: 
 1103:     #  Get my host file entry.
 1104: 
 1105:     my $ConfigLine    = $editor->Find($myHostName);
 1106:     if(! (defined $ConfigLine)) {
 1107: 	die "AdjustOurHost - no entry for me in hosts file $myHostName";
 1108:     }
 1109:     # figure out my IP:
 1110:     #   Use the config line to get my hostname.
 1111:     #   Use gethostbyname to translate that into an IP address.
 1112:     #
 1113:     my ($id,$domain,$role,$name,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
 1114:     #
 1115:     #  Reassemble the config line from the elements in the list.
 1116:     #  Note that if the loncnew items were not present before, they will
 1117:     #  be now even if they would be empty
 1118:     #
 1119:     my $newConfigLine = $id;
 1120:     foreach my $item ($domain, $role, $name, $maxcon, $idleto, $mincon) {
 1121: 	$newConfigLine .= ":".$item;
 1122:     }
 1123:     #  Replace the line:
 1124: 
 1125:     $editor->ReplaceLine($id, $newConfigLine);
 1126:     
 1127: }
 1128: #
 1129: #   ReplaceConfigFile:
 1130: #              Replaces a configuration file with the contents of a
 1131: #              configuration file editor object.
 1132: #              This is done by:
 1133: #              - Copying the target file to <filename>.old
 1134: #              - Writing the new file to <filename>.tmp
 1135: #              - Moving <filename.tmp>  -> <filename>
 1136: #              This laborious process ensures that the system is never without
 1137: #              a configuration file that's at least valid (even if the contents
 1138: #              may be dated).
 1139: #   Parameters:
 1140: #        filename   - Name of the file to modify... this is a full path.
 1141: #        editor     - Editor containing the file.
 1142: #
 1143: sub ReplaceConfigFile {
 1144:     
 1145:     my ($filename, $editor) = @_;
 1146: 
 1147:     CopyFile ($filename, $filename.".old");
 1148: 
 1149:     my $contents  = $editor->Get(); # Get the contents of the file.
 1150: 
 1151:     InstallFile($filename, $contents);
 1152: }
 1153: #   
 1154: #
 1155: #   Called to edit a configuration table  file
 1156: #   Parameters:
 1157: #      request           - The entire command/request sent by lonc or lonManage
 1158: #   Return:
 1159: #      The reply to send to the client.
 1160: #
 1161: sub EditFile {
 1162:     my $request = shift;
 1163: 
 1164:     #  Split the command into it's pieces:  edit:filetype:script
 1165: 
 1166:     my ($cmd, $filetype, $script) = split(/:/, $request,3);	# : in script
 1167: 
 1168:     #  Check the pre-coditions for success:
 1169: 
 1170:     if($cmd != "edit") {	# Something is amiss afoot alack.
 1171: 	return "error:edit request detected, but request != 'edit'\n";
 1172:     }
 1173:     if( ($filetype ne "hosts")  &&
 1174: 	($filetype ne "domain")) {
 1175: 	return "error:edit requested with invalid file specifier: $filetype \n";
 1176:     }
 1177: 
 1178:     #   Split the edit script and check it's validity.
 1179: 
 1180:     my @scriptlines = split(/\n/, $script);  # one line per element.
 1181:     my $linecount   = scalar(@scriptlines);
 1182:     for(my $i = 0; $i < $linecount; $i++) {
 1183: 	chomp($scriptlines[$i]);
 1184: 	if(!isValidEditCommand($scriptlines[$i])) {
 1185: 	    return "error:edit with bad script line: '$scriptlines[$i]' \n";
 1186: 	}
 1187:     }
 1188: 
 1189:     #   Execute the edit operation.
 1190:     #   - Create a config file editor for the appropriate file and 
 1191:     #   - execute each command in the script:
 1192:     #
 1193:     my $configfile = ConfigFileFromSelector($filetype);
 1194:     if (!(defined $configfile)) {
 1195: 	return "refused\n";
 1196:     }
 1197:     my $editor = ConfigFileEdit->new($configfile);
 1198: 
 1199:     for (my $i = 0; $i < $linecount; $i++) {
 1200: 	ApplyEdit($scriptlines[$i], $editor);
 1201:     }
 1202:     # If the file is the host file, ensure that our host is
 1203:     # adjusted to have our ip:
 1204:     #
 1205:     if($filetype eq "host") {
 1206: 	AdjustOurHost($editor);
 1207:     }
 1208:     #  Finally replace the current file with our file.
 1209:     #
 1210:     ReplaceConfigFile($configfile, $editor);
 1211: 
 1212:     return "ok\n";
 1213: }
 1214: 
 1215: #   read_profile
 1216: #
 1217: #   Returns a set of specific entries from a user's profile file.
 1218: #   this is a utility function that is used by both get_profile_entry and
 1219: #   get_profile_entry_encrypted.
 1220: #
 1221: # Parameters:
 1222: #    udom       - Domain in which the user exists.
 1223: #    uname      - User's account name (loncapa account)
 1224: #    namespace  - The profile namespace to open.
 1225: #    what       - A set of & separated queries.
 1226: # Returns:
 1227: #    If all ok: - The string that needs to be shipped back to the user.
 1228: #    If failure - A string that starts with error: followed by the failure
 1229: #                 reason.. note that this probabyl gets shipped back to the
 1230: #                 user as well.
 1231: #
 1232: sub read_profile {
 1233:     my ($udom, $uname, $namespace, $what) = @_;
 1234:     
 1235:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 1236: 				 &GDBM_READER());
 1237:     if ($hashref) {
 1238:         my @queries=split(/\&/,$what);
 1239:         if ($namespace eq 'roles') {
 1240:             @queries = map { &unescape($_); } @queries; 
 1241:         }
 1242:         my $qresult='';
 1243: 	
 1244: 	for (my $i=0;$i<=$#queries;$i++) {
 1245: 	    $qresult.="$hashref->{$queries[$i]}&";    # Presumably failure gives empty string.
 1246: 	}
 1247: 	$qresult=~s/\&$//;              # Remove trailing & from last lookup.
 1248: 	if (&untie_user_hash($hashref)) {
 1249: 	    return $qresult;
 1250: 	} else {
 1251: 	    return "error: ".($!+0)." untie (GDBM) Failed";
 1252: 	}
 1253:     } else {
 1254: 	if ($!+0 == 2) {
 1255: 	    return "error:No such file or GDBM reported bad block error";
 1256: 	} else {
 1257: 	    return "error: ".($!+0)." tie (GDBM) Failed";
 1258: 	}
 1259:     }
 1260: 
 1261: }
 1262: #--------------------- Request Handlers --------------------------------------------
 1263: #
 1264: #   By convention each request handler registers itself prior to the sub 
 1265: #   declaration:
 1266: #
 1267: 
 1268: #++
 1269: #
 1270: #  Handles ping requests.
 1271: #  Parameters:
 1272: #      $cmd    - the actual keyword that invoked us.
 1273: #      $tail   - the tail of the request that invoked us.
 1274: #      $replyfd- File descriptor connected to the client
 1275: #  Implicit Inputs:
 1276: #      $currenthostid - Global variable that carries the name of the host we are
 1277: #                       known as.
 1278: #  Returns:
 1279: #      1       - Ok to continue processing.
 1280: #      0       - Program should exit.
 1281: #  Side effects:
 1282: #      Reply information is sent to the client.
 1283: sub ping_handler {
 1284:     my ($cmd, $tail, $client) = @_;
 1285:     Debug("$cmd $tail $client .. $currenthostid:");
 1286:    
 1287:     Reply( $client,\$currenthostid,"$cmd:$tail");
 1288:    
 1289:     return 1;
 1290: }
 1291: &register_handler("ping", \&ping_handler, 0, 1, 1);       # Ping unencoded, client or manager.
 1292: 
 1293: #++
 1294: #
 1295: # Handles pong requests.  Pong replies with our current host id, and
 1296: #                         the results of a ping sent to us via our lonc.
 1297: #
 1298: # Parameters:
 1299: #      $cmd    - the actual keyword that invoked us.
 1300: #      $tail   - the tail of the request that invoked us.
 1301: #      $replyfd- File descriptor connected to the client
 1302: #  Implicit Inputs:
 1303: #      $currenthostid - Global variable that carries the name of the host we are
 1304: #                       connected to.
 1305: #  Returns:
 1306: #      1       - Ok to continue processing.
 1307: #      0       - Program should exit.
 1308: #  Side effects:
 1309: #      Reply information is sent to the client.
 1310: sub pong_handler {
 1311:     my ($cmd, $tail, $replyfd) = @_;
 1312: 
 1313:     my $reply=&Apache::lonnet::reply("ping",$clientname);
 1314:     &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail"); 
 1315:     return 1;
 1316: }
 1317: &register_handler("pong", \&pong_handler, 0, 1, 1);       # Pong unencoded, client or manager
 1318: 
 1319: #++
 1320: #      Called to establish an encrypted session key with the remote client.
 1321: #      Note that with secure lond, in most cases this function is never
 1322: #      invoked.  Instead, the secure session key is established either
 1323: #      via a local file that's locked down tight and only lives for a short
 1324: #      time, or via an ssl tunnel...and is generated from a bunch-o-random
 1325: #      bits from /dev/urandom, rather than the predictable pattern used by
 1326: #      by this sub.  This sub is only used in the old-style insecure
 1327: #      key negotiation.
 1328: # Parameters:
 1329: #      $cmd    - the actual keyword that invoked us.
 1330: #      $tail   - the tail of the request that invoked us.
 1331: #      $replyfd- File descriptor connected to the client
 1332: #  Implicit Inputs:
 1333: #      $currenthostid - Global variable that carries the name of the host
 1334: #                       known as.
 1335: #      $clientname    - Global variable that carries the name of the host we're connected to.
 1336: #  Returns:
 1337: #      1       - Ok to continue processing.
 1338: #      0       - Program should exit.
 1339: #  Implicit Outputs:
 1340: #      Reply information is sent to the client.
 1341: #      $cipher is set with a reference to a new IDEA encryption object.
 1342: #
 1343: sub establish_key_handler {
 1344:     my ($cmd, $tail, $replyfd) = @_;
 1345: 
 1346:     my $buildkey=time.$$.int(rand 100000);
 1347:     $buildkey=~tr/1-6/A-F/;
 1348:     $buildkey=int(rand 100000).$buildkey.int(rand 100000);
 1349:     my $key=$currenthostid.$clientname;
 1350:     $key=~tr/a-z/A-Z/;
 1351:     $key=~tr/G-P/0-9/;
 1352:     $key=~tr/Q-Z/0-9/;
 1353:     $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
 1354:     $key=substr($key,0,32);
 1355:     my $cipherkey=pack("H32",$key);
 1356:     $cipher=new IDEA $cipherkey;
 1357:     &Reply($replyfd, \$buildkey, "$cmd:$tail"); 
 1358:    
 1359:     return 1;
 1360: 
 1361: }
 1362: &register_handler("ekey", \&establish_key_handler, 0, 1,1);
 1363: 
 1364: #     Handler for the load command.  Returns the current system load average
 1365: #     to the requestor.
 1366: #
 1367: # Parameters:
 1368: #      $cmd    - the actual keyword that invoked us.
 1369: #      $tail   - the tail of the request that invoked us.
 1370: #      $replyfd- File descriptor connected to the client
 1371: #  Implicit Inputs:
 1372: #      $currenthostid - Global variable that carries the name of the host
 1373: #                       known as.
 1374: #      $clientname    - Global variable that carries the name of the host we're connected to.
 1375: #  Returns:
 1376: #      1       - Ok to continue processing.
 1377: #      0       - Program should exit.
 1378: #  Side effects:
 1379: #      Reply information is sent to the client.
 1380: sub load_handler {
 1381:     my ($cmd, $tail, $replyfd) = @_;
 1382: 
 1383: 
 1384: 
 1385:    # Get the load average from /proc/loadavg and calculate it as a percentage of
 1386:    # the allowed load limit as set by the perl global variable lonLoadLim
 1387: 
 1388:     my $loadavg;
 1389:     my $loadfile=IO::File->new('/proc/loadavg');
 1390:    
 1391:     $loadavg=<$loadfile>;
 1392:     $loadavg =~ s/\s.*//g;                      # Extract the first field only.
 1393:    
 1394:     my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
 1395: 
 1396:     &Reply( $replyfd, \$loadpercent, "$cmd:$tail");
 1397:    
 1398:     return 1;
 1399: }
 1400: &register_handler("load", \&load_handler, 0, 1, 0);
 1401: 
 1402: #
 1403: #   Process the userload request.  This sub returns to the client the current
 1404: #  user load average.  It can be invoked either by clients or managers.
 1405: #
 1406: # Parameters:
 1407: #      $cmd    - the actual keyword that invoked us.
 1408: #      $tail   - the tail of the request that invoked us.
 1409: #      $replyfd- File descriptor connected to the client
 1410: #  Implicit Inputs:
 1411: #      $currenthostid - Global variable that carries the name of the host
 1412: #                       known as.
 1413: #      $clientname    - Global variable that carries the name of the host we're connected to.
 1414: #  Returns:
 1415: #      1       - Ok to continue processing.
 1416: #      0       - Program should exit
 1417: # Implicit inputs:
 1418: #     whatever the userload() function requires.
 1419: #  Implicit outputs:
 1420: #     the reply is written to the client.
 1421: #
 1422: sub user_load_handler {
 1423:     my ($cmd, $tail, $replyfd) = @_;
 1424: 
 1425:     my $userloadpercent=&Apache::lonnet::userload();
 1426:     &Reply($replyfd, \$userloadpercent, "$cmd:$tail");
 1427:     
 1428:     return 1;
 1429: }
 1430: &register_handler("userload", \&user_load_handler, 0, 1, 0);
 1431: 
 1432: #   Process a request for the authorization type of a user:
 1433: #   (userauth).
 1434: #
 1435: # Parameters:
 1436: #      $cmd    - the actual keyword that invoked us.
 1437: #      $tail   - the tail of the request that invoked us.
 1438: #      $replyfd- File descriptor connected to the client
 1439: #  Returns:
 1440: #      1       - Ok to continue processing.
 1441: #      0       - Program should exit
 1442: # Implicit outputs:
 1443: #    The user authorization type is written to the client.
 1444: #
 1445: sub user_authorization_type {
 1446:     my ($cmd, $tail, $replyfd) = @_;
 1447:    
 1448:     my $userinput = "$cmd:$tail";
 1449:    
 1450:     #  Pull the domain and username out of the command tail.
 1451:     # and call get_auth_type to determine the authentication type.
 1452:    
 1453:     my ($udom,$uname)=split(/:/,$tail);
 1454:     my $result = &get_auth_type($udom, $uname);
 1455:     if($result eq "nouser") {
 1456: 	&Failure( $replyfd, "unknown_user\n", $userinput);
 1457:     } else {
 1458: 	#
 1459: 	# We only want to pass the second field from get_auth_type
 1460: 	# for ^krb.. otherwise we'll be handing out the encrypted
 1461: 	# password for internals e.g.
 1462: 	#
 1463: 	my ($type,$otherinfo) = split(/:/,$result);
 1464: 	if($type =~ /^krb/) {
 1465: 	    $type = $result;
 1466: 	} else {
 1467:             $type .= ':';
 1468:         }
 1469: 	&Reply( $replyfd, \$type, $userinput);
 1470:     }
 1471:   
 1472:     return 1;
 1473: }
 1474: &register_handler("currentauth", \&user_authorization_type, 1, 1, 0);
 1475: 
 1476: #   Process a request by a manager to push a hosts or domain table 
 1477: #   to us.  We pick apart the command and pass it on to the subs
 1478: #   that already exist to do this.
 1479: #
 1480: # Parameters:
 1481: #      $cmd    - the actual keyword that invoked us.
 1482: #      $tail   - the tail of the request that invoked us.
 1483: #      $client - File descriptor connected to the client
 1484: #  Returns:
 1485: #      1       - Ok to continue processing.
 1486: #      0       - Program should exit
 1487: # Implicit Output:
 1488: #    a reply is written to the client.
 1489: sub push_file_handler {
 1490:     my ($cmd, $tail, $client) = @_;
 1491:     &Debug("In push file handler");
 1492:     my $userinput = "$cmd:$tail";
 1493: 
 1494:     # At this time we only know that the IP of our partner is a valid manager
 1495:     # the code below is a hook to do further authentication (e.g. to resolve
 1496:     # spoofing).
 1497: 
 1498:     my $cert = &GetCertificate($userinput);
 1499:     if(&ValidManager($cert)) {
 1500: 	&Debug("Valid manager: $client");
 1501: 
 1502: 	# Now presumably we have the bona fides of both the peer host and the
 1503: 	# process making the request.
 1504:       
 1505: 	my $reply = &PushFile($userinput);
 1506: 	&Reply($client, \$reply, $userinput);
 1507: 
 1508:     } else {
 1509: 	&logthis("push_file_handler $client is not valid");
 1510: 	&Failure( $client, "refused\n", $userinput);
 1511:     } 
 1512:     return 1;
 1513: }
 1514: &register_handler("pushfile", \&push_file_handler, 1, 0, 1);
 1515: 
 1516: # The du_handler routine should be considered obsolete and is retained
 1517: # for communication with legacy servers.  Please see the du2_handler.
 1518: #
 1519: #   du  - list the disk usage of a directory recursively. 
 1520: #    
 1521: #   note: stolen code from the ls file handler
 1522: #   under construction by Rick Banghart 
 1523: #    .
 1524: # Parameters:
 1525: #    $cmd        - The command that dispatched us (du).
 1526: #    $ududir     - The directory path to list... I'm not sure what this
 1527: #                  is relative as things like ls:. return e.g.
 1528: #                  no_such_dir.
 1529: #    $client     - Socket open on the client.
 1530: # Returns:
 1531: #     1 - indicating that the daemon should not disconnect.
 1532: # Side Effects:
 1533: #   The reply is written to  $client.
 1534: #
 1535: sub du_handler {
 1536:     my ($cmd, $ududir, $client) = @_;
 1537:     ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
 1538:     my $userinput = "$cmd:$ududir";
 1539: 
 1540:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
 1541: 	&Failure($client,"refused\n","$cmd:$ududir");
 1542: 	return 1;
 1543:     }
 1544:     #  Since $ududir could have some nasties in it,
 1545:     #  we will require that ududir is a valid
 1546:     #  directory.  Just in case someone tries to
 1547:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
 1548:     #  etc.
 1549:     #
 1550:     if (-d $ududir) {
 1551: 	my $total_size=0;
 1552: 	my $code=sub { 
 1553: 	    if ($_=~/\.\d+\./) { return;} 
 1554: 	    if ($_=~/\.meta$/) { return;}
 1555: 	    if (-d $_)         { return;}
 1556: 	    $total_size+=(stat($_))[7];
 1557: 	};
 1558: 	chdir($ududir);
 1559: 	find($code,$ududir);
 1560: 	$total_size=int($total_size/1024);
 1561: 	&Reply($client,\$total_size,"$cmd:$ududir");
 1562:     } else {
 1563: 	&Failure($client, "bad_directory:$ududir\n","$cmd:$ududir"); 
 1564:     }
 1565:     return 1;
 1566: }
 1567: &register_handler("du", \&du_handler, 0, 1, 0);
 1568: 
 1569: # Please also see the du_handler, which is obsoleted by du2. 
 1570: # du2_handler differs from du_handler in that required path to directory
 1571: # provided by &propath() is prepended in the handler instead of on the 
 1572: # client side.
 1573: #
 1574: #   du2  - list the disk usage of a directory recursively.
 1575: #
 1576: # Parameters:
 1577: #    $cmd        - The command that dispatched us (du).
 1578: #    $tail       - The tail of the request that invoked us.
 1579: #                  $tail is a : separated list of the following:
 1580: #                   - $ududir - directory path to list (before prepending)
 1581: #                   - $getpropath = 1 if &propath() should prepend
 1582: #                   - $uname - username to use for &propath or user dir
 1583: #                   - $udom - domain to use for &propath or user dir
 1584: #                   All are escaped.
 1585: #    $client     - Socket open on the client.
 1586: # Returns:
 1587: #     1 - indicating that the daemon should not disconnect.
 1588: # Side Effects:
 1589: #   The reply is written to $client.
 1590: #
 1591: 
 1592: sub du2_handler {
 1593:     my ($cmd, $tail, $client) = @_;
 1594:     my ($ududir,$getpropath,$uname,$udom) = map { &unescape($_) } (split(/:/, $tail));
 1595:     my $userinput = "$cmd:$tail";
 1596:     if (($ududir=~/\.\./) || (($ududir!~m|^/home/httpd/|) && (!$getpropath))) {
 1597:         &Failure($client,"refused\n","$cmd:$tail");
 1598:         return 1;
 1599:     }
 1600:     if ($getpropath) {
 1601:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
 1602:             $ududir = &propath($udom,$uname).'/'.$ududir;
 1603:         } else {
 1604:             &Failure($client,"refused\n","$cmd:$tail");
 1605:             return 1;
 1606:         }
 1607:     }
 1608:     #  Since $ududir could have some nasties in it,
 1609:     #  we will require that ududir is a valid
 1610:     #  directory.  Just in case someone tries to
 1611:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
 1612:     #  etc.
 1613:     #
 1614:     if (-d $ududir) {
 1615:         my $total_size=0;
 1616:         my $code=sub {
 1617:             if ($_=~/\.\d+\./) { return;}
 1618:             if ($_=~/\.meta$/) { return;}
 1619:             if (-d $_)         { return;}
 1620:             $total_size+=(stat($_))[7];
 1621:         };
 1622:         chdir($ududir);
 1623:         find($code,$ududir);
 1624:         $total_size=int($total_size/1024);
 1625:         &Reply($client,\$total_size,"$cmd:$ududir");
 1626:     } else {
 1627:         &Failure($client, "bad_directory:$ududir\n","$cmd:$tail");
 1628:     }
 1629:     return 1;
 1630: }
 1631: &register_handler("du2", \&du2_handler, 0, 1, 0);
 1632: 
 1633: #
 1634: # The ls_handler routine should be considered obsolete and is retained
 1635: # for communication with legacy servers.  Please see the ls3_handler.
 1636: #
 1637: #   ls  - list the contents of a directory.  For each file in the
 1638: #    selected directory the filename followed by the full output of
 1639: #    the stat function is returned.  The returned info for each
 1640: #    file are separated by ':'.  The stat fields are separated by &'s.
 1641: #
 1642: #    If the requested path contains /../ or is:
 1643: #
 1644: #    1. for a directory, and the path does not begin with one of:
 1645: #        (a) /home/httpd/html/res/<domain>
 1646: #        (b) /home/httpd/html/userfiles/
 1647: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
 1648: #    or is:
 1649: #
 1650: #    2. for a file, and the path (after prepending) does not begin with one of:
 1651: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
 1652: #        (b) /home/httpd/html/res/<domain>/<username>/
 1653: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
 1654: #
 1655: #    the response will be "refused".
 1656: #
 1657: # Parameters:
 1658: #    $cmd        - The command that dispatched us (ls).
 1659: #    $ulsdir     - The directory path to list... I'm not sure what this
 1660: #                  is relative as things like ls:. return e.g.
 1661: #                  no_such_dir.
 1662: #    $client     - Socket open on the client.
 1663: # Returns:
 1664: #     1 - indicating that the daemon should not disconnect.
 1665: # Side Effects:
 1666: #   The reply is written to  $client.
 1667: #
 1668: sub ls_handler {
 1669:     # obsoleted by ls2_handler
 1670:     my ($cmd, $ulsdir, $client) = @_;
 1671: 
 1672:     my $userinput = "$cmd:$ulsdir";
 1673: 
 1674:     my $obs;
 1675:     my $rights;
 1676:     my $ulsout='';
 1677:     my $ulsfn;
 1678:     if ($ulsdir =~m{/\.\./}) {
 1679:         &Failure($client,"refused\n",$userinput);
 1680:         return 1;
 1681:     }
 1682:     if (-e $ulsdir) {
 1683: 	if(-d $ulsdir) {
 1684:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
 1685:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
 1686:                 &Failure($client,"refused\n",$userinput);
 1687:                 return 1;
 1688:             }
 1689: 	    if (opendir(LSDIR,$ulsdir)) {
 1690: 		while ($ulsfn=readdir(LSDIR)) {
 1691: 		    undef($obs);
 1692: 		    undef($rights); 
 1693: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1694: 		    #We do some obsolete checking here
 1695: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
 1696: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
 1697: 			my @obsolete=<FILE>;
 1698: 			foreach my $obsolete (@obsolete) {
 1699: 			    if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
 1700: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
 1701: 			}
 1702: 		    }
 1703: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
 1704: 		    if($obs eq '1') { $ulsout.="&1"; }
 1705: 		    else { $ulsout.="&0"; }
 1706: 		    if($rights eq '1') { $ulsout.="&1:"; }
 1707: 		    else { $ulsout.="&0:"; }
 1708: 		}
 1709: 		closedir(LSDIR);
 1710: 	    }
 1711: 	} else {
 1712:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
 1713:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
 1714:                 &Failure($client,"refused\n",$userinput);
 1715:                 return 1;
 1716:             }
 1717: 	    my @ulsstats=stat($ulsdir);
 1718: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1719: 	}
 1720:     } else {
 1721: 	$ulsout='no_such_dir';
 1722:     }
 1723:     if ($ulsout eq '') { $ulsout='empty'; }
 1724:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
 1725:     
 1726:     return 1;
 1727: 
 1728: }
 1729: &register_handler("ls", \&ls_handler, 0, 1, 0);
 1730: 
 1731: # The ls2_handler routine should be considered obsolete and is retained
 1732: # for communication with legacy servers.  Please see the ls3_handler.
 1733: # Please also see the ls_handler, which was itself obsoleted by ls2.
 1734: # ls2_handler differs from ls_handler in that it escapes its return 
 1735: # values before concatenating them together with ':'s.
 1736: #
 1737: #   ls2  - list the contents of a directory.  For each file in the
 1738: #    selected directory the filename followed by the full output of
 1739: #    the stat function is returned.  The returned info for each
 1740: #    file are separated by ':'.  The stat fields are separated by &'s.
 1741: #
 1742: #    If the requested path contains /../ or is:
 1743: #
 1744: #    1. for a directory, and the path does not begin with one of:
 1745: #        (a) /home/httpd/html/res/<domain>
 1746: #        (b) /home/httpd/html/userfiles/
 1747: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
 1748: #    or is:
 1749: #
 1750: #    2. for a file, and the path (after prepending) does not begin with one of:
 1751: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
 1752: #        (b) /home/httpd/html/res/<domain>/<username>/
 1753: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
 1754: #
 1755: #    the response will be "refused".
 1756: #
 1757: # Parameters:
 1758: #    $cmd        - The command that dispatched us (ls).
 1759: #    $ulsdir     - The directory path to list... I'm not sure what this
 1760: #                  is relative as things like ls:. return e.g.
 1761: #                  no_such_dir.
 1762: #    $client     - Socket open on the client.
 1763: # Returns:
 1764: #     1 - indicating that the daemon should not disconnect.
 1765: # Side Effects:
 1766: #   The reply is written to  $client.
 1767: #
 1768: sub ls2_handler {
 1769:     my ($cmd, $ulsdir, $client) = @_;
 1770: 
 1771:     my $userinput = "$cmd:$ulsdir";
 1772: 
 1773:     my $obs;
 1774:     my $rights;
 1775:     my $ulsout='';
 1776:     my $ulsfn;
 1777:     if ($ulsdir =~m{/\.\./}) {
 1778:         &Failure($client,"refused\n",$userinput);
 1779:         return 1;
 1780:     }
 1781:     if (-e $ulsdir) {
 1782:         if(-d $ulsdir) {
 1783:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
 1784:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
 1785:                 &Failure($client,"refused\n","$userinput");
 1786:                 return 1;
 1787:             }
 1788:             if (opendir(LSDIR,$ulsdir)) {
 1789:                 while ($ulsfn=readdir(LSDIR)) {
 1790:                     undef($obs);
 1791: 		    undef($rights); 
 1792:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1793:                     #We do some obsolete checking here
 1794:                     if(-e $ulsdir.'/'.$ulsfn.".meta") { 
 1795:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
 1796:                         my @obsolete=<FILE>;
 1797:                         foreach my $obsolete (@obsolete) {
 1798:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
 1799:                             if($obsolete =~ m|(<copyright>)(default)|) {
 1800:                                 $rights = 1;
 1801:                             }
 1802:                         }
 1803:                     }
 1804:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
 1805:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1806:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1807:                     $ulsout.= &escape($tmp).':';
 1808:                 }
 1809:                 closedir(LSDIR);
 1810:             }
 1811:         } else {
 1812:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
 1813:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
 1814:                 &Failure($client,"refused\n",$userinput);
 1815:                 return 1;
 1816:             }
 1817:             my @ulsstats=stat($ulsdir);
 1818:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1819:         }
 1820:     } else {
 1821:         $ulsout='no_such_dir';
 1822:    }
 1823:    if ($ulsout eq '') { $ulsout='empty'; }
 1824:    &Reply($client, \$ulsout, $userinput); # This supports debug logging.
 1825:    return 1;
 1826: }
 1827: &register_handler("ls2", \&ls2_handler, 0, 1, 0);
 1828: #
 1829: #   ls3  - list the contents of a directory.  For each file in the
 1830: #    selected directory the filename followed by the full output of
 1831: #    the stat function is returned.  The returned info for each
 1832: #    file are separated by ':'.  The stat fields are separated by &'s.
 1833: #
 1834: #    If the requested path (after prepending) contains /../ or is:
 1835: #
 1836: #    1. for a directory, and the path does not begin with one of:
 1837: #        (a) /home/httpd/html/res/<domain>
 1838: #        (b) /home/httpd/html/userfiles/
 1839: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
 1840: #        (d) /home/httpd/html/priv/<domain> and client is the homeserver
 1841: #
 1842: #    or is:
 1843: #
 1844: #    2. for a file, and the path (after prepending) does not begin with one of:
 1845: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
 1846: #        (b) /home/httpd/html/res/<domain>/<username>/
 1847: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
 1848: #        (d) /home/httpd/html/priv/<domain>/<username>/ and client is the homeserver
 1849: #
 1850: #    the response will be "refused".
 1851: #
 1852: # Parameters:
 1853: #    $cmd        - The command that dispatched us (ls).
 1854: #    $tail       - The tail of the request that invoked us.
 1855: #                  $tail is a : separated list of the following:
 1856: #                   - $ulsdir - directory path to list (before prepending)
 1857: #                   - $getpropath = 1 if &propath() should prepend
 1858: #                   - $getuserdir = 1 if path to user dir in lonUsers should
 1859: #                                     prepend
 1860: #                   - $alternate_root - path to prepend
 1861: #                   - $uname - username to use for &propath or user dir
 1862: #                   - $udom - domain to use for &propath or user dir
 1863: #            All of these except $getpropath and &getuserdir are escaped.    
 1864: #                  no_such_dir.
 1865: #    $client     - Socket open on the client.
 1866: # Returns:
 1867: #     1 - indicating that the daemon should not disconnect.
 1868: # Side Effects:
 1869: #   The reply is written to $client.
 1870: #
 1871: 
 1872: sub ls3_handler {
 1873:     my ($cmd, $tail, $client) = @_;
 1874:     my $userinput = "$cmd:$tail";
 1875:     my ($ulsdir,$getpropath,$getuserdir,$alternate_root,$uname,$udom) =
 1876:         split(/:/,$tail);
 1877:     if (defined($ulsdir)) {
 1878:         $ulsdir = &unescape($ulsdir);
 1879:     }
 1880:     if (defined($alternate_root)) {
 1881:         $alternate_root = &unescape($alternate_root);
 1882:     }
 1883:     if (defined($uname)) {
 1884:         $uname = &unescape($uname);
 1885:     }
 1886:     if (defined($udom)) {
 1887:         $udom = &unescape($udom);
 1888:     }
 1889: 
 1890:     my $dir_root = $perlvar{'lonDocRoot'};
 1891:     if (($getpropath) || ($getuserdir)) {
 1892:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
 1893:             $dir_root = &propath($udom,$uname);
 1894:             $dir_root =~ s/\/$//;
 1895:         } else {
 1896:             &Failure($client,"refused\n",$userinput);
 1897:             return 1;
 1898:         }
 1899:     } elsif ($alternate_root ne '') {
 1900:         $dir_root = $alternate_root;
 1901:     }
 1902:     if (($dir_root ne '') && ($dir_root ne '/')) {
 1903:         if ($ulsdir =~ /^\//) {
 1904:             $ulsdir = $dir_root.$ulsdir;
 1905:         } else {
 1906:             $ulsdir = $dir_root.'/'.$ulsdir;
 1907:         }
 1908:     }
 1909:     if ($ulsdir =~m{/\.\./}) {
 1910:         &Failure($client,"refused\n",$userinput);
 1911:         return 1;
 1912:     }
 1913:     my $islocal;
 1914:     my @machine_ids = &Apache::lonnet::current_machine_ids();
 1915:     if (grep(/^\Q$clientname\E$/,@machine_ids)) {
 1916:         $islocal = 1;
 1917:     }
 1918:     my $obs;
 1919:     my $rights;
 1920:     my $ulsout='';
 1921:     my $ulsfn;
 1922: 
 1923:     my ($crscheck,$toplevel,$currdom,$currnum,$skip);
 1924:     unless ($islocal) {
 1925:         my ($major,$minor) = split(/\./,$clientversion);
 1926:         if (($major < 2) || ($major == 2 && $minor < 12)) {
 1927:             $crscheck = 1;
 1928:         }
 1929:     }
 1930:     if (-e $ulsdir) {
 1931:         if(-d $ulsdir) {
 1932:             unless (($getpropath) || ($getuserdir) ||
 1933:                     ($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
 1934:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles}) ||
 1935:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain}) && ($islocal))) {
 1936:                 &Failure($client,"refused\n",$userinput);
 1937:                 return 1;
 1938:             }
 1939:             if (($crscheck) &&
 1940:                 ($ulsdir =~ m{^/home/httpd/html/res/($LONCAPA::match_domain)(/?$|/$LONCAPA::match_courseid)})) {
 1941:                 ($currdom,my $posscnum) = ($1,$2);
 1942:                 if (($posscnum eq '') || ($posscnum eq '/')) {
 1943:                     $toplevel = 1;
 1944:                 } else {
 1945:                     $posscnum =~ s{^/+}{};
 1946:                     if (&LONCAPA::Lond::is_course($currdom,$posscnum)) {
 1947:                         $skip = 1;
 1948:                     }
 1949:                 }
 1950:             }
 1951:             if ((!$skip) && (opendir(LSDIR,$ulsdir))) {
 1952:                 while ($ulsfn=readdir(LSDIR)) {
 1953:                     if (($crscheck) && ($toplevel) && ($currdom ne '') &&
 1954:                         ($ulsfn =~ /^$LONCAPA::match_courseid$/) && (-d "$ulsdir/$ulsfn")) {
 1955:                         if (&LONCAPA::Lond::is_course($currdom,$ulsfn)) {
 1956:                             next;
 1957:                         }
 1958:                     }
 1959:                     undef($obs);
 1960:                     undef($rights);
 1961:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1962:                     #We do some obsolete checking here
 1963:                     if(-e $ulsdir.'/'.$ulsfn.".meta") {
 1964:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
 1965:                         my @obsolete=<FILE>;
 1966:                         foreach my $obsolete (@obsolete) {
 1967:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
 1968:                             if($obsolete =~ m|(<copyright>)(default)|) {
 1969:                                 $rights = 1;
 1970:                             }
 1971:                         }
 1972:                     }
 1973:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
 1974:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1975:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1976:                     $ulsout.= &escape($tmp).':';
 1977:                 }
 1978:                 closedir(LSDIR);
 1979:             }
 1980:         } else {
 1981:             unless (($getpropath) || ($getuserdir) ||
 1982:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
 1983:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/}) ||
 1984:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain/$LONCAPA::match_name/}) && ($islocal))) {
 1985:                 &Failure($client,"refused\n",$userinput);
 1986:                 return 1;
 1987:             }
 1988:             my @ulsstats=stat($ulsdir);
 1989:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1990:         }
 1991:     } else {
 1992:         $ulsout='no_such_dir';
 1993:     }
 1994:     if ($ulsout eq '') { $ulsout='empty'; }
 1995:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
 1996:     return 1;
 1997: }
 1998: &register_handler("ls3", \&ls3_handler, 0, 1, 0);
 1999: 
 2000: sub read_lonnet_global {
 2001:     my ($cmd,$tail,$client) = @_;
 2002:     my $userinput = "$cmd:$tail";
 2003:     my $requested = &Apache::lonnet::thaw_unescape($tail);
 2004:     my $result;
 2005:     my %packagevars = (
 2006:                         spareid => \%Apache::lonnet::spareid,
 2007:                         perlvar => \%Apache::lonnet::perlvar,
 2008:                       );
 2009:     my %limit_to = (
 2010:                     perlvar => {
 2011:                                  lonOtherAuthen  => 1,
 2012:                                  lonBalancer     => 1,
 2013:                                  lonVersion      => 1,
 2014:                                  lonAdmEMail     => 1,
 2015:                                  lonSupportEMail => 1,  
 2016:                                  lonSysEMail     => 1,
 2017:                                  lonHostID       => 1,
 2018:                                  lonRole         => 1,
 2019:                                  lonDefDomain    => 1,
 2020:                                  lonLoadLim      => 1,
 2021:                                  lonUserLoadLim  => 1,
 2022:                                }
 2023:                   );
 2024:     if (ref($requested) eq 'HASH') {
 2025:         foreach my $what (keys(%{$requested})) {
 2026:             my $response;
 2027:             my $items = {};
 2028:             if (exists($packagevars{$what})) {
 2029:                 if (ref($limit_to{$what}) eq 'HASH') {
 2030:                     foreach my $varname (keys(%{$packagevars{$what}})) {
 2031:                         if ($limit_to{$what}{$varname}) {
 2032:                             $items->{$varname} = $packagevars{$what}{$varname};
 2033:                         }
 2034:                     }
 2035:                 } else {
 2036:                     $items = $packagevars{$what};
 2037:                 }
 2038:                 if ($what eq 'perlvar') {
 2039:                     if (!exists($packagevars{$what}{'lonBalancer'})) {
 2040:                         if ($dist =~ /^(centos|rhes|fedora|scientific|oracle|rocky|alma)/) {
 2041:                             my $othervarref=LONCAPA::Configuration::read_conf('httpd.conf');
 2042:                             if (ref($othervarref) eq 'HASH') {
 2043:                                 $items->{'lonBalancer'} = $othervarref->{'lonBalancer'};
 2044:                             }
 2045:                         }
 2046:                     }
 2047:                 }
 2048:                 $response = &Apache::lonnet::freeze_escape($items);
 2049:             }
 2050:             $result .= &escape($what).'='.$response.'&';
 2051:         }
 2052:     }
 2053:     $result =~ s/\&$//;
 2054:     &Reply($client,\$result,$userinput);
 2055:     return 1;
 2056: }
 2057: &register_handler("readlonnetglobal", \&read_lonnet_global, 0, 1, 0);
 2058: 
 2059: sub server_devalidatecache_handler {
 2060:     my ($cmd,$tail,$client) = @_;
 2061:     my $userinput = "$cmd:$tail";
 2062:     my $items = &unescape($tail);
 2063:     my @cached = split(/\&/,$items);
 2064:     foreach my $key (@cached) {
 2065:         if ($key =~ /:/) {
 2066:             my ($name,$id) = map { &unescape($_); } split(/:/,$key);
 2067:             &Apache::lonnet::devalidate_cache_new($name,$id);
 2068:         }
 2069:     }
 2070:     my $result = 'ok';
 2071:     &Reply($client,\$result,$userinput);
 2072:     return 1;
 2073: }
 2074: &register_handler("devalidatecache", \&server_devalidatecache_handler, 0, 1, 0);
 2075: 
 2076: sub server_timezone_handler {
 2077:     my ($cmd,$tail,$client) = @_;
 2078:     my $userinput = "$cmd:$tail";
 2079:     my $timezone;
 2080:     my $clockfile = '/etc/sysconfig/clock'; # Fedora/CentOS/SuSE
 2081:     my $tzfile = '/etc/timezone'; # Debian/Ubuntu
 2082:     if (-e $clockfile) {
 2083:         if (open(my $fh,"<$clockfile")) {
 2084:             while (<$fh>) {
 2085:                 next if (/^[\#\s]/);
 2086:                 if (/^(?:TIME)?ZONE\s*=\s*['"]?\s*([\w\/]+)/) {
 2087:                     $timezone = $1;
 2088:                     last;
 2089:                 }
 2090:             }
 2091:             close($fh);
 2092:         }
 2093:     } elsif (-e $tzfile) {
 2094:         if (open(my $fh,"<$tzfile")) {
 2095:             $timezone = <$fh>;
 2096:             close($fh);
 2097:             chomp($timezone);
 2098:             if ($timezone =~ m{^Etc/(\w+)$}) {
 2099:                 $timezone = $1;
 2100:             }
 2101:         }
 2102:     }
 2103:     &Reply($client,\$timezone,$userinput); # This supports debug logging.
 2104:     return 1;
 2105: }
 2106: &register_handler("servertimezone", \&server_timezone_handler, 0, 1, 0);
 2107: 
 2108: sub server_loncaparev_handler {
 2109:     my ($cmd,$tail,$client) = @_;
 2110:     my $userinput = "$cmd:$tail";
 2111:     &Reply($client,\$perlvar{'lonVersion'},$userinput);
 2112:     return 1;
 2113: }
 2114: &register_handler("serverloncaparev", \&server_loncaparev_handler, 0, 1, 0);
 2115: 
 2116: sub server_homeID_handler {
 2117:     my ($cmd,$tail,$client) = @_;
 2118:     my $userinput = "$cmd:$tail";
 2119:     &Reply($client,\$perlvar{'lonHostID'},$userinput);
 2120:     return 1;
 2121: }
 2122: &register_handler("serverhomeID", \&server_homeID_handler, 0, 1, 0);
 2123: 
 2124: sub server_distarch_handler {
 2125:     my ($cmd,$tail,$client) = @_;
 2126:     my $userinput = "$cmd:$tail";
 2127:     my $reply = &distro_and_arch();
 2128:     &Reply($client,\$reply,$userinput);
 2129:     return 1;
 2130: }
 2131: &register_handler("serverdistarch", \&server_distarch_handler, 0, 1, 0);
 2132: 
 2133: sub server_certs_handler {
 2134:     my ($cmd,$tail,$client) = @_;
 2135:     my $userinput = "$cmd:$tail";
 2136:     my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
 2137:     my $result = &LONCAPA::Lond::server_certs(\%perlvar,$perlvar{'lonHostID'},$hostname);
 2138:     &Reply($client,\$result,$userinput);
 2139:     return;
 2140: }
 2141: &register_handler("servercerts", \&server_certs_handler, 0, 1, 0);
 2142: 
 2143: #   Process a reinit request.  Reinit requests that either
 2144: #   lonc or lond be reinitialized so that an updated 
 2145: #   host.tab or domain.tab can be processed.
 2146: #
 2147: # Parameters:
 2148: #      $cmd    - the actual keyword that invoked us.
 2149: #      $tail   - the tail of the request that invoked us.
 2150: #      $client - File descriptor connected to the client
 2151: #  Returns:
 2152: #      1       - Ok to continue processing.
 2153: #      0       - Program should exit
 2154: #  Implicit output:
 2155: #     a reply is sent to the client.
 2156: #
 2157: sub reinit_process_handler {
 2158:     my ($cmd, $tail, $client) = @_;
 2159:    
 2160:     my $userinput = "$cmd:$tail";
 2161:    
 2162:     my $cert = &GetCertificate($userinput);
 2163:     if(&ValidManager($cert)) {
 2164: 	chomp($userinput);
 2165: 	my $reply = &ReinitProcess($userinput);
 2166: 	&Reply( $client,  \$reply, $userinput);
 2167:     } else {
 2168: 	&Failure( $client, "refused\n", $userinput);
 2169:     }
 2170:     return 1;
 2171: }
 2172: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
 2173: 
 2174: #  Process the editing script for a table edit operation.
 2175: #  the editing operation must be encrypted and requested by
 2176: #  a manager host.
 2177: #
 2178: # Parameters:
 2179: #      $cmd    - the actual keyword that invoked us.
 2180: #      $tail   - the tail of the request that invoked us.
 2181: #      $client - File descriptor connected to the client
 2182: #  Returns:
 2183: #      1       - Ok to continue processing.
 2184: #      0       - Program should exit
 2185: #  Implicit output:
 2186: #     a reply is sent to the client.
 2187: #
 2188: sub edit_table_handler {
 2189:     my ($command, $tail, $client) = @_;
 2190:    
 2191:     my $userinput = "$command:$tail";
 2192: 
 2193:     my $cert = &GetCertificate($userinput);
 2194:     if(&ValidManager($cert)) {
 2195: 	my($filetype, $script) = split(/:/, $tail);
 2196: 	if (($filetype eq "hosts") || 
 2197: 	    ($filetype eq "domain")) {
 2198: 	    if($script ne "") {
 2199: 		&Reply($client,              # BUGBUG - EditFile
 2200: 		      &EditFile($userinput), #   could fail.
 2201: 		      $userinput);
 2202: 	    } else {
 2203: 		&Failure($client,"refused\n",$userinput);
 2204: 	    }
 2205: 	} else {
 2206: 	    &Failure($client,"refused\n",$userinput);
 2207: 	}
 2208:     } else {
 2209: 	&Failure($client,"refused\n",$userinput);
 2210:     }
 2211:     return 1;
 2212: }
 2213: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
 2214: 
 2215: #
 2216: #   Authenticate a user against the LonCAPA authentication
 2217: #   database.  Note that there are several authentication
 2218: #   possibilities:
 2219: #   - unix     - The user can be authenticated against the unix
 2220: #                password file.
 2221: #   - internal - The user can be authenticated against a purely 
 2222: #                internal per user password file.
 2223: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
 2224: #                ticket granting authority.
 2225: #   - user     - The person tailoring LonCAPA can supply a user authentication
 2226: #                mechanism that is per system.
 2227: #
 2228: # Parameters:
 2229: #    $cmd      - The command that got us here.
 2230: #    $tail     - Tail of the command (remaining parameters).
 2231: #    $client   - File descriptor connected to client.
 2232: # Returns
 2233: #     0        - Requested to exit, caller should shut down.
 2234: #     1        - Continue processing.
 2235: # Implicit inputs:
 2236: #    The authentication systems describe above have their own forms of implicit
 2237: #    input into the authentication process that are described above.
 2238: #
 2239: sub authenticate_handler {
 2240:     my ($cmd, $tail, $client) = @_;
 2241: 
 2242:     
 2243:     #  Regenerate the full input line 
 2244:     
 2245:     my $userinput  = $cmd.":".$tail;
 2246:     
 2247:     #  udom    - User's domain.
 2248:     #  uname   - Username.
 2249:     #  upass   - User's password.
 2250:     #  checkdefauth - Pass to validate_user() to try authentication
 2251:     #                 with default auth type(s) if no user account.
 2252:     #  clientcancheckhost - Passed by clients with functionality in lonauth.pm
 2253:     #                       to check if session can be hosted.
 2254:     
 2255:     my ($udom, $uname, $upass, $checkdefauth, $clientcancheckhost)=split(/:/,$tail);
 2256:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass,  checkdefauth = $checkdefauth");
 2257:     chomp($upass);
 2258:     $upass=&unescape($upass);
 2259: 
 2260:     my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
 2261:     if($pwdcorrect) {
 2262:         my $canhost = 1;
 2263:         unless ($clientcancheckhost) {
 2264:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 2265:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 2266:             my @intdoms;
 2267:             my $internet_names = &Apache::lonnet::get_internet_names($clientname);
 2268:             if (ref($internet_names) eq 'ARRAY') {
 2269:                 @intdoms = @{$internet_names};
 2270:             }
 2271:             unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
 2272:                 my ($remote,$hosted);
 2273:                 my $remotesession = &get_usersession_config($udom,'remotesession');
 2274:                 if (ref($remotesession) eq 'HASH') {
 2275:                     $remote = $remotesession->{'remote'};
 2276:                 }
 2277:                 my $hostedsession = &get_usersession_config($clienthomedom,'hostedsession');
 2278:                 if (ref($hostedsession) eq 'HASH') {
 2279:                     $hosted = $hostedsession->{'hosted'};
 2280:                 }
 2281:                 $canhost = &Apache::lonnet::can_host_session($udom,$clientname,
 2282:                                                              $clientversion,
 2283:                                                              $remote,$hosted);
 2284:             }
 2285:         }
 2286:         if ($canhost) {               
 2287:             &Reply( $client, "authorized\n", $userinput);
 2288:         } else {
 2289:             &Reply( $client, "not_allowed_to_host\n", $userinput);
 2290:         }
 2291: 	#
 2292: 	#  Bad credentials: Failed to authorize
 2293: 	#
 2294:     } else {
 2295: 	&Failure( $client, "non_authorized\n", $userinput);
 2296:     }
 2297: 
 2298:     return 1;
 2299: }
 2300: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
 2301: 
 2302: #
 2303: #   Change a user's password.  Note that this function is complicated by
 2304: #   the fact that a user may be authenticated in more than one way:
 2305: #   At present, we are not able to change the password for all types of
 2306: #   authentication methods.  Only for:
 2307: #      unix    - unix password or shadow passoword style authentication.
 2308: #      local   - Locally written authentication mechanism.
 2309: #   For now, kerb4 and kerb5 password changes are not supported and result
 2310: #   in an error.
 2311: # FUTURE WORK:
 2312: #    Support kerberos passwd changes?
 2313: # Parameters:
 2314: #    $cmd      - The command that got us here.
 2315: #    $tail     - Tail of the command (remaining parameters).
 2316: #    $client   - File descriptor connected to client.
 2317: # Returns
 2318: #     0        - Requested to exit, caller should shut down.
 2319: #     1        - Continue processing.
 2320: # Implicit inputs:
 2321: #    The authentication systems describe above have their own forms of implicit
 2322: #    input into the authentication process that are described above.
 2323: sub change_password_handler {
 2324:     my ($cmd, $tail, $client) = @_;
 2325: 
 2326:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
 2327: 
 2328:     #
 2329:     #  udom  - user's domain.
 2330:     #  uname - Username.
 2331:     #  upass - Current password.
 2332:     #  npass - New password.
 2333:     #  context - Context in which this was called 
 2334:     #            (preferences or reset_by_email).
 2335:     #  lonhost - HostID of server where request originated 
 2336:    
 2337:     my ($udom,$uname,$upass,$npass,$context,$lonhost)=split(/:/,$tail);
 2338: 
 2339:     $upass=&unescape($upass);
 2340:     $npass=&unescape($npass);
 2341:     &Debug("Trying to change password for $uname");
 2342: 
 2343:     # First require that the user can be authenticated with their
 2344:     # old password unless context was 'reset_by_email':
 2345:     
 2346:     my ($validated,$failure);
 2347:     if ($context eq 'reset_by_email') {
 2348:         if ($lonhost eq '') {
 2349:             $failure = 'invalid_client';
 2350:         } else {
 2351:             $validated = 1;
 2352:         }
 2353:     } else {
 2354:         $validated = &validate_user($udom, $uname, $upass);
 2355:     }
 2356:     if($validated) {
 2357: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
 2358: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
 2359:         my $notunique;
 2360: 	if ($howpwd eq 'internal') {
 2361: 	    &Debug("internal auth");
 2362:             my $ncpass = &hash_passwd($udom,$npass);
 2363:             my (undef,$method,@rest) = split(/!/,$contentpwd);
 2364:             if ($method eq 'bcrypt') {
 2365:                 my %passwdconf = &Apache::lonnet::get_passwdconf($udom);
 2366:                 if (($passwdconf{'numsaved'}) && ($passwdconf{'numsaved'} =~ /^\d+$/)) {
 2367:                     my @oldpasswds;
 2368:                     my $userpath = &propath($udom,$uname);
 2369:                     my $fullpath = $userpath.'/oldpasswds';
 2370:                     if (-d $userpath) {
 2371:                         my @oldfiles;
 2372:                         if (-e $fullpath) {
 2373:                             if (opendir(my $dir,$fullpath)) {
 2374:                                 (@oldfiles) = grep(/^\d+$/,readdir($dir));
 2375:                                 closedir($dir);
 2376:                             }
 2377:                             if (@oldfiles) {
 2378:                                 @oldfiles = sort { $b <=> $a } (@oldfiles);
 2379:                                 my $numremoved = 0;
 2380:                                 for (my $i=0; $i<@oldfiles; $i++) {
 2381:                                     if ($i>=$passwdconf{'numsaved'}) {
 2382:                                         if (-f "$fullpath/$oldfiles[$i]") {
 2383:                                             if (unlink("$fullpath/$oldfiles[$i]")) {
 2384:                                                 $numremoved ++;
 2385:                                             }
 2386:                                         }
 2387:                                     } elsif (open(my $fh,'<',"$fullpath/$oldfiles[$i]")) {
 2388:                                         while (my $line = <$fh>) {
 2389:                                             push(@oldpasswds,$line);
 2390:                                         }
 2391:                                         close($fh);
 2392:                                     }
 2393:                                 }
 2394:                                 if ($numremoved) {
 2395:                                     &logthis("unlinked $numremoved old password files for $uname:$udom");
 2396:                                 }
 2397:                             }
 2398:                         }
 2399:                         push(@oldpasswds,$contentpwd);
 2400:                         foreach my $item (@oldpasswds) {
 2401:                             my (undef,$method,@rest) = split(/!/,$item);
 2402:                             if ($method eq 'bcrypt') {
 2403:                                 my $result = &hash_passwd($udom,$npass,@rest);
 2404:                                 if ($result eq $item) {
 2405:                                     $notunique = 1;
 2406:                                     last;
 2407:                                 }
 2408:                             }
 2409:                         }
 2410:                         unless ($notunique) {
 2411:                             unless (-e $fullpath) {
 2412:                                 if (&mkpath("$fullpath/")) {
 2413:                                     chmod(0700,$fullpath);
 2414:                                 }
 2415:                             }
 2416:                             if (-d $fullpath) {
 2417:                                 my $now = time;
 2418:                                 if (open(my $fh,'>',"$fullpath/$now")) {
 2419:                                     print $fh $contentpwd;
 2420:                                     close($fh);
 2421:                                     chmod(0400,"$fullpath/$now");
 2422:                                 }
 2423:                             }
 2424:                         }
 2425:                     }
 2426:                 }
 2427:             }
 2428:             if ($notunique) {
 2429:                 my $msg="Result of password change for $uname:$udom - password matches one used before";
 2430:                 if ($lonhost) {
 2431:                     $msg .= " - request originated from: $lonhost";
 2432:                 }
 2433:                 &logthis($msg);
 2434:                 &Reply($client, "prioruse\n", $userinput);
 2435: 	    } elsif (&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
 2436: 		my $msg="Result of password change for $uname: pwchange_success";
 2437:                 if ($lonhost) {
 2438:                     $msg .= " - request originated from: $lonhost";
 2439:                 }
 2440:                 &logthis($msg);
 2441:                 &update_passwd_history($uname,$udom,$howpwd,$context);
 2442: 		&Reply($client, "ok\n", $userinput);
 2443: 	    } else {
 2444: 		&logthis("Unable to open $uname passwd "               
 2445: 			 ."to change password");
 2446: 		&Failure( $client, "non_authorized\n",$userinput);
 2447: 	    }
 2448: 	} elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
 2449: 	    my $result = &change_unix_password($uname, $npass);
 2450:             if ($result eq 'ok') {
 2451:                 &update_passwd_history($uname,$udom,$howpwd,$context);
 2452:             }
 2453: 	    &logthis("Result of password change for $uname: ".
 2454: 		     $result);
 2455: 	    &Reply($client, \$result, $userinput);
 2456: 	} else {
 2457: 	    # this just means that the current password mode is not
 2458: 	    # one we know how to change (e.g the kerberos auth modes or
 2459: 	    # locally written auth handler).
 2460: 	    #
 2461: 	    &Failure( $client, "auth_mode_error\n", $userinput);
 2462: 	}  
 2463:     } else {
 2464: 	if ($failure eq '') {
 2465: 	    $failure = 'non_authorized';
 2466: 	}
 2467: 	&Failure( $client, "$failure\n", $userinput);
 2468:     }
 2469: 
 2470:     return 1;
 2471: }
 2472: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
 2473: 
 2474: sub hash_passwd {
 2475:     my ($domain,$plainpass,@rest) = @_;
 2476:     my ($salt,$cost);
 2477:     if (@rest) {
 2478:         $cost = $rest[0];
 2479:         # salt is first 22 characters, base-64 encoded by bcrypt
 2480:         my $plainsalt = substr($rest[1],0,22);
 2481:         $salt = Crypt::Eksblowfish::Bcrypt::de_base64($plainsalt);
 2482:     } else {
 2483:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2484:         my $defaultcost = $domdefaults{'intauth_cost'};
 2485:         if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
 2486:             $cost = 10;
 2487:         } else {
 2488:             $cost = $defaultcost;
 2489:         }
 2490:         # Generate random 16-octet base64 salt
 2491:         $salt = "";
 2492:         $salt .= pack("C", int rand(256)) for 1..16;
 2493:     }
 2494:     my $hash = &Crypt::Eksblowfish::Bcrypt::bcrypt_hash({
 2495:         key_nul => 1,
 2496:         cost    => $cost,
 2497:         salt    => $salt,
 2498:     }, Digest::SHA::sha512(Encode::encode('UTF-8',$plainpass)));
 2499: 
 2500:     my $result = join("!", "", "bcrypt", sprintf("%02d",$cost),
 2501:                 &Crypt::Eksblowfish::Bcrypt::en_base64($salt).
 2502:                 &Crypt::Eksblowfish::Bcrypt::en_base64($hash));
 2503:     return $result;
 2504: }
 2505: 
 2506: #
 2507: #   Create a new user.  User in this case means a lon-capa user.
 2508: #   The user must either already exist in some authentication realm
 2509: #   like kerberos or the /etc/passwd.  If not, a user completely local to
 2510: #   this loncapa system is created.
 2511: #
 2512: # Parameters:
 2513: #    $cmd      - The command that got us here.
 2514: #    $tail     - Tail of the command (remaining parameters).
 2515: #    $client   - File descriptor connected to client.
 2516: # Returns
 2517: #     0        - Requested to exit, caller should shut down.
 2518: #     1        - Continue processing.
 2519: # Implicit inputs:
 2520: #    The authentication systems describe above have their own forms of implicit
 2521: #    input into the authentication process that are described above.
 2522: sub add_user_handler {
 2523: 
 2524:     my ($cmd, $tail, $client) = @_;
 2525: 
 2526: 
 2527:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
 2528:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
 2529: 
 2530:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
 2531: 
 2532: 
 2533:     if($udom eq $currentdomainid) { # Reject new users for other domains...
 2534: 	
 2535: 	my $oldumask=umask(0077);
 2536: 	chomp($npass);
 2537: 	$npass=&unescape($npass);
 2538: 	my $passfilename  = &password_path($udom, $uname);
 2539: 	&Debug("Password file created will be:".$passfilename);
 2540: 	if (-e $passfilename) {
 2541: 	    &Failure( $client, "already_exists\n", $userinput);
 2542: 	} else {
 2543: 	    my $fperror='';
 2544: 	    if (!&mkpath($passfilename)) {
 2545: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
 2546: 		    ."makeuser";
 2547: 	    }
 2548: 	    unless ($fperror) {
 2549: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
 2550:                                              $passfilename,'makeuser');
 2551: 		&Reply($client,\$result, $userinput);     #BUGBUG - could be fail
 2552: 	    } else {
 2553: 		&Failure($client, \$fperror, $userinput);
 2554: 	    }
 2555: 	}
 2556: 	umask($oldumask);
 2557:     }  else {
 2558: 	&Failure($client, "not_right_domain\n",
 2559: 		$userinput);	# Even if we are multihomed.
 2560:     
 2561:     }
 2562:     return 1;
 2563: 
 2564: }
 2565: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
 2566: 
 2567: #
 2568: #   Change the authentication method of a user.  Note that this may
 2569: #   also implicitly change the user's password if, for example, the user is
 2570: #   joining an existing authentication realm.  Known authentication realms at
 2571: #   this time are:
 2572: #    internal   - Purely internal password file (only loncapa knows this user)
 2573: #    local      - Institutionally written authentication module.
 2574: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
 2575: #    kerb4      - kerberos version 4
 2576: #    kerb5      - kerberos version 5
 2577: #
 2578: # Parameters:
 2579: #    $cmd      - The command that got us here.
 2580: #    $tail     - Tail of the command (remaining parameters).
 2581: #    $client   - File descriptor connected to client.
 2582: # Returns
 2583: #     0        - Requested to exit, caller should shut down.
 2584: #     1        - Continue processing.
 2585: # Implicit inputs:
 2586: #    The authentication systems describe above have their own forms of implicit
 2587: #    input into the authentication process that are described above.
 2588: # NOTE:
 2589: #   This is also used to change the authentication credential values (e.g. passwd).
 2590: #   
 2591: #
 2592: sub change_authentication_handler {
 2593: 
 2594:     my ($cmd, $tail, $client) = @_;
 2595:    
 2596:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
 2597: 
 2598:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
 2599:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
 2600:     if ($udom ne $currentdomainid) {
 2601: 	&Failure( $client, "not_right_domain\n", $client);
 2602:     } else {
 2603: 	
 2604: 	chomp($npass);
 2605: 	
 2606: 	$npass=&unescape($npass);
 2607: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
 2608: 	my $passfilename = &password_path($udom, $uname);
 2609: 	if ($passfilename) {	# Not allowed to create a new user!!
 2610: 	    # If just changing the unix passwd. need to arrange to run
 2611: 	    # passwd since otherwise make_passwd_file will fail as 
 2612: 	    # creation of unix authenticated users is no longer supported
 2613:             # except from the command line, when running make_domain_coordinator.pl
 2614: 
 2615: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
 2616: 		my $result = &change_unix_password($uname, $npass);
 2617: 		&logthis("Result of password change for $uname: ".$result);
 2618: 		if ($result eq "ok") {
 2619:                     &update_passwd_history($uname,$udom,$umode,'changeuserauth'); 
 2620: 		    &Reply($client, \$result);
 2621: 		} else {
 2622: 		    &Failure($client, \$result);
 2623: 		}
 2624: 	    } else {
 2625: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
 2626:                                              $passfilename,'changeuserauth');
 2627: 		#
 2628: 		#  If the current auth mode is internal, and the old auth mode was
 2629: 		#  unix, or krb*,  and the user is an author for this domain,
 2630: 		#  re-run manage_permissions for that role in order to be able
 2631: 		#  to take ownership of the construction space back to www:www
 2632: 		#
 2633: 
 2634: 
 2635: 		&Reply($client, \$result, $userinput);
 2636: 	    }
 2637: 	       
 2638: 
 2639: 	} else {	       
 2640: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
 2641: 	}
 2642:     }
 2643:     return 1;
 2644: }
 2645: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
 2646: 
 2647: sub update_passwd_history {
 2648:     my ($uname,$udom,$umode,$context) = @_;
 2649:     my $proname=&propath($udom,$uname);
 2650:     my $now = time;
 2651:     if (open(my $fh,">>$proname/passwd.log")) {
 2652:         print $fh "$now:$umode:$context\n";
 2653:         close($fh);
 2654:     }
 2655:     return;
 2656: }
 2657: 
 2658: #
 2659: #   Determines if this is the home server for a user.  The home server
 2660: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
 2661: #   to do is determine if this file exists.
 2662: #
 2663: # Parameters:
 2664: #    $cmd      - The command that got us here.
 2665: #    $tail     - Tail of the command (remaining parameters).
 2666: #    $client   - File descriptor connected to client.
 2667: # Returns
 2668: #     0        - Requested to exit, caller should shut down.
 2669: #     1        - Continue processing.
 2670: # Implicit inputs:
 2671: #    The authentication systems describe above have their own forms of implicit
 2672: #    input into the authentication process that are described above.
 2673: #
 2674: sub is_home_handler {
 2675:     my ($cmd, $tail, $client) = @_;
 2676:    
 2677:     my $userinput  = "$cmd:$tail";
 2678:    
 2679:     my ($udom,$uname)=split(/:/,$tail);
 2680:     chomp($uname);
 2681:     my $passfile = &password_filename($udom, $uname);
 2682:     if($passfile) {
 2683: 	&Reply( $client, "found\n", $userinput);
 2684:     } else {
 2685: 	&Failure($client, "not_found\n", $userinput);
 2686:     }
 2687:     return 1;
 2688: }
 2689: &register_handler("home", \&is_home_handler, 0,1,0);
 2690: 
 2691: #
 2692: #   Process an update request for a resource.
 2693: #   A resource has been modified that we hold a subscription to.
 2694: #   If the resource is not local, then we must update, or at least invalidate our
 2695: #   cached copy of the resource. 
 2696: # Parameters:
 2697: #    $cmd      - The command that got us here.
 2698: #    $tail     - Tail of the command (remaining parameters).
 2699: #    $client   - File descriptor connected to client.
 2700: # Returns
 2701: #     0        - Requested to exit, caller should shut down.
 2702: #     1        - Continue processing.
 2703: # Implicit inputs:
 2704: #    The authentication systems describe above have their own forms of implicit
 2705: #    input into the authentication process that are described above.
 2706: #
 2707: sub update_resource_handler {
 2708: 
 2709:     my ($cmd, $tail, $client) = @_;
 2710:    
 2711:     my $userinput = "$cmd:$tail";
 2712:    
 2713:     my $fname= $tail;		# This allows interactive testing
 2714: 
 2715: 
 2716:     my $ownership=ishome($fname);
 2717:     if ($ownership eq 'not_owner') {
 2718: 	if (-e $fname) {
 2719:             # Delete preview file, if exists
 2720:             unlink("$fname.tmp");
 2721:             # Get usage stats
 2722: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
 2723: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
 2724: 	    my $now=time;
 2725: 	    my $since=$now-$atime;
 2726:             # If the file has not been used within lonExpire seconds,
 2727:             # unsubscribe from it and delete local copy
 2728: 	    if ($since>$perlvar{'lonExpire'}) {
 2729: 		my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
 2730: 		&devalidate_meta_cache($fname);
 2731: 		unlink("$fname");
 2732: 		unlink("$fname.meta");
 2733: 	    } else {
 2734:             # Yes, this is in active use. Get a fresh copy. Since it might be in
 2735:             # very active use and huge (like a movie), copy it to "in.transfer" filename first.
 2736: 		my $transname="$fname.in.transfer";
 2737: 		my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
 2738: 		my $response;
 2739: # FIXME: cannot replicate files that take more than two minutes to transfer -- needs checking now 1200s timeout used
 2740: # for LWP request.
 2741: 		my $request=new HTTP::Request('GET',"$remoteurl");
 2742:                 $response=&LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,0,1);
 2743: 		if ($response->is_error()) {
 2744:                     my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
 2745:                     &devalidate_meta_cache($fname);
 2746:                     if (-e $transname) {
 2747:                         unlink($transname);
 2748:                     }
 2749:                     unlink($fname);
 2750: 		    my $message=$response->status_line;
 2751: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
 2752: 		} else {
 2753: 		    if ($remoteurl!~/\.meta$/) {
 2754: 			my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2755:                         my $mresponse = &LONCAPA::LWPReq::makerequest($clientname,$mrequest,$fname.'.meta',\%perlvar,120,0,1);
 2756: 			if ($mresponse->is_error()) {
 2757: 			    unlink($fname.'.meta');
 2758: 			}
 2759: 		    }
 2760:                     # we successfully transfered, copy file over to real name
 2761: 		    rename($transname,$fname);
 2762: 		    &devalidate_meta_cache($fname);
 2763: 		}
 2764: 	    }
 2765: 	    &Reply( $client, "ok\n", $userinput);
 2766: 	} else {
 2767: 	    &Failure($client, "not_found\n", $userinput);
 2768: 	}
 2769:     } else {
 2770: 	&Failure($client, "rejected\n", $userinput);
 2771:     }
 2772:     return 1;
 2773: }
 2774: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
 2775: 
 2776: sub devalidate_meta_cache {
 2777:     my ($url) = @_;
 2778:     use Cache::Memcached;
 2779:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
 2780:     $url = &Apache::lonnet::declutter($url);
 2781:     $url =~ s-\.meta$--;
 2782:     my $id = &escape('meta:'.$url);
 2783:     $memcache->delete($id);
 2784: }
 2785: 
 2786: #
 2787: #   Fetch a user file from a remote server to the user's home directory
 2788: #   userfiles subdir.
 2789: # Parameters:
 2790: #    $cmd      - The command that got us here.
 2791: #    $tail     - Tail of the command (remaining parameters).
 2792: #    $client   - File descriptor connected to client.
 2793: # Returns
 2794: #     0        - Requested to exit, caller should shut down.
 2795: #     1        - Continue processing.
 2796: #
 2797: sub fetch_user_file_handler {
 2798: 
 2799:     my ($cmd, $tail, $client) = @_;
 2800: 
 2801:     my $userinput = "$cmd:$tail";
 2802:     my $fname           = $tail;
 2803:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
 2804:     my $udir=&propath($udom,$uname).'/userfiles';
 2805:     unless (-e $udir) {
 2806: 	mkdir($udir,0770); 
 2807:     }
 2808:     Debug("fetch user file for $fname");
 2809:     if (-e $udir) {
 2810: 	$ufile=~s/^[\.\~]+//;
 2811: 
 2812: 	# IF necessary, create the path right down to the file.
 2813: 	# Note that any regular files in the way of this path are
 2814: 	# wiped out to deal with some earlier folly of mine.
 2815: 
 2816: 	if (!&mkpath($udir.'/'.$ufile)) {
 2817: 	    &Failure($client, "unable_to_create\n", $userinput);	    
 2818: 	}
 2819: 
 2820: 	my $destname=$udir.'/'.$ufile;
 2821: 	my $transname=$udir.'/'.$ufile.'.in.transit';
 2822:         my $clientprotocol=$Apache::lonnet::protocol{$clientname};
 2823:         $clientprotocol = 'http' if ($clientprotocol ne 'https');
 2824: 	my $clienthost = &Apache::lonnet::hostname($clientname);
 2825: 	my $remoteurl=$clientprotocol.'://'.$clienthost.'/userfiles/'.$fname;
 2826: 	my $response;
 2827: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
 2828: 	my $request=new HTTP::Request('GET',"$remoteurl");
 2829:         my $verifycert = 1;
 2830:         my @machine_ids = &Apache::lonnet::current_machine_ids();
 2831:         if (grep(/^\Q$clientname\E$/,@machine_ids)) {
 2832:             $verifycert = 0;
 2833:         }
 2834:         $response = &LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,$verifycert);
 2835: 	if ($response->is_error()) {
 2836: 	    unlink($transname);
 2837: 	    my $message=$response->status_line;
 2838: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
 2839: 	    &Failure($client, "failed\n", $userinput);
 2840: 	} else {
 2841: 	    Debug("Renaming $transname to $destname");
 2842: 	    if (!rename($transname,$destname)) {
 2843: 		&logthis("Unable to move $transname to $destname");
 2844: 		unlink($transname);
 2845: 		&Failure($client, "failed\n", $userinput);
 2846: 	    } else {
 2847:                 if ($fname =~ /^default.+\.(page|sequence)$/) {
 2848:                     my ($major,$minor) = split(/\./,$clientversion);
 2849:                     if (($major < 2) || ($major == 2 && $minor < 11)) {
 2850:                         my $now = time;
 2851:                         &Apache::lonnet::do_cache_new('crschange',$udom.'_'.$uname,$now,600);
 2852:                         my $key = &escape('internal.contentchange');
 2853:                         my $what = "$key=$now";
 2854:                         my $hashref = &tie_user_hash($udom,$uname,'environment',
 2855:                                                      &GDBM_WRCREAT(),"P",$what);
 2856:                         if ($hashref) {
 2857:                             $hashref->{$key}=$now;
 2858:                             if (!&untie_user_hash($hashref)) {
 2859:                                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
 2860:                                          "when updating internal.contentchange");
 2861:                             }
 2862:                         }
 2863:                     }
 2864:                 }
 2865: 		&Reply($client, "ok\n", $userinput);
 2866: 	    }
 2867: 	}   
 2868:     } else {
 2869: 	&Failure($client, "not_home\n", $userinput);
 2870:     }
 2871:     return 1;
 2872: }
 2873: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
 2874: 
 2875: #
 2876: #   Remove a file from a user's home directory userfiles subdirectory.
 2877: # Parameters:
 2878: #    cmd   - the Lond request keyword that got us here.
 2879: #    tail  - the part of the command past the keyword.
 2880: #    client- File descriptor connected with the client.
 2881: #
 2882: # Returns:
 2883: #    1    - Continue processing.
 2884: sub remove_user_file_handler {
 2885:     my ($cmd, $tail, $client) = @_;
 2886: 
 2887:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
 2888: 
 2889:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
 2890:     if ($ufile =~m|/\.\./|) {
 2891: 	# any files paths with /../ in them refuse 
 2892: 	# to deal with
 2893: 	&Failure($client, "refused\n", "$cmd:$tail");
 2894:     } else {
 2895: 	my $udir = &propath($udom,$uname);
 2896: 	if (-e $udir) {
 2897: 	    my $file=$udir.'/userfiles/'.$ufile;
 2898: 	    if (-e $file) {
 2899: 		#
 2900: 		#   If the file is a regular file unlink is fine...
 2901: 		#   However it's possible the client wants a dir 
 2902: 		#   removed, in which case rmdir is more appropriate.
 2903: 		#   Note: rmdir will only remove an empty directory.
 2904: 		#
 2905: 	        if (-f $file){
 2906: 		    unlink($file);
 2907:                     # for html files remove the associated .bak file 
 2908:                     # which may have been created by the editor.
 2909:                     if ($ufile =~ m{^((docs|supplemental)/(?:\d+|default)/\d+(?:|/.+)/)[^/]+\.x?html?$}i) {
 2910:                         my $path = $1;
 2911:                         if (-e $file.'.bak') {
 2912:                             unlink($file.'.bak');
 2913:                         }
 2914:                     }
 2915: 		} elsif(-d $file) {
 2916: 		    rmdir($file);
 2917: 		}
 2918: 		if (-e $file) {
 2919: 		    #  File is still there after we deleted it ?!?
 2920: 
 2921: 		    &Failure($client, "failed\n", "$cmd:$tail");
 2922: 		} else {
 2923: 		    &Reply($client, "ok\n", "$cmd:$tail");
 2924: 		}
 2925: 	    } else {
 2926: 		&Failure($client, "not_found\n", "$cmd:$tail");
 2927: 	    }
 2928: 	} else {
 2929: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 2930: 	}
 2931:     }
 2932:     return 1;
 2933: }
 2934: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
 2935: 
 2936: #
 2937: #   make a directory in a user's home directory userfiles subdirectory.
 2938: # Parameters:
 2939: #    cmd   - the Lond request keyword that got us here.
 2940: #    tail  - the part of the command past the keyword.
 2941: #    client- File descriptor connected with the client.
 2942: #
 2943: # Returns:
 2944: #    1    - Continue processing.
 2945: sub mkdir_user_file_handler {
 2946:     my ($cmd, $tail, $client) = @_;
 2947: 
 2948:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
 2949:     $dir=&unescape($dir);
 2950:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
 2951:     if ($ufile =~m|/\.\./|) {
 2952: 	# any files paths with /../ in them refuse 
 2953: 	# to deal with
 2954: 	&Failure($client, "refused\n", "$cmd:$tail");
 2955:     } else {
 2956: 	my $udir = &propath($udom,$uname);
 2957: 	if (-e $udir) {
 2958: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
 2959: 	    if (!&mkpath($newdir)) {
 2960: 		&Failure($client, "failed\n", "$cmd:$tail");
 2961: 	    }
 2962: 	    &Reply($client, "ok\n", "$cmd:$tail");
 2963: 	} else {
 2964: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 2965: 	}
 2966:     }
 2967:     return 1;
 2968: }
 2969: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
 2970: 
 2971: #
 2972: #   rename a file in a user's home directory userfiles subdirectory.
 2973: # Parameters:
 2974: #    cmd   - the Lond request keyword that got us here.
 2975: #    tail  - the part of the command past the keyword.
 2976: #    client- File descriptor connected with the client.
 2977: #
 2978: # Returns:
 2979: #    1    - Continue processing.
 2980: sub rename_user_file_handler {
 2981:     my ($cmd, $tail, $client) = @_;
 2982: 
 2983:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
 2984:     $old=&unescape($old);
 2985:     $new=&unescape($new);
 2986:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
 2987: 	# any files paths with /../ in them refuse to deal with
 2988: 	&Failure($client, "refused\n", "$cmd:$tail");
 2989:     } else {
 2990: 	my $udir = &propath($udom,$uname);
 2991: 	if (-e $udir) {
 2992: 	    my $oldfile=$udir.'/userfiles/'.$old;
 2993: 	    my $newfile=$udir.'/userfiles/'.$new;
 2994: 	    if (-e $newfile) {
 2995: 		&Failure($client, "exists\n", "$cmd:$tail");
 2996: 	    } elsif (! -e $oldfile) {
 2997: 		&Failure($client, "not_found\n", "$cmd:$tail");
 2998: 	    } else {
 2999: 		if (!rename($oldfile,$newfile)) {
 3000: 		    &Failure($client, "failed\n", "$cmd:$tail");
 3001: 		} else {
 3002: 		    &Reply($client, "ok\n", "$cmd:$tail");
 3003: 		}
 3004: 	    }
 3005: 	} else {
 3006: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 3007: 	}
 3008:     }
 3009:     return 1;
 3010: }
 3011: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
 3012: 
 3013: #
 3014: #  Checks if the specified user has an active session on the server
 3015: #  return ok if so, not_found if not
 3016: #
 3017: # Parameters:
 3018: #   cmd      - The request keyword that dispatched to tus.
 3019: #   tail     - The tail of the request (colon separated parameters).
 3020: #   client   - Filehandle open on the client.
 3021: # Return:
 3022: #    1.
 3023: sub user_has_session_handler {
 3024:     my ($cmd, $tail, $client) = @_;
 3025: 
 3026:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
 3027:     
 3028:     opendir(DIR,$perlvar{'lonIDsDir'});
 3029:     my $filename;
 3030:     while ($filename=readdir(DIR)) {
 3031: 	last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
 3032:     }
 3033:     if ($filename) {
 3034: 	&Reply($client, "ok\n", "$cmd:$tail");
 3035:     } else {
 3036: 	&Failure($client, "not_found\n", "$cmd:$tail");
 3037:     }
 3038:     return 1;
 3039: 
 3040: }
 3041: &register_handler("userhassession", \&user_has_session_handler, 0,1,0);
 3042: 
 3043: sub del_usersession_handler {
 3044:     my ($cmd, $tail, $client) = @_;
 3045: 
 3046:     my $result;
 3047:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
 3048:     if (($udom =~ /^$LONCAPA::match_domain$/) && ($uname =~ /^$LONCAPA::match_username$/)) {
 3049:         my $lonidsdir = $perlvar{'lonIDsDir'};
 3050:         if (-d $lonidsdir) {
 3051:             if (opendir(DIR,$lonidsdir)) {
 3052:                 my $filename;
 3053:                 while ($filename=readdir(DIR)) {
 3054:                     if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/) {
 3055:                         if (tie(my %oldenv,'GDBM_File',"$lonidsdir/$filename",
 3056:                                 &GDBM_READER(),0640)) {
 3057:                             my $linkedfile;
 3058:                             if (exists($oldenv{'user.linkedenv'})) {
 3059:                                 $linkedfile = $oldenv{'user.linkedenv'};
 3060:                             }
 3061:                             untie(%oldenv);
 3062:                             $result = unlink("$lonidsdir/$filename");
 3063:                             if ($result) {
 3064:                                 if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
 3065:                                     if (-l "$lonidsdir/$linkedfile.id") {
 3066:                                         unlink("$lonidsdir/$linkedfile.id");
 3067:                                     }
 3068:                                 }
 3069:                             }
 3070:                         } else {
 3071:                             $result = unlink("$lonidsdir/$filename");
 3072:                         }
 3073:                         last;
 3074:                     }
 3075:                 }
 3076:             }
 3077:         }
 3078:         if ($result == 1) {
 3079:             &Reply($client, "$result\n", "$cmd:$tail");
 3080:         } else {
 3081:             &Reply($client, "not_found\n", "$cmd:$tail");
 3082:         }
 3083:     } else {
 3084:         &Failure($client, "invalid_user\n", "$cmd:$tail");
 3085:     }
 3086:     return 1;
 3087: }
 3088: 
 3089: &register_handler("delusersession", \&del_usersession_handler, 0,1,0);
 3090: 
 3091: #
 3092: #  Authenticate access to a user file by checking that the token the user's 
 3093: #  passed also exists in their session file
 3094: #
 3095: # Parameters:
 3096: #   cmd      - The request keyword that dispatched to tus.
 3097: #   tail     - The tail of the request (colon separated parameters).
 3098: #   client   - Filehandle open on the client.
 3099: # Return:
 3100: #    1.
 3101: sub token_auth_user_file_handler {
 3102:     my ($cmd, $tail, $client) = @_;
 3103: 
 3104:     my ($fname, $session) = split(/:/, $tail);
 3105:     
 3106:     chomp($session);
 3107:     my $reply="non_auth";
 3108:     my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
 3109:     if (open(ENVIN,"$file")) {
 3110: 	flock(ENVIN,LOCK_SH);
 3111: 	tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
 3112: 	if (exists($disk_env{"userfile.$fname"})) {
 3113: 	    $reply="ok";
 3114: 	} else {
 3115: 	    foreach my $envname (keys(%disk_env)) {
 3116: 		if ($envname=~ m|^userfile\.\Q$fname\E|) {
 3117: 		    $reply="ok";
 3118: 		    last;
 3119: 		}
 3120: 	    }
 3121: 	}
 3122: 	untie(%disk_env);
 3123: 	close(ENVIN);
 3124: 	&Reply($client, \$reply, "$cmd:$tail");
 3125:     } else {
 3126: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
 3127:     }
 3128:     return 1;
 3129: 
 3130: }
 3131: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
 3132: 
 3133: #
 3134: #   Unsubscribe from a resource.
 3135: #
 3136: # Parameters:
 3137: #    $cmd      - The command that got us here.
 3138: #    $tail     - Tail of the command (remaining parameters).
 3139: #    $client   - File descriptor connected to client.
 3140: # Returns
 3141: #     0        - Requested to exit, caller should shut down.
 3142: #     1        - Continue processing.
 3143: #
 3144: sub unsubscribe_handler {
 3145:     my ($cmd, $tail, $client) = @_;
 3146: 
 3147:     my $userinput= "$cmd:$tail";
 3148:     
 3149:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
 3150: 
 3151:     &Debug("Unsubscribing $fname");
 3152:     if (-e $fname) {
 3153: 	&Debug("Exists");
 3154: 	&Reply($client, &unsub($fname,$clientip), $userinput);
 3155:     } else {
 3156: 	&Failure($client, "not_found\n", $userinput);
 3157:     }
 3158:     return 1;
 3159: }
 3160: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
 3161: 
 3162: #   Subscribe to a resource
 3163: #
 3164: # Parameters:
 3165: #    $cmd      - The command that got us here.
 3166: #    $tail     - Tail of the command (remaining parameters).
 3167: #    $client   - File descriptor connected to client.
 3168: # Returns
 3169: #     0        - Requested to exit, caller should shut down.
 3170: #     1        - Continue processing.
 3171: #
 3172: sub subscribe_handler {
 3173:     my ($cmd, $tail, $client)= @_;
 3174: 
 3175:     my $userinput  = "$cmd:$tail";
 3176: 
 3177:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
 3178: 
 3179:     return 1;
 3180: }
 3181: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
 3182: 
 3183: #
 3184: #   Determine the latest version of a resource (it looks for the highest
 3185: #   past version and then returns that +1)
 3186: #
 3187: # Parameters:
 3188: #    $cmd      - The command that got us here.
 3189: #    $tail     - Tail of the command (remaining parameters).
 3190: #                 (Should consist of an absolute path to a file)
 3191: #    $client   - File descriptor connected to client.
 3192: # Returns
 3193: #     0        - Requested to exit, caller should shut down.
 3194: #     1        - Continue processing.
 3195: #
 3196: sub current_version_handler {
 3197:     my ($cmd, $tail, $client) = @_;
 3198: 
 3199:     my $userinput= "$cmd:$tail";
 3200:    
 3201:     my $fname   = $tail;
 3202:     &Reply( $client, &currentversion($fname)."\n", $userinput);
 3203:     return 1;
 3204: 
 3205: }
 3206: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
 3207: 
 3208: #  Make an entry in a user's activity log.
 3209: #
 3210: # Parameters:
 3211: #    $cmd      - The command that got us here.
 3212: #    $tail     - Tail of the command (remaining parameters).
 3213: #    $client   - File descriptor connected to client.
 3214: # Returns
 3215: #     0        - Requested to exit, caller should shut down.
 3216: #     1        - Continue processing.
 3217: #
 3218: sub activity_log_handler {
 3219:     my ($cmd, $tail, $client) = @_;
 3220: 
 3221: 
 3222:     my $userinput= "$cmd:$tail";
 3223: 
 3224:     my ($udom,$uname,$what)=split(/:/,$tail);
 3225:     chomp($what);
 3226:     my $proname=&propath($udom,$uname);
 3227:     my $now=time;
 3228:     my $hfh;
 3229:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
 3230: 	print $hfh "$now:$clientname:$what\n";
 3231: 	&Reply( $client, "ok\n", $userinput); 
 3232:     } else {
 3233: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
 3234: 		 ."while attempting log\n", 
 3235: 		 $userinput);
 3236:     }
 3237: 
 3238:     return 1;
 3239: }
 3240: &register_handler("log", \&activity_log_handler, 0, 1, 0);
 3241: 
 3242: #
 3243: #   Put a namespace entry in a user profile hash.
 3244: #   My druthers would be for this to be an encrypted interaction too.
 3245: #   anything that might be an inadvertent covert channel about either
 3246: #   user authentication or user personal information....
 3247: #
 3248: # Parameters:
 3249: #    $cmd      - The command that got us here.
 3250: #    $tail     - Tail of the command (remaining parameters).
 3251: #    $client   - File descriptor connected to client.
 3252: # Returns
 3253: #     0        - Requested to exit, caller should shut down.
 3254: #     1        - Continue processing.
 3255: #
 3256: sub put_user_profile_entry {
 3257:     my ($cmd, $tail, $client)  = @_;
 3258: 
 3259:     my $userinput = "$cmd:$tail";
 3260:     
 3261:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
 3262:     if ($namespace ne 'roles') {
 3263: 	chomp($what);
 3264: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3265: 				  &GDBM_WRCREAT(),"P",$what);
 3266: 	if($hashref) {
 3267: 	    my @pairs=split(/\&/,$what);
 3268: 	    foreach my $pair (@pairs) {
 3269: 		my ($key,$value)=split(/=/,$pair);
 3270: 		$hashref->{$key}=$value;
 3271: 	    }
 3272: 	    if (&untie_user_hash($hashref)) {
 3273: 		&Reply( $client, "ok\n", $userinput);
 3274: 	    } else {
 3275: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 3276: 			"while attempting put\n", 
 3277: 			$userinput);
 3278: 	    }
 3279: 	} else {
 3280: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3281: 		     "while attempting put\n", $userinput);
 3282: 	}
 3283:     } else {
 3284:         &Failure( $client, "refused\n", $userinput);
 3285:     }
 3286:     
 3287:     return 1;
 3288: }
 3289: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
 3290: 
 3291: #   Put a piece of new data in hash, returns error if entry already exists
 3292: # Parameters:
 3293: #    $cmd      - The command that got us here.
 3294: #    $tail     - Tail of the command (remaining parameters).
 3295: #    $client   - File descriptor connected to client.
 3296: # Returns
 3297: #     0        - Requested to exit, caller should shut down.
 3298: #     1        - Continue processing.
 3299: #
 3300: sub newput_user_profile_entry {
 3301:     my ($cmd, $tail, $client)  = @_;
 3302: 
 3303:     my $userinput = "$cmd:$tail";
 3304: 
 3305:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
 3306:     if ($namespace eq 'roles') {
 3307:         &Failure( $client, "refused\n", $userinput);
 3308: 	return 1;
 3309:     }
 3310: 
 3311:     chomp($what);
 3312: 
 3313:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3314: 				 &GDBM_WRCREAT(),"N",$what);
 3315:     if(!$hashref) {
 3316: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3317: 		  "while attempting put\n", $userinput);
 3318: 	return 1;
 3319:     }
 3320: 
 3321:     my @pairs=split(/\&/,$what);
 3322:     foreach my $pair (@pairs) {
 3323: 	my ($key,$value)=split(/=/,$pair);
 3324: 	if (exists($hashref->{$key})) {
 3325:             if (!&untie_user_hash($hashref)) {
 3326:                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
 3327:                          "while attempting newput - early out as key exists");
 3328:             }
 3329:             &Failure($client, "key_exists: ".$key."\n",$userinput);
 3330:             return 1;
 3331: 	}
 3332:     }
 3333: 
 3334:     foreach my $pair (@pairs) {
 3335: 	my ($key,$value)=split(/=/,$pair);
 3336: 	$hashref->{$key}=$value;
 3337:     }
 3338: 
 3339:     if (&untie_user_hash($hashref)) {
 3340: 	&Reply( $client, "ok\n", $userinput);
 3341:     } else {
 3342: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 3343: 		 "while attempting put\n", 
 3344: 		 $userinput);
 3345:     }
 3346:     return 1;
 3347: }
 3348: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
 3349: 
 3350: # 
 3351: #   Increment a profile entry in the user history file.
 3352: #   The history contains keyword value pairs.  In this case,
 3353: #   The value itself is a pair of numbers.  The first, the current value
 3354: #   the second an increment that this function applies to the current
 3355: #   value.
 3356: #
 3357: # Parameters:
 3358: #    $cmd      - The command that got us here.
 3359: #    $tail     - Tail of the command (remaining parameters).
 3360: #    $client   - File descriptor connected to client.
 3361: # Returns
 3362: #     0        - Requested to exit, caller should shut down.
 3363: #     1        - Continue processing.
 3364: #
 3365: sub increment_user_value_handler {
 3366:     my ($cmd, $tail, $client) = @_;
 3367:     
 3368:     my $userinput   = "$cmd:$tail";
 3369:     
 3370:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
 3371:     if ($namespace ne 'roles') {
 3372:         chomp($what);
 3373: 	my $hashref = &tie_user_hash($udom, $uname,
 3374: 				     $namespace, &GDBM_WRCREAT(),
 3375: 				     "P",$what);
 3376: 	if ($hashref) {
 3377: 	    my @pairs=split(/\&/,$what);
 3378: 	    foreach my $pair (@pairs) {
 3379: 		my ($key,$value)=split(/=/,$pair);
 3380:                 $value = &unescape($value);
 3381: 		# We could check that we have a number...
 3382: 		if (! defined($value) || $value eq '') {
 3383: 		    $value = 1;
 3384: 		}
 3385: 		$hashref->{$key}+=$value;
 3386:                 if ($namespace eq 'nohist_resourcetracker') {
 3387:                     if ($hashref->{$key} < 0) {
 3388:                         $hashref->{$key} = 0;
 3389:                     }
 3390:                 }
 3391: 	    }
 3392: 	    if (&untie_user_hash($hashref)) {
 3393: 		&Reply( $client, "ok\n", $userinput);
 3394: 	    } else {
 3395: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 3396: 			 "while attempting inc\n", $userinput);
 3397: 	    }
 3398: 	} else {
 3399: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3400: 		     "while attempting inc\n", $userinput);
 3401: 	}
 3402:     } else {
 3403: 	&Failure($client, "refused\n", $userinput);
 3404:     }
 3405:     
 3406:     return 1;
 3407: }
 3408: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
 3409: 
 3410: #
 3411: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
 3412: #   Each 'role' a user has implies a set of permissions.  Adding a new role
 3413: #   for a person grants the permissions packaged with that role
 3414: #   to that user when the role is selected.
 3415: #
 3416: # Parameters:
 3417: #    $cmd       - The command string (rolesput).
 3418: #    $tail      - The remainder of the request line.  For rolesput this
 3419: #                 consists of a colon separated list that contains:
 3420: #                 The domain and user that is granting the role (logged).
 3421: #                 The domain and user that is getting the role.
 3422: #                 The roles being granted as a set of & separated pairs.
 3423: #                 each pair a key value pair.
 3424: #    $client    - File descriptor connected to the client.
 3425: # Returns:
 3426: #     0         - If the daemon should exit
 3427: #     1         - To continue processing.
 3428: #
 3429: #
 3430: sub roles_put_handler {
 3431:     my ($cmd, $tail, $client) = @_;
 3432: 
 3433:     my $userinput  = "$cmd:$tail";
 3434: 
 3435:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
 3436:     
 3437: 
 3438:     my $namespace='roles';
 3439:     chomp($what);
 3440:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3441: 				 &GDBM_WRCREAT(), "P",
 3442: 				 "$exedom:$exeuser:$what");
 3443:     #
 3444:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
 3445:     #  handle is open for the minimal amount of time.  Since the flush
 3446:     #  is done on close this improves the chances the log will be an un-
 3447:     #  corrupted ordered thing.
 3448:     if ($hashref) {
 3449: 	my $pass_entry = &get_auth_type($udom, $uname);
 3450: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
 3451: 	$auth_type = $auth_type.":";
 3452: 	my @pairs=split(/\&/,$what);
 3453: 	foreach my $pair (@pairs) {
 3454: 	    my ($key,$value)=split(/=/,$pair);
 3455: 	    &manage_permissions($key, $udom, $uname,
 3456: 			       $auth_type);
 3457: 	    $hashref->{$key}=$value;
 3458: 	}
 3459: 	if (&untie_user_hash($hashref)) {
 3460: 	    &Reply($client, "ok\n", $userinput);
 3461: 	} else {
 3462: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 3463: 		     "while attempting rolesput\n", $userinput);
 3464: 	}
 3465:     } else {
 3466: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3467: 		 "while attempting rolesput\n", $userinput);
 3468:     }
 3469:     return 1;
 3470: }
 3471: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
 3472: 
 3473: #
 3474: #   Deletes (removes) a role for a user.   This is equivalent to removing
 3475: #  a permissions package associated with the role from the user's profile.
 3476: #
 3477: # Parameters:
 3478: #     $cmd                 - The command (rolesdel)
 3479: #     $tail                - The remainder of the request line. This consists
 3480: #                             of:
 3481: #                             The domain and user requesting the change (logged)
 3482: #                             The domain and user being changed.
 3483: #                             The roles being revoked.  These are shipped to us
 3484: #                             as a bunch of & separated role name keywords.
 3485: #     $client              - The file handle open on the client.
 3486: # Returns:
 3487: #     1                    - Continue processing
 3488: #     0                    - Exit.
 3489: #
 3490: sub roles_delete_handler {
 3491:     my ($cmd, $tail, $client)  = @_;
 3492: 
 3493:     my $userinput    = "$cmd:$tail";
 3494:    
 3495:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
 3496:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
 3497: 	   "what = ".$what);
 3498:     my $namespace='roles';
 3499:     chomp($what);
 3500:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3501: 				 &GDBM_WRCREAT(), "D",
 3502: 				 "$exedom:$exeuser:$what");
 3503:     
 3504:     if ($hashref) {
 3505: 	my @rolekeys=split(/\&/,$what);
 3506: 	
 3507: 	foreach my $key (@rolekeys) {
 3508: 	    delete $hashref->{$key};
 3509: 	}
 3510: 	if (&untie_user_hash($hashref)) {
 3511: 	    &Reply($client, "ok\n", $userinput);
 3512: 	} else {
 3513: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 3514: 		     "while attempting rolesdel\n", $userinput);
 3515: 	}
 3516:     } else {
 3517:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3518: 		 "while attempting rolesdel\n", $userinput);
 3519:     }
 3520:     
 3521:     return 1;
 3522: }
 3523: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
 3524: 
 3525: # Unencrypted get from a user's profile database.  See 
 3526: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
 3527: # This function retrieves a keyed item from a specific named database in the
 3528: # user's directory.
 3529: #
 3530: # Parameters:
 3531: #   $cmd             - Command request keyword (get).
 3532: #   $tail            - Tail of the command.  This is a colon separated list
 3533: #                      consisting of the domain and username that uniquely
 3534: #                      identifies the profile,
 3535: #                      The 'namespace' which selects the gdbm file to 
 3536: #                      do the lookup in, 
 3537: #                      & separated list of keys to lookup.  Note that
 3538: #                      the values are returned as an & separated list too.
 3539: #   $client          - File descriptor open on the client.
 3540: # Returns:
 3541: #   1       - Continue processing.
 3542: #   0       - Exit.
 3543: #
 3544: sub get_profile_entry {
 3545:     my ($cmd, $tail, $client) = @_;
 3546: 
 3547:     my $userinput= "$cmd:$tail";
 3548:    
 3549:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 3550:     chomp($what);
 3551: 
 3552: 
 3553:     my $replystring = read_profile($udom, $uname, $namespace, $what);
 3554:     my ($first) = split(/:/,$replystring);
 3555:     if($first ne "error") {
 3556: 	&Reply($client, \$replystring, $userinput);
 3557:     } else {
 3558: 	&Failure($client, $replystring." while attempting get\n", $userinput);
 3559:     }
 3560:     return 1;
 3561: 
 3562: 
 3563: }
 3564: &register_handler("get", \&get_profile_entry, 0,1,0);
 3565: 
 3566: #
 3567: #  Process the encrypted get request.  Note that the request is sent
 3568: #  in clear, but the reply is encrypted.  This is a small covert channel:
 3569: #  information about the sensitive keys is given to the snooper.  Just not
 3570: #  information about the values of the sensitive key.  Hmm if I wanted to
 3571: #  know these I'd snoop for the egets. Get the profile item names from them
 3572: #  and then issue a get for them since there's no enforcement of the
 3573: #  requirement of an encrypted get for particular profile items.  If I
 3574: #  were re-doing this, I'd force the request to be encrypted as well as the
 3575: #  reply.  I'd also just enforce encrypted transactions for all gets since
 3576: #  that would prevent any covert channel snooping.
 3577: #
 3578: #  Parameters:
 3579: #     $cmd               - Command keyword of request (eget).
 3580: #     $tail              - Tail of the command.  See GetProfileEntry
 3581: #                          for more information about this.
 3582: #     $client            - File open on the client.
 3583: #  Returns:
 3584: #     1      - Continue processing
 3585: #     0      - server should exit.
 3586: sub get_profile_entry_encrypted {
 3587:     my ($cmd, $tail, $client) = @_;
 3588: 
 3589:     my $userinput = "$cmd:$tail";
 3590:    
 3591:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 3592:     chomp($what);
 3593:     my $qresult = read_profile($udom, $uname, $namespace, $what);
 3594:     my ($first) = split(/:/, $qresult);
 3595:     if($first ne "error") {
 3596: 	
 3597: 	if ($cipher) {
 3598: 	    my $cmdlength=length($qresult);
 3599: 	    $qresult.="         ";
 3600: 	    my $encqresult='';
 3601: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 3602: 		$encqresult.= unpack("H16", 
 3603: 				     $cipher->encrypt(substr($qresult,
 3604: 							     $encidx,
 3605: 							     8)));
 3606: 	    }
 3607: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
 3608: 	} else {
 3609: 		&Failure( $client, "error:no_key\n", $userinput);
 3610: 	    }
 3611:     } else {
 3612: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
 3613: 
 3614:     }
 3615:     
 3616:     return 1;
 3617: }
 3618: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
 3619: 
 3620: #
 3621: #   Deletes a key in a user profile database.
 3622: #   
 3623: #   Parameters:
 3624: #       $cmd                  - Command keyword (del).
 3625: #       $tail                 - Command tail.  IN this case a colon
 3626: #                               separated list containing:
 3627: #                               The domain and user that identifies uniquely
 3628: #                               the identity of the user.
 3629: #                               The profile namespace (name of the profile
 3630: #                               database file).
 3631: #                               & separated list of keywords to delete.
 3632: #       $client              - File open on client socket.
 3633: # Returns:
 3634: #     1   - Continue processing
 3635: #     0   - Exit server.
 3636: #
 3637: #
 3638: sub delete_profile_entry {
 3639:     my ($cmd, $tail, $client) = @_;
 3640: 
 3641:     my $userinput = "cmd:$tail";
 3642: 
 3643:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 3644:     chomp($what);
 3645:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3646: 				 &GDBM_WRCREAT(),
 3647: 				 "D",$what);
 3648:     if ($hashref) {
 3649:         my @keys=split(/\&/,$what);
 3650: 	foreach my $key (@keys) {
 3651: 	    delete($hashref->{$key});
 3652: 	}
 3653: 	if (&untie_user_hash($hashref)) {
 3654: 	    &Reply($client, "ok\n", $userinput);
 3655: 	} else {
 3656: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3657: 		    "while attempting del\n", $userinput);
 3658: 	}
 3659:     } else {
 3660: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3661: 		 "while attempting del\n", $userinput);
 3662:     }
 3663:     return 1;
 3664: }
 3665: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
 3666: 
 3667: #
 3668: #  List the set of keys that are defined in a profile database file.
 3669: #  A successful reply from this will contain an & separated list of
 3670: #  the keys. 
 3671: # Parameters:
 3672: #     $cmd              - Command request (keys).
 3673: #     $tail             - Remainder of the request, a colon separated
 3674: #                         list containing domain/user that identifies the
 3675: #                         user being queried, and the database namespace
 3676: #                         (database filename essentially).
 3677: #     $client           - File open on the client.
 3678: #  Returns:
 3679: #    1    - Continue processing.
 3680: #    0    - Exit the server.
 3681: #
 3682: sub get_profile_keys {
 3683:     my ($cmd, $tail, $client) = @_;
 3684: 
 3685:     my $userinput = "$cmd:$tail";
 3686: 
 3687:     my ($udom,$uname,$namespace)=split(/:/,$tail);
 3688:     my $qresult='';
 3689:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3690: 				  &GDBM_READER());
 3691:     if ($hashref) {
 3692: 	foreach my $key (keys %$hashref) {
 3693: 	    $qresult.="$key&";
 3694: 	}
 3695: 	if (&untie_user_hash($hashref)) {
 3696: 	    $qresult=~s/\&$//;
 3697: 	    &Reply($client, \$qresult, $userinput);
 3698: 	} else {
 3699: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3700: 		    "while attempting keys\n", $userinput);
 3701: 	}
 3702:     } else {
 3703: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3704: 		 "while attempting keys\n", $userinput);
 3705:     }
 3706:    
 3707:     return 1;
 3708: }
 3709: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
 3710: 
 3711: #
 3712: #   Dump the contents of a user profile database.
 3713: #   Note that this constitutes a very large covert channel too since
 3714: #   the dump will return sensitive information that is not encrypted.
 3715: #   The naive security assumption is that the session negotiation ensures
 3716: #   our client is trusted and I don't believe that's assured at present.
 3717: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
 3718: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
 3719: # 
 3720: #  Parameters:
 3721: #     $cmd           - The command request keyword (currentdump).
 3722: #     $tail          - Remainder of the request, consisting of a colon
 3723: #                      separated list that has the domain/username and
 3724: #                      the namespace to dump (database file).
 3725: #     $client        - file open on the remote client.
 3726: # Returns:
 3727: #     1    - Continue processing.
 3728: #     0    - Exit the server.
 3729: #
 3730: sub dump_profile_database {
 3731:     my ($cmd, $tail, $client) = @_;
 3732: 
 3733:     my $res = LONCAPA::Lond::dump_profile_database($tail);
 3734: 
 3735:     if ($res =~ /^error:/) {
 3736:         Failure($client, \$res, "$cmd:$tail");
 3737:     } else {
 3738:         Reply($client, \$res, "$cmd:$tail");
 3739:     }
 3740: 
 3741:     return 1;  
 3742: 
 3743:     #TODO remove 
 3744:     my $userinput = "$cmd:$tail";
 3745:    
 3746:     my ($udom,$uname,$namespace) = split(/:/,$tail);
 3747:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3748: 				 &GDBM_READER());
 3749:     if ($hashref) {
 3750: 	# Structure of %data:
 3751: 	# $data{$symb}->{$parameter}=$value;
 3752: 	# $data{$symb}->{'v.'.$parameter}=$version;
 3753: 	# since $parameter will be unescaped, we do not
 3754:  	# have to worry about silly parameter names...
 3755: 	
 3756:         my $qresult='';
 3757: 	my %data = ();                     # A hash of anonymous hashes..
 3758: 	while (my ($key,$value) = each(%$hashref)) {
 3759: 	    my ($v,$symb,$param) = split(/:/,$key);
 3760: 	    next if ($v eq 'version' || $symb eq 'keys');
 3761: 	    next if (exists($data{$symb}) && 
 3762: 		     exists($data{$symb}->{$param}) &&
 3763: 		     $data{$symb}->{'v.'.$param} > $v);
 3764: 	    $data{$symb}->{$param}=$value;
 3765: 	    $data{$symb}->{'v.'.$param}=$v;
 3766: 	}
 3767: 	if (&untie_user_hash($hashref)) {
 3768: 	    while (my ($symb,$param_hash) = each(%data)) {
 3769: 		while(my ($param,$value) = each (%$param_hash)){
 3770: 		    next if ($param =~ /^v\./);       # Ignore versions...
 3771: 		    #
 3772: 		    #   Just dump the symb=value pairs separated by &
 3773: 		    #
 3774: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
 3775: 		}
 3776: 	    }
 3777: 	    chop($qresult);
 3778: 	    &Reply($client , \$qresult, $userinput);
 3779: 	} else {
 3780: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 3781: 		     "while attempting currentdump\n", $userinput);
 3782: 	}
 3783:     } else {
 3784: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3785: 		"while attempting currentdump\n", $userinput);
 3786:     }
 3787: 
 3788:     return 1;
 3789: }
 3790: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
 3791: 
 3792: #
 3793: #   Dump a profile database with an optional regular expression
 3794: #   to match against the keys.  In this dump, no effort is made
 3795: #   to separate symb from version information. Presumably the
 3796: #   databases that are dumped by this command are of a different
 3797: #   structure.  Need to look at this and improve the documentation of
 3798: #   both this and the currentdump handler.
 3799: # Parameters:
 3800: #    $cmd                     - The command keyword.
 3801: #    $tail                    - All of the characters after the $cmd:
 3802: #                               These are expected to be a colon
 3803: #                               separated list containing:
 3804: #                               domain/user - identifying the user.
 3805: #                               namespace   - identifying the database.
 3806: #                               regexp      - optional regular expression
 3807: #                                             that is matched against
 3808: #                                             database keywords to do
 3809: #                                             selective dumps.
 3810: #                               range       - optional range of entries
 3811: #                                             e.g., 10-20 would return the
 3812: #                                             10th to 19th items, etc.  
 3813: #   $client                   - Channel open on the client.
 3814: # Returns:
 3815: #    1    - Continue processing.
 3816: # Side effects:
 3817: #    response is written to $client.
 3818: #
 3819: sub dump_with_regexp {
 3820:     my ($cmd, $tail, $client) = @_;
 3821: 
 3822:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
 3823:     
 3824:     if ($res =~ /^error:/) {
 3825:         Failure($client, \$res, "$cmd:$tail");
 3826:     } else {
 3827:         Reply($client, \$res, "$cmd:$tail");
 3828:     }
 3829: 
 3830:     return 1;
 3831: }
 3832: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
 3833: 
 3834: #
 3835: #  Process the encrypted dump request. Original call should
 3836: #  be from lonnet::dump() with seventh arg ($encrypt) set to
 3837: #  1, to ensure that both request and response are encrypted.
 3838: #
 3839: #  Parameters:
 3840: #     $cmd               - Command keyword of request (edump).
 3841: #     $tail              - Tail of the command.
 3842: #                          See &dump_with_regexp for more
 3843: #                          information about this.
 3844: #     $client            - File open on the client.
 3845: #  Returns:
 3846: #     1      - Continue processing
 3847: #     0      - server should exit.
 3848: #
 3849: 
 3850: sub encrypted_dump_with_regexp {
 3851:     my ($cmd, $tail, $client) = @_;
 3852:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
 3853: 
 3854:     if ($res =~ /^error:/) {
 3855:         Failure($client, \$res, "$cmd:$tail");
 3856:     } else {
 3857:         if ($cipher) {
 3858:             my $cmdlength=length($res);
 3859:             $res.="         ";
 3860:             my $encres='';
 3861:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 3862:                 $encres.= unpack("H16",
 3863:                                  $cipher->encrypt(substr($res,
 3864:                                                          $encidx,
 3865:                                                          8)));
 3866:             }
 3867:             &Reply( $client,"enc:$cmdlength:$encres\n","$cmd:$tail");
 3868:         } else {
 3869:             &Failure( $client, "error:no_key\n","$cmd:$tail");
 3870:         }
 3871:     }
 3872: }
 3873: &register_handler("edump", \&encrypted_dump_with_regexp, 0, 1, 0);
 3874: 
 3875: #  Store a set of key=value pairs associated with a versioned name.
 3876: #
 3877: #  Parameters:
 3878: #    $cmd                - Request command keyword.
 3879: #    $tail               - Tail of the request.  This is a colon
 3880: #                          separated list containing:
 3881: #                          domain/user - User and authentication domain.
 3882: #                          namespace   - Name of the database being modified
 3883: #                          rid         - Resource keyword to modify.
 3884: #                          what        - new value associated with rid.
 3885: #                          laststore   - (optional) version=timestamp
 3886: #                                        for most recent transaction for rid
 3887: #                                        in namespace, when cstore was called
 3888: #
 3889: #    $client             - Socket open on the client.
 3890: #
 3891: #
 3892: #  Returns:
 3893: #      1 (keep on processing).
 3894: #  Side-Effects:
 3895: #    Writes to the client
 3896: #    Successful storage will cause either 'ok', or, if $laststore was included
 3897: #    in the tail of the request, and the version number for the last transaction
 3898: #    is larger than the version in $laststore, delay:$numtrans , where $numtrans
 3899: #    is the number of store evevnts recorded for rid in namespace since
 3900: #    lonnet::store() was called by the client.
 3901: #
 3902: sub store_handler {
 3903:     my ($cmd, $tail, $client) = @_;
 3904:  
 3905:     my $userinput = "$cmd:$tail";
 3906:     chomp($tail);
 3907:     my ($udom,$uname,$namespace,$rid,$what,$laststore) =split(/:/,$tail);
 3908:     if ($namespace ne 'roles') {
 3909: 
 3910: 	my @pairs=split(/\&/,$what);
 3911: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
 3912: 				       &GDBM_WRCREAT(), "S",
 3913: 				       "$rid:$what");
 3914: 	if ($hashref) {
 3915: 	    my $now = time;
 3916:             my $numtrans;
 3917:             if ($laststore) {
 3918:                 my ($previousversion,$previoustime) = split(/\=/,$laststore);
 3919:                 my ($lastversion,$lasttime) = (0,0);
 3920:                 $lastversion = $hashref->{"version:$rid"};
 3921:                 if ($lastversion) {
 3922:                     $lasttime = $hashref->{"$lastversion:$rid:timestamp"};
 3923:                 }
 3924:                 if (($previousversion) && ($previousversion !~ /\D/)) {
 3925:                     if (($lastversion > $previousversion) && ($lasttime >= $previoustime)) {
 3926:                         $numtrans = $lastversion - $previousversion;
 3927:                     }
 3928:                 } elsif ($lastversion) {
 3929:                     $numtrans = $lastversion;
 3930:                 }
 3931:                 if ($numtrans) {
 3932:                     $numtrans =~ s/D//g;
 3933:                 }
 3934:             }
 3935: 	    $hashref->{"version:$rid"}++;
 3936: 	    my $version=$hashref->{"version:$rid"};
 3937: 	    my $allkeys=''; 
 3938: 	    foreach my $pair (@pairs) {
 3939: 		my ($key,$value)=split(/=/,$pair);
 3940: 		$allkeys.=$key.':';
 3941: 		$hashref->{"$version:$rid:$key"}=$value;
 3942: 	    }
 3943: 	    $hashref->{"$version:$rid:timestamp"}=$now;
 3944: 	    $allkeys.='timestamp';
 3945: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
 3946: 	    if (&untie_user_hash($hashref)) {
 3947:                 my $msg = 'ok';
 3948:                 if ($numtrans) {
 3949:                     $msg = 'delay:'.$numtrans;
 3950:                 }
 3951: 		&Reply($client, "$msg\n", $userinput);
 3952: 	    } else {
 3953: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3954: 			"while attempting store\n", $userinput);
 3955: 	    }
 3956: 	} else {
 3957: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3958: 		     "while attempting store\n", $userinput);
 3959: 	}
 3960:     } else {
 3961: 	&Failure($client, "refused\n", $userinput);
 3962:     }
 3963: 
 3964:     return 1;
 3965: }
 3966: &register_handler("store", \&store_handler, 0, 1, 0);
 3967: 
 3968: #  Modify a set of key=value pairs associated with a versioned name.
 3969: #
 3970: #  Parameters:
 3971: #    $cmd                - Request command keyword.
 3972: #    $tail               - Tail of the request.  This is a colon
 3973: #                          separated list containing:
 3974: #                          domain/user - User and authentication domain.
 3975: #                          namespace   - Name of the database being modified
 3976: #                          rid         - Resource keyword to modify.
 3977: #                          v           - Version item to modify
 3978: #                          what        - new value associated with rid.
 3979: #
 3980: #    $client             - Socket open on the client.
 3981: #
 3982: #
 3983: #  Returns:
 3984: #      1 (keep on processing).
 3985: #  Side-Effects:
 3986: #    Writes to the client
 3987: sub putstore_handler {
 3988:     my ($cmd, $tail, $client) = @_;
 3989:  
 3990:     my $userinput = "$cmd:$tail";
 3991: 
 3992:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
 3993:     if ($namespace ne 'roles') {
 3994: 
 3995: 	chomp($what);
 3996: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
 3997: 				       &GDBM_WRCREAT(), "M",
 3998: 				       "$rid:$v:$what");
 3999: 	if ($hashref) {
 4000: 	    my $now = time;
 4001: 	    my %data = &hash_extract($what);
 4002: 	    my @allkeys;
 4003: 	    while (my($key,$value) = each(%data)) {
 4004: 		push(@allkeys,$key);
 4005: 		$hashref->{"$v:$rid:$key"} = $value;
 4006: 	    }
 4007: 	    my $allkeys = join(':',@allkeys);
 4008: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
 4009: 
 4010: 	    if (&untie_user_hash($hashref)) {
 4011: 		&Reply($client, "ok\n", $userinput);
 4012: 	    } else {
 4013: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4014: 			"while attempting store\n", $userinput);
 4015: 	    }
 4016: 	} else {
 4017: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 4018: 		     "while attempting store\n", $userinput);
 4019: 	}
 4020:     } else {
 4021: 	&Failure($client, "refused\n", $userinput);
 4022:     }
 4023: 
 4024:     return 1;
 4025: }
 4026: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
 4027: 
 4028: sub hash_extract {
 4029:     my ($str)=@_;
 4030:     my %hash;
 4031:     foreach my $pair (split(/\&/,$str)) {
 4032: 	my ($key,$value)=split(/=/,$pair);
 4033: 	$hash{$key}=$value;
 4034:     }
 4035:     return (%hash);
 4036: }
 4037: sub hash_to_str {
 4038:     my ($hash_ref)=@_;
 4039:     my $str;
 4040:     foreach my $key (keys(%$hash_ref)) {
 4041: 	$str.=$key.'='.$hash_ref->{$key}.'&';
 4042:     }
 4043:     $str=~s/\&$//;
 4044:     return $str;
 4045: }
 4046: 
 4047: #
 4048: #  Dump out all versions of a resource that has key=value pairs associated
 4049: # with it for each version.  These resources are built up via the store
 4050: # command.
 4051: #
 4052: #  Parameters:
 4053: #     $cmd               - Command keyword.
 4054: #     $tail              - Remainder of the request which consists of:
 4055: #                          domain/user   - User and auth. domain.
 4056: #                          namespace     - name of resource database.
 4057: #                          rid           - Resource id.
 4058: #    $client             - socket open on the client.
 4059: #
 4060: # Returns:
 4061: #      1  indicating the caller should not yet exit.
 4062: # Side-effects:
 4063: #   Writes a reply to the client.
 4064: #   The reply is a string of the following shape:
 4065: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
 4066: #    Where the 1 above represents version 1.
 4067: #    this continues for all pairs of keys in all versions.
 4068: #
 4069: #
 4070: #    
 4071: #
 4072: sub restore_handler {
 4073:     my ($cmd, $tail, $client) = @_;
 4074: 
 4075:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
 4076:     my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
 4077:     $namespace=~s/\//\_/g;
 4078:     $namespace = &LONCAPA::clean_username($namespace);
 4079: 
 4080:     chomp($rid);
 4081:     my $qresult='';
 4082:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
 4083:     if ($hashref) {
 4084: 	my $version=$hashref->{"version:$rid"};
 4085: 	$qresult.="version=$version&";
 4086: 	my $scope;
 4087: 	for ($scope=1;$scope<=$version;$scope++) {
 4088: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
 4089: 	    my @keys=split(/:/,$vkeys);
 4090: 	    my $key;
 4091: 	    $qresult.="$scope:keys=$vkeys&";
 4092: 	    foreach $key (@keys) {
 4093: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
 4094: 	    }                                  
 4095: 	}
 4096: 	if (&untie_user_hash($hashref)) {
 4097: 	    $qresult=~s/\&$//;
 4098: 	    &Reply( $client, \$qresult, $userinput);
 4099: 	} else {
 4100: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4101: 		    "while attempting restore\n", $userinput);
 4102: 	}
 4103:     } else {
 4104: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 4105: 		"while attempting restore\n", $userinput);
 4106:     }
 4107:   
 4108:     return 1;
 4109: 
 4110: 
 4111: }
 4112: &register_handler("restore", \&restore_handler, 0,1,0);
 4113: 
 4114: #
 4115: #   Add a chat message to a synchronous discussion board.
 4116: #
 4117: # Parameters:
 4118: #    $cmd                - Request keyword.
 4119: #    $tail               - Tail of the command. A colon separated list
 4120: #                          containing:
 4121: #                          cdom    - Domain on which the chat board lives
 4122: #                          cnum    - Course containing the chat board.
 4123: #                          newpost - Body of the posting.
 4124: #                          group   - Optional group, if chat board is only 
 4125: #                                    accessible in a group within the course 
 4126: #   $client              - Socket open on the client.
 4127: # Returns:
 4128: #   1    - Indicating caller should keep on processing.
 4129: #
 4130: # Side-effects:
 4131: #   writes a reply to the client.
 4132: #
 4133: #
 4134: sub send_chat_handler {
 4135:     my ($cmd, $tail, $client) = @_;
 4136: 
 4137:     
 4138:     my $userinput = "$cmd:$tail";
 4139: 
 4140:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
 4141:     &chat_add($cdom,$cnum,$newpost,$group);
 4142:     &Reply($client, "ok\n", $userinput);
 4143: 
 4144:     return 1;
 4145: }
 4146: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
 4147: 
 4148: #
 4149: #   Retrieve the set of chat messages from a discussion board.
 4150: #
 4151: #  Parameters:
 4152: #    $cmd             - Command keyword that initiated the request.
 4153: #    $tail            - Remainder of the request after the command
 4154: #                       keyword.  In this case a colon separated list of
 4155: #                       chat domain    - Which discussion board.
 4156: #                       chat id        - Discussion thread(?)
 4157: #                       domain/user    - Authentication domain and username
 4158: #                                        of the requesting person.
 4159: #                       group          - Optional course group containing
 4160: #                                        the board.      
 4161: #   $client           - Socket open on the client program.
 4162: # Returns:
 4163: #    1     - continue processing
 4164: # Side effects:
 4165: #    Response is written to the client.
 4166: #
 4167: sub retrieve_chat_handler {
 4168:     my ($cmd, $tail, $client) = @_;
 4169: 
 4170: 
 4171:     my $userinput = "$cmd:$tail";
 4172: 
 4173:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
 4174:     my $reply='';
 4175:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
 4176: 	$reply.=&escape($_).':';
 4177:     }
 4178:     $reply=~s/\:$//;
 4179:     &Reply($client, \$reply, $userinput);
 4180: 
 4181: 
 4182:     return 1;
 4183: }
 4184: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
 4185: 
 4186: #
 4187: #  Initiate a query of an sql database.  SQL query repsonses get put in
 4188: #  a file for later retrieval.  This prevents sql query results from
 4189: #  bottlenecking the system.  Note that with loncnew, perhaps this is
 4190: #  less of an issue since multiple outstanding requests can be concurrently
 4191: #  serviced.
 4192: #
 4193: #  Parameters:
 4194: #     $cmd       - Command keyword that initiated the request.
 4195: #     $tail      - Remainder of the command after the keyword.
 4196: #                  For this function, this consists of a query and
 4197: #                  3 arguments that are self-documentingly labelled
 4198: #                  in the original arg1, arg2, arg3.
 4199: #     $client    - Socket open on the client.
 4200: # Return:
 4201: #    1   - Indicating processing should continue.
 4202: # Side-effects:
 4203: #    a reply is written to $client.
 4204: #
 4205: sub send_query_handler {
 4206:     my ($cmd, $tail, $client) = @_;
 4207: 
 4208:     my $userinput = "$cmd:$tail";
 4209: 
 4210:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
 4211:     $query=~s/\n*$//g;
 4212:     if (($query eq 'usersearch') || ($query eq 'instdirsearch')) {
 4213:         my $usersearchconf = &get_usersearch_config($currentdomainid,'directorysrch');
 4214:         my $earlyout;
 4215:         if (ref($usersearchconf) eq 'HASH') {
 4216:             if ($currentdomainid eq $clienthomedom) {
 4217:                 if ($query eq 'usersearch') {
 4218:                     if ($usersearchconf->{'lcavailable'} eq '0') {
 4219:                         $earlyout = 1;
 4220:                     }
 4221:                 } else {
 4222:                     if ($usersearchconf->{'available'} eq '0') {
 4223:                         $earlyout = 1;
 4224:                     }
 4225:                 }
 4226:             } else {
 4227:                 if ($query eq 'usersearch') {
 4228:                     if ($usersearchconf->{'lclocalonly'}) {
 4229:                         $earlyout = 1;
 4230:                     }
 4231:                 } else {
 4232:                     if ($usersearchconf->{'localonly'}) {
 4233:                         $earlyout = 1;
 4234:                     }
 4235:                 }
 4236:             }
 4237:         }
 4238:         if ($earlyout) {
 4239:             &Reply($client, "query_not_authorized\n");
 4240:             return 1;
 4241:         }
 4242:     }
 4243:     &Reply($client, "". &sql_reply("$clientname\&$query".
 4244: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
 4245: 	  $userinput);
 4246:     
 4247:     return 1;
 4248: }
 4249: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
 4250: 
 4251: #
 4252: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
 4253: #   The query is submitted via a "querysend" transaction.
 4254: #   There it is passed on to the lonsql daemon, queued and issued to
 4255: #   mysql.
 4256: #     This transaction is invoked when the sql transaction is complete
 4257: #   it stores the query results in flie and indicates query completion.
 4258: #   presumably local software then fetches this response... I'm guessing
 4259: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
 4260: #   lonsql on completion of the query interacts with the lond of our
 4261: #   client to do a query reply storing two files:
 4262: #    - id     - The results of the query.
 4263: #    - id.end - Indicating the transaction completed. 
 4264: #    NOTE: id is a unique id assigned to the query and querysend time.
 4265: # Parameters:
 4266: #    $cmd        - Command keyword that initiated this request.
 4267: #    $tail       - Remainder of the tail.  In this case that's a colon
 4268: #                  separated list containing the query Id and the 
 4269: #                  results of the query.
 4270: #    $client     - Socket open on the client.
 4271: # Return:
 4272: #    1           - Indicating that we should continue processing.
 4273: # Side effects:
 4274: #    ok written to the client.
 4275: #
 4276: sub reply_query_handler {
 4277:     my ($cmd, $tail, $client) = @_;
 4278: 
 4279: 
 4280:     my $userinput = "$cmd:$tail";
 4281: 
 4282:     my ($id,$reply)=split(/:/,$tail); 
 4283:     my $store;
 4284:     my $execdir=$perlvar{'lonDaemons'};
 4285:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
 4286: 	$reply=~s/\&/\n/g;
 4287: 	print $store $reply;
 4288: 	close $store;
 4289: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
 4290: 	print $store2 "done\n";
 4291: 	close $store2;
 4292: 	&Reply($client, "ok\n", $userinput);
 4293:     } else {
 4294: 	&Failure($client, "error: ".($!+0)
 4295: 		." IO::File->new Failed ".
 4296: 		"while attempting queryreply\n", $userinput);
 4297:     }
 4298:  
 4299: 
 4300:     return 1;
 4301: }
 4302: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
 4303: 
 4304: #
 4305: #  Process the courseidput request.  Not quite sure what this means
 4306: #  at the system level sense.  It appears a gdbm file in the 
 4307: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
 4308: #  a set of entries made in that database.
 4309: #
 4310: # Parameters:
 4311: #   $cmd      - The command keyword that initiated this request.
 4312: #   $tail     - Tail of the command.  In this case consists of a colon
 4313: #               separated list contaning the domain to apply this to and
 4314: #               an ampersand separated list of keyword=value pairs.
 4315: #               Each value is a colon separated list that includes:  
 4316: #               description, institutional code and course owner.
 4317: #               For backward compatibility with versions included
 4318: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
 4319: #               code and/or course owner are preserved from the existing 
 4320: #               record when writing a new record in response to 1.1 or 
 4321: #               1.2 implementations of lonnet::flushcourselogs().   
 4322: #                      
 4323: #   $client   - Socket open on the client.
 4324: # Returns:
 4325: #   1    - indicating that processing should continue
 4326: #
 4327: # Side effects:
 4328: #   reply is written to the client.
 4329: #
 4330: sub put_course_id_handler {
 4331:     my ($cmd, $tail, $client) = @_;
 4332: 
 4333: 
 4334:     my $userinput = "$cmd:$tail";
 4335: 
 4336:     my ($udom, $what) = split(/:/, $tail,2);
 4337:     chomp($what);
 4338:     my $now=time;
 4339:     my @pairs=split(/\&/,$what);
 4340: 
 4341:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 4342:     if ($hashref) {
 4343: 	foreach my $pair (@pairs) {
 4344:             my ($key,$courseinfo) = split(/=/,$pair,2);
 4345:             $courseinfo =~ s/=/:/g;
 4346:             if (defined($hashref->{$key})) {
 4347:                 my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
 4348:                 if (ref($value) eq 'HASH') {
 4349:                     my @items = ('description','inst_code','owner','type');
 4350:                     my @new_items = split(/:/,$courseinfo,-1);
 4351:                     my %storehash; 
 4352:                     for (my $i=0; $i<@new_items; $i++) {
 4353:                         $storehash{$items[$i]} = &unescape($new_items[$i]);
 4354:                     }
 4355:                     $hashref->{$key} = 
 4356:                         &Apache::lonnet::freeze_escape(\%storehash);
 4357:                     my $unesc_key = &unescape($key);
 4358:                     $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
 4359:                     next;
 4360:                 }
 4361:             }
 4362:             my @current_items = split(/:/,$hashref->{$key},-1);
 4363:             shift(@current_items); # remove description
 4364:             pop(@current_items);   # remove last access
 4365:             my $numcurrent = scalar(@current_items);
 4366:             if ($numcurrent > 3) {
 4367:                 $numcurrent = 3;
 4368:             }
 4369:             my @new_items = split(/:/,$courseinfo,-1);
 4370:             my $numnew = scalar(@new_items);
 4371:             if ($numcurrent > 0) {
 4372:                 if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2 
 4373:                     for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
 4374:                         $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
 4375:                     }
 4376:                 }
 4377:             }
 4378:             $hashref->{$key}=$courseinfo.':'.$now;
 4379: 	}
 4380: 	if (&untie_domain_hash($hashref)) {
 4381: 	    &Reply( $client, "ok\n", $userinput);
 4382: 	} else {
 4383: 	    &Failure($client, "error: ".($!+0)
 4384: 		     ." untie(GDBM) Failed ".
 4385: 		     "while attempting courseidput\n", $userinput);
 4386: 	}
 4387:     } else {
 4388: 	&Failure($client, "error: ".($!+0)
 4389: 		 ." tie(GDBM) Failed ".
 4390: 		 "while attempting courseidput\n", $userinput);
 4391:     }
 4392: 
 4393:     return 1;
 4394: }
 4395: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
 4396: 
 4397: sub put_course_id_hash_handler {
 4398:     my ($cmd, $tail, $client) = @_;
 4399:     my $userinput = "$cmd:$tail";
 4400:     my ($udom,$mode,$what) = split(/:/, $tail,3);
 4401:     chomp($what);
 4402:     my $now=time;
 4403:     my @pairs=split(/\&/,$what);
 4404:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 4405:     if ($hashref) {
 4406:         foreach my $pair (@pairs) {
 4407:             my ($key,$value)=split(/=/,$pair);
 4408:             my $unesc_key = &unescape($key);
 4409:             if ($mode ne 'timeonly') {
 4410:                 if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
 4411:                     my $curritems = &Apache::lonnet::thaw_unescape($key); 
 4412:                     if (ref($curritems) ne 'HASH') {
 4413:                         my @current_items = split(/:/,$hashref->{$key},-1);
 4414:                         my $lasttime = pop(@current_items);
 4415:                         $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
 4416:                     } else {
 4417:                         $hashref->{&escape('lasttime:'.$unesc_key)} = '';
 4418:                     }
 4419:                 } 
 4420:                 $hashref->{$key} = $value;
 4421:             }
 4422:             if ($mode ne 'notime') {
 4423:                 $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
 4424:             }
 4425:         }
 4426:         if (&untie_domain_hash($hashref)) {
 4427:             &Reply($client, "ok\n", $userinput);
 4428:         } else {
 4429:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4430:                      "while attempting courseidputhash\n", $userinput);
 4431:         }
 4432:     } else {
 4433:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 4434:                   "while attempting courseidputhash\n", $userinput);
 4435:     }
 4436:     return 1;
 4437: }
 4438: &register_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
 4439: 
 4440: #  Retrieves the value of a course id resource keyword pattern
 4441: #  defined since a starting date.  Both the starting date and the
 4442: #  keyword pattern are optional.  If the starting date is not supplied it
 4443: #  is treated as the beginning of time.  If the pattern is not found,
 4444: #  it is treatred as "." matching everything.
 4445: #
 4446: #  Parameters:
 4447: #     $cmd     - Command keyword that resulted in us being dispatched.
 4448: #     $tail    - The remainder of the command that, in this case, consists
 4449: #                of a colon separated list of:
 4450: #                 domain   - The domain in which the course database is 
 4451: #                            defined.
 4452: #                 since    - Optional parameter describing the minimum
 4453: #                            time of definition(?) of the resources that
 4454: #                            will match the dump.
 4455: #                 description - regular expression that is used to filter
 4456: #                            the dump.  Only keywords matching this regexp
 4457: #                            will be used.
 4458: #                 institutional code - optional supplied code to filter 
 4459: #                            the dump. Only courses with an institutional code 
 4460: #                            that match the supplied code will be returned.
 4461: #                 owner    - optional supplied username and domain of owner to
 4462: #                            filter the dump.  Only courses for which the course
 4463: #                            owner matches the supplied username and/or domain
 4464: #                            will be returned. Pre-2.2.0 legacy entries from 
 4465: #                            nohist_courseiddump will only contain usernames.
 4466: #                 type     - optional parameter for selection 
 4467: #                 regexp_ok - if 1 or -1 allow the supplied institutional code
 4468: #                            filter to behave as a regular expression:
 4469: #	                      1 will not exclude the course if the instcode matches the RE 
 4470: #                            -1 will exclude the course if the instcode matches the RE
 4471: #                 rtn_as_hash - whether to return the information available for
 4472: #                            each matched item as a frozen hash of all 
 4473: #                            key, value pairs in the item's hash, or as a 
 4474: #                            colon-separated list of (in order) description,
 4475: #                            institutional code, and course owner.
 4476: #                 selfenrollonly - filter by courses allowing self-enrollment  
 4477: #                                  now or in the future (selfenrollonly = 1).
 4478: #                 catfilter - filter by course category, assigned to a course 
 4479: #                             using manually defined categories (i.e., not
 4480: #                             self-cataloging based on on institutional code).   
 4481: #                 showhidden - include course in results even if course  
 4482: #                              was set to be excluded from course catalog (DC only).
 4483: #                 caller -  if set to 'coursecatalog', courses set to be hidden
 4484: #                           from course catalog will be excluded from results (unless
 4485: #                           overridden by "showhidden".
 4486: #                 cloner - escaped username:domain of course cloner (if picking course to
 4487: #                          clone).
 4488: #                 cc_clone_list - escaped comma separated list of courses for which 
 4489: #                                 course cloner has active CC role (and so can clone
 4490: #                                 automatically).
 4491: #                 cloneonly - filter by courses for which cloner has rights to clone.
 4492: #                 createdbefore - include courses for which creation date preceeded this date.
 4493: #                 createdafter - include courses for which creation date followed this date.
 4494: #                 creationcontext - include courses created in specified context 
 4495: #
 4496: #                 domcloner - flag to indicate if user can create CCs in course's domain.
 4497: #                             If so, ability to clone course is automatic.
 4498: #                 hasuniquecode - filter by courses for which a six character unique code has 
 4499: #                                 been set.
 4500: #
 4501: #     $client  - The socket open on the client.
 4502: # Returns:
 4503: #    1     - Continue processing.
 4504: # Side Effects:
 4505: #   a reply is written to $client.
 4506: sub dump_course_id_handler {
 4507:     my ($cmd, $tail, $client) = @_;
 4508: 
 4509:     my $res = LONCAPA::Lond::dump_course_id_handler($tail);
 4510:     if ($res =~ /^error:/) {
 4511:         Failure($client, \$res, "$cmd:$tail");
 4512:     } else {
 4513:         Reply($client, \$res, "$cmd:$tail");
 4514:     }
 4515: 
 4516:     return 1;  
 4517: 
 4518:     #TODO remove
 4519:     my $userinput = "$cmd:$tail";
 4520: 
 4521:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
 4522:         $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
 4523:         $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
 4524:         $creationcontext,$domcloner,$hasuniquecode) =split(/:/,$tail);
 4525:     my $now = time;
 4526:     my ($cloneruname,$clonerudom,%cc_clone);
 4527:     if (defined($description)) {
 4528: 	$description=&unescape($description);
 4529:     } else {
 4530: 	$description='.';
 4531:     }
 4532:     if (defined($instcodefilter)) {
 4533:         $instcodefilter=&unescape($instcodefilter);
 4534:     } else {
 4535:         $instcodefilter='.';
 4536:     }
 4537:     my ($ownerunamefilter,$ownerdomfilter);
 4538:     if (defined($ownerfilter)) {
 4539:         $ownerfilter=&unescape($ownerfilter);
 4540:         if ($ownerfilter ne '.' && defined($ownerfilter)) {
 4541:             if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
 4542:                  $ownerunamefilter = $1;
 4543:                  $ownerdomfilter = $2;
 4544:             } else {
 4545:                 $ownerunamefilter = $ownerfilter;
 4546:                 $ownerdomfilter = '';
 4547:             }
 4548:         }
 4549:     } else {
 4550:         $ownerfilter='.';
 4551:     }
 4552: 
 4553:     if (defined($coursefilter)) {
 4554:         $coursefilter=&unescape($coursefilter);
 4555:     } else {
 4556:         $coursefilter='.';
 4557:     }
 4558:     if (defined($typefilter)) {
 4559:         $typefilter=&unescape($typefilter);
 4560:     } else {
 4561:         $typefilter='.';
 4562:     }
 4563:     if (defined($regexp_ok)) {
 4564:         $regexp_ok=&unescape($regexp_ok);
 4565:     }
 4566:     if (defined($catfilter)) {
 4567:         $catfilter=&unescape($catfilter);
 4568:     }
 4569:     if (defined($cloner)) {
 4570:         $cloner = &unescape($cloner);
 4571:         ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/); 
 4572:     }
 4573:     if (defined($cc_clone_list)) {
 4574:         $cc_clone_list = &unescape($cc_clone_list);
 4575:         my @cc_cloners = split('&',$cc_clone_list);
 4576:         foreach my $cid (@cc_cloners) {
 4577:             my ($clonedom,$clonenum) = split(':',$cid);
 4578:             next if ($clonedom ne $udom); 
 4579:             $cc_clone{$clonedom.'_'.$clonenum} = 1;
 4580:         } 
 4581:     }
 4582:     if ($createdbefore ne '') {
 4583:         $createdbefore = &unescape($createdbefore);
 4584:     } else {
 4585:        $createdbefore = 0;
 4586:     }
 4587:     if ($createdafter ne '') {
 4588:         $createdafter = &unescape($createdafter);
 4589:     } else {
 4590:         $createdafter = 0;
 4591:     }
 4592:     if ($creationcontext ne '') {
 4593:         $creationcontext = &unescape($creationcontext);
 4594:     } else {
 4595:         $creationcontext = '.';
 4596:     }
 4597:     unless ($hasuniquecode) {
 4598:         $hasuniquecode = '.';
 4599:     }
 4600:     my $unpack = 1;
 4601:     if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' && 
 4602:         $typefilter eq '.') {
 4603:         $unpack = 0;
 4604:     }
 4605:     if (!defined($since)) { $since=0; }
 4606:     my $qresult='';
 4607:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 4608:     if ($hashref) {
 4609: 	while (my ($key,$value) = each(%$hashref)) {
 4610:             my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
 4611:                 %unesc_val,$selfenroll_end,$selfenroll_types,$created,
 4612:                 $context);
 4613:             $unesc_key = &unescape($key);
 4614:             if ($unesc_key =~ /^lasttime:/) {
 4615:                 next;
 4616:             } else {
 4617:                 $lasttime_key = &escape('lasttime:'.$unesc_key);
 4618:             }
 4619:             if ($hashref->{$lasttime_key} ne '') {
 4620:                 $lasttime = $hashref->{$lasttime_key};
 4621:                 next if ($lasttime<$since);
 4622:             }
 4623:             my ($canclone,$valchange);
 4624:             my $items = &Apache::lonnet::thaw_unescape($value);
 4625:             if (ref($items) eq 'HASH') {
 4626:                 if ($hashref->{$lasttime_key} eq '') {
 4627:                     next if ($since > 1);
 4628:                 }
 4629:                 $is_hash =  1;
 4630:                 if ($domcloner) {
 4631:                     $canclone = 1;
 4632:                 } elsif (defined($clonerudom)) {
 4633:                     if ($items->{'cloners'}) {
 4634:                         my @cloneable = split(',',$items->{'cloners'});
 4635:                         if (@cloneable) {
 4636:                             if (grep(/^\*$/,@cloneable))  {
 4637:                                 $canclone = 1;
 4638:                             } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
 4639:                                 $canclone = 1;
 4640:                             } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
 4641:                                 $canclone = 1;
 4642:                             }
 4643:                         }
 4644:                         unless ($canclone) {
 4645:                             if ($cloneruname ne '' && $clonerudom ne '') {
 4646:                                 if ($cc_clone{$unesc_key}) {
 4647:                                     $canclone = 1;
 4648:                                     $items->{'cloners'} .= ','.$cloneruname.':'.
 4649:                                                            $clonerudom;
 4650:                                     $valchange = 1;
 4651:                                 }
 4652:                             }
 4653:                         }
 4654:                     } elsif (defined($cloneruname)) {
 4655:                         if ($cc_clone{$unesc_key}) {
 4656:                             $canclone = 1;
 4657:                             $items->{'cloners'} = $cloneruname.':'.$clonerudom;
 4658:                             $valchange = 1;
 4659:                         }
 4660:                         unless ($canclone) {
 4661:                             if ($items->{'owner'} =~ /:/) {
 4662:                                 if ($items->{'owner'} eq $cloner) {
 4663:                                     $canclone = 1;
 4664:                                 }
 4665:                             } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
 4666:                                 $canclone = 1;
 4667:                             }
 4668:                             if ($canclone) {
 4669:                                 $items->{'cloners'} = $cloneruname.':'.$clonerudom;
 4670:                                 $valchange = 1;
 4671:                             }
 4672:                         }
 4673:                     }
 4674:                 }
 4675:                 if ($unpack || !$rtn_as_hash) {
 4676:                     $unesc_val{'descr'} = $items->{'description'};
 4677:                     $unesc_val{'inst_code'} = $items->{'inst_code'};
 4678:                     $unesc_val{'owner'} = $items->{'owner'};
 4679:                     $unesc_val{'type'} = $items->{'type'};
 4680:                     $unesc_val{'cloners'} = $items->{'cloners'};
 4681:                     $unesc_val{'created'} = $items->{'created'};
 4682:                     $unesc_val{'context'} = $items->{'context'};
 4683:                 }
 4684:                 $selfenroll_types = $items->{'selfenroll_types'};
 4685:                 $selfenroll_end = $items->{'selfenroll_end_date'};
 4686:                 $created = $items->{'created'};
 4687:                 $context = $items->{'context'};
 4688:                 if ($hasuniquecode ne '.') {
 4689:                     next unless ($items->{'uniquecode'});
 4690:                 }
 4691:                 if ($selfenrollonly) {
 4692:                     next if (!$selfenroll_types);
 4693:                     if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
 4694:                         next;
 4695:                     }
 4696:                 }
 4697:                 if ($creationcontext ne '.') {
 4698:                     next if (($context ne '') && ($context ne $creationcontext));  
 4699:                 }
 4700:                 if ($createdbefore > 0) {
 4701:                     next if (($created eq '') || ($created > $createdbefore));   
 4702:                 }
 4703:                 if ($createdafter > 0) {
 4704:                     next if (($created eq '') || ($created <= $createdafter)); 
 4705:                 }
 4706:                 if ($catfilter ne '') {
 4707:                     next if ($items->{'categories'} eq '');
 4708:                     my @categories = split('&',$items->{'categories'}); 
 4709:                     next if (@categories == 0);
 4710:                     my @subcats = split('&',$catfilter);
 4711:                     my $matchcat = 0;
 4712:                     foreach my $cat (@categories) {
 4713:                         if (grep(/^\Q$cat\E$/,@subcats)) {
 4714:                             $matchcat = 1;
 4715:                             last;
 4716:                         }
 4717:                     }
 4718:                     next if (!$matchcat);
 4719:                 }
 4720:                 if ($caller eq 'coursecatalog') {
 4721:                     if ($items->{'hidefromcat'} eq 'yes') {
 4722:                         next if !$showhidden;
 4723:                     }
 4724:                 }
 4725:             } else {
 4726:                 next if ($catfilter ne '');
 4727:                 next if ($selfenrollonly);
 4728:                 next if ($createdbefore || $createdafter);
 4729:                 next if ($creationcontext ne '.');
 4730:                 if ((defined($clonerudom)) && (defined($cloneruname)))  {
 4731:                     if ($cc_clone{$unesc_key}) {
 4732:                         $canclone = 1;
 4733:                         $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
 4734:                     }
 4735:                 }
 4736:                 $is_hash =  0;
 4737:                 my @courseitems = split(/:/,$value);
 4738:                 $lasttime = pop(@courseitems);
 4739:                 if ($hashref->{$lasttime_key} eq '') {
 4740:                     next if ($lasttime<$since);
 4741:                 }
 4742: 	        ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
 4743:             }
 4744:             if ($cloneonly) {
 4745:                next unless ($canclone);
 4746:             }
 4747:             my $match = 1;
 4748: 	    if ($description ne '.') {
 4749:                 if (!$is_hash) {
 4750:                     $unesc_val{'descr'} = &unescape($val{'descr'});
 4751:                 }
 4752:                 if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
 4753:                     $match = 0;
 4754:                 }
 4755:             }
 4756:             if ($instcodefilter ne '.') {
 4757:                 if (!$is_hash) {
 4758:                     $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
 4759:                 }
 4760:                 if ($regexp_ok == 1) {
 4761:                     if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
 4762:                         $match = 0;
 4763:                     }
 4764:                 } elsif ($regexp_ok == -1) {
 4765:                     if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
 4766:                         $match = 0;
 4767:                     }
 4768:                 } else {
 4769:                     if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
 4770:                         $match = 0;
 4771:                     }
 4772:                 }
 4773: 	    }
 4774:             if ($ownerfilter ne '.') {
 4775:                 if (!$is_hash) {
 4776:                     $unesc_val{'owner'} = &unescape($val{'owner'});
 4777:                 }
 4778:                 if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
 4779:                     if ($unesc_val{'owner'} =~ /:/) {
 4780:                         if (eval{$unesc_val{'owner'} !~ 
 4781:                              /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
 4782:                             $match = 0;
 4783:                         } 
 4784:                     } else {
 4785:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
 4786:                             $match = 0;
 4787:                         }
 4788:                     }
 4789:                 } elsif ($ownerunamefilter ne '') {
 4790:                     if ($unesc_val{'owner'} =~ /:/) {
 4791:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
 4792:                              $match = 0;
 4793:                         }
 4794:                     } else {
 4795:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
 4796:                             $match = 0;
 4797:                         }
 4798:                     }
 4799:                 } elsif ($ownerdomfilter ne '') {
 4800:                     if ($unesc_val{'owner'} =~ /:/) {
 4801:                         if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
 4802:                              $match = 0;
 4803:                         }
 4804:                     } else {
 4805:                         if ($ownerdomfilter ne $udom) {
 4806:                             $match = 0;
 4807:                         }
 4808:                     }
 4809:                 }
 4810:             }
 4811:             if ($coursefilter ne '.') {
 4812:                 if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
 4813:                     $match = 0;
 4814:                 }
 4815:             }
 4816:             if ($typefilter ne '.') {
 4817:                 if (!$is_hash) {
 4818:                     $unesc_val{'type'} = &unescape($val{'type'});
 4819:                 }
 4820:                 if ($unesc_val{'type'} eq '') {
 4821:                     if ($typefilter ne 'Course') {
 4822:                         $match = 0;
 4823:                     }
 4824:                 } else {
 4825:                     if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
 4826:                         $match = 0;
 4827:                     }
 4828:                 }
 4829:             }
 4830:             if ($match == 1) {
 4831:                 if ($rtn_as_hash) {
 4832:                     if ($is_hash) {
 4833:                         if ($valchange) {
 4834:                             my $newvalue = &Apache::lonnet::freeze_escape($items);
 4835:                             $qresult.=$key.'='.$newvalue.'&';
 4836:                         } else {
 4837:                             $qresult.=$key.'='.$value.'&';
 4838:                         }
 4839:                     } else {
 4840:                         my %rtnhash = ( 'description' => &unescape($val{'descr'}),
 4841:                                         'inst_code' => &unescape($val{'inst_code'}),
 4842:                                         'owner'     => &unescape($val{'owner'}),
 4843:                                         'type'      => &unescape($val{'type'}),
 4844:                                         'cloners'   => &unescape($val{'cloners'}),
 4845:                                       );
 4846:                         my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
 4847:                         $qresult.=$key.'='.$items.'&';
 4848:                     }
 4849:                 } else {
 4850:                     if ($is_hash) {
 4851:                         $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
 4852:                                     &escape($unesc_val{'inst_code'}).':'.
 4853:                                     &escape($unesc_val{'owner'}).'&';
 4854:                     } else {
 4855:                         $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
 4856:                                     ':'.$val{'owner'}.'&';
 4857:                     }
 4858:                 }
 4859:             }
 4860: 	}
 4861: 	if (&untie_domain_hash($hashref)) {
 4862: 	    chop($qresult);
 4863: 	    &Reply($client, \$qresult, $userinput);
 4864: 	} else {
 4865: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4866: 		    "while attempting courseiddump\n", $userinput);
 4867: 	}
 4868:     } else {
 4869: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 4870: 		"while attempting courseiddump\n", $userinput);
 4871:     }
 4872:     return 1;
 4873: }
 4874: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
 4875: 
 4876: sub course_lastaccess_handler {
 4877:     my ($cmd, $tail, $client) = @_;
 4878:     my $userinput = "$cmd:$tail";
 4879:     my ($cdom,$cnum) = split(':',$tail); 
 4880:     my (%lastaccess,$qresult);
 4881:     my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
 4882:     if ($hashref) {
 4883:         while (my ($key,$value) = each(%$hashref)) {
 4884:             my ($unesc_key,$lasttime);
 4885:             $unesc_key = &unescape($key);
 4886:             if ($cnum) {
 4887:                 next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
 4888:             }
 4889:             if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
 4890:                 $lastaccess{$1} = $value;
 4891:             } else {
 4892:                 my $items = &Apache::lonnet::thaw_unescape($value);
 4893:                 if (ref($items) eq 'HASH') {
 4894:                     unless ($lastaccess{$unesc_key}) {
 4895:                         $lastaccess{$unesc_key} = '';
 4896:                     }
 4897:                 } else {
 4898:                     my @courseitems = split(':',$value);
 4899:                     $lastaccess{$unesc_key} = pop(@courseitems);
 4900:                 }
 4901:             }
 4902:         }
 4903:         foreach my $cid (sort(keys(%lastaccess))) {
 4904:             $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&'; 
 4905:         }
 4906:         if (&untie_domain_hash($hashref)) {
 4907:             if ($qresult) {
 4908:                 chop($qresult);
 4909:             }
 4910:             &Reply($client, \$qresult, $userinput);
 4911:         } else {
 4912:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4913:                     "while attempting lastacourseaccess\n", $userinput);
 4914:         }
 4915:     } else {
 4916:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 4917:                 "while attempting lastcourseaccess\n", $userinput);
 4918:     }
 4919:     return 1;
 4920: }
 4921: &register_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
 4922: 
 4923: sub course_sessions_handler {
 4924:     my ($cmd, $tail, $client) = @_;
 4925:     my $userinput = "$cmd:$tail";
 4926:     my ($cdom,$cnum,$lastactivity) = split(':',$tail);
 4927:     my $dbsuffix = '_'.$cdom.'_'.$cnum.'.db';
 4928:     my (%sessions,$qresult);
 4929:     my $now=time;
 4930:     if (opendir(DIR,$perlvar{'lonIDsDir'})) {
 4931:         my $filename;
 4932:         while ($filename=readdir(DIR)) {
 4933:             next if ($filename=~/^\./);
 4934:             next if ($filename=~/^publicuser_/);
 4935:             next if ($filename=~/^[a-f0-9]+_(linked|lti_\d+)\.id$/);
 4936:             if ($filename =~ /^($LONCAPA::match_username)_\d+_($LONCAPA::match_domain)_/) {
 4937:                 my ($uname,$udom) = ($1,$2);
 4938:                 next unless (-e "$perlvar{'lonDaemons'}/tmp/$uname$dbsuffix");
 4939:                 my $mtime = (stat("$perlvar{'lonIDsDir'}/$filename"))[9];
 4940:                 if ($lastactivity < 0) {
 4941:                     next if ($mtime-$now > $lastactivity);
 4942:                 } else {
 4943:                     next if ($now-$mtime > $lastactivity);
 4944:                 }
 4945:                 $sessions{$uname.':'.$udom} = $mtime;
 4946:             }
 4947:         }
 4948:         closedir(DIR); 
 4949:     }
 4950:     foreach my $user (keys(%sessions)) {
 4951:         $qresult.=&escape($user).'='.$sessions{$user}.'&';
 4952:     }
 4953:     if ($qresult) {
 4954:         chop($qresult);
 4955:     }
 4956:     &Reply($client, \$qresult, $userinput);
 4957:     return 1;
 4958: }
 4959: &register_handler("coursesessions",\&course_sessions_handler, 0, 1, 0);
 4960: 
 4961: #
 4962: # Puts an unencrypted entry in a namespace db file at the domain level 
 4963: #
 4964: # Parameters:
 4965: #    $cmd      - The command that got us here.
 4966: #    $tail     - Tail of the command (remaining parameters).
 4967: #    $client   - File descriptor connected to client.
 4968: # Returns
 4969: #     0        - Requested to exit, caller should shut down.
 4970: #     1        - Continue processing.
 4971: #  Side effects:
 4972: #     reply is written to $client.
 4973: #
 4974: sub put_domain_handler {
 4975:     my ($cmd,$tail,$client) = @_;
 4976: 
 4977:     my $userinput = "$cmd:$tail";
 4978: 
 4979:     my ($udom,$namespace,$what) =split(/:/,$tail,3);
 4980:     chomp($what);
 4981:     my @pairs=split(/\&/,$what);
 4982:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
 4983:                                    "P", $what);
 4984:     if ($hashref) {
 4985:         foreach my $pair (@pairs) {
 4986:             my ($key,$value)=split(/=/,$pair);
 4987:             $hashref->{$key}=$value;
 4988:         }
 4989:         if (&untie_domain_hash($hashref)) {
 4990:             &Reply($client, "ok\n", $userinput);
 4991:         } else {
 4992:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4993:                      "while attempting putdom\n", $userinput);
 4994:         }
 4995:     } else {
 4996:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 4997:                   "while attempting putdom\n", $userinput);
 4998:     }
 4999: 
 5000:     return 1;
 5001: }
 5002: &register_handler("putdom", \&put_domain_handler, 0, 1, 0);
 5003: 
 5004: # Updates one or more entries in clickers.db file at the domain level
 5005: #
 5006: # Parameters:
 5007: #    $cmd      - The command that got us here.
 5008: #    $tail     - Tail of the command (remaining parameters).
 5009: #                In this case a colon separated list containing:
 5010: #                (a) the domain for which we are updating the entries,
 5011: #                (b) the action required -- add or del -- and
 5012: #                (c) a &-separated list of entries to add or delete.
 5013: #    $client   - File descriptor connected to client.
 5014: # Returns
 5015: #     1        - Continue processing.
 5016: #     0        - Requested to exit, caller should shut down.
 5017: #  Side effects:
 5018: #     reply is written to $client.
 5019: #
 5020: 
 5021: 
 5022: sub update_clickers {
 5023:     my ($cmd, $tail, $client)  = @_;
 5024: 
 5025:     my $userinput = "$cmd:$tail";
 5026:     my ($udom,$action,$what) =split(/:/,$tail,3);
 5027:     chomp($what);
 5028: 
 5029:     my $hashref = &tie_domain_hash($udom, "clickers", &GDBM_WRCREAT(),
 5030:                                  "U","$action:$what");
 5031: 
 5032:     if (!$hashref) {
 5033:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 5034:                   "while attempting updateclickers\n", $userinput);
 5035:         return 1;
 5036:     }
 5037: 
 5038:     my @pairs=split(/\&/,$what);
 5039:     foreach my $pair (@pairs) {
 5040:         my ($key,$value)=split(/=/,$pair);
 5041:         if ($action eq 'add') {
 5042:             if (exists($hashref->{$key})) {
 5043:                 my @newvals = split(/,/,&unescape($value));
 5044:                 my @currvals = split(/,/,&unescape($hashref->{$key}));
 5045:                 my @merged = sort(keys(%{{map { $_ => 1 } (@newvals,@currvals)}}));
 5046:                 $hashref->{$key}=&escape(join(',',@merged));
 5047:             } else {
 5048:                 $hashref->{$key}=$value;
 5049:             }
 5050:         } elsif ($action eq 'del') {
 5051:             if (exists($hashref->{$key})) {
 5052:                 my %current;
 5053:                 map { $current{$_} = 1; } split(/,/,&unescape($hashref->{$key}));
 5054:                 map { delete($current{$_}); } split(/,/,&unescape($value));
 5055:                 if (keys(%current)) {
 5056:                     $hashref->{$key}=&escape(join(',',sort(keys(%current))));
 5057:                 } else {
 5058:                     delete($hashref->{$key});
 5059:                 }
 5060:             }
 5061:         }
 5062:     }
 5063:     if (&untie_user_hash($hashref)) {
 5064:         &Reply( $client, "ok\n", $userinput);
 5065:     } else {
 5066:         &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 5067:                  "while attempting put\n",
 5068:                  $userinput);
 5069:     }
 5070:     return 1;
 5071: }
 5072: &register_handler("updateclickers", \&update_clickers, 0, 1, 0);
 5073: 
 5074: 
 5075: # Deletes one or more entries in a namespace db file at the domain level
 5076: #
 5077: # Parameters:
 5078: #    $cmd      - The command that got us here.
 5079: #    $tail     - Tail of the command (remaining parameters).
 5080: #                In this case a colon separated list containing:
 5081: #                (a) the domain for which we are deleting the entries,
 5082: #                (b) &-separated list of keys to delete.  
 5083: #    $client   - File descriptor connected to client.
 5084: # Returns
 5085: #     1        - Continue processing.
 5086: #     0        - Requested to exit, caller should shut down.
 5087: #  Side effects:
 5088: #     reply is written to $client.
 5089: #
 5090: 
 5091: sub del_domain_handler {
 5092:     my ($cmd,$tail,$client) = @_;
 5093: 
 5094:     my $userinput = "$cmd:$tail";
 5095: 
 5096:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
 5097:     chomp($what);
 5098:     my $hashref = &tie_domain_hash($udom,$namespace,&GDBM_WRCREAT(),
 5099:                                    "D", $what);
 5100:     if ($hashref) {
 5101:         my @keys=split(/\&/,$what);
 5102:         foreach my $key (@keys) {
 5103:             delete($hashref->{$key});
 5104:         }
 5105:         if (&untie_user_hash($hashref)) {
 5106:             &Reply($client, "ok\n", $userinput);
 5107:         } else {
 5108:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5109:                     "while attempting deldom\n", $userinput);
 5110:         }
 5111:     } else {
 5112:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 5113:                  "while attempting deldom\n", $userinput);
 5114:     }
 5115:     return 1;
 5116: }
 5117: &register_handler("deldom", \&del_domain_handler, 0, 1, 0);
 5118: 
 5119: 
 5120: # Unencrypted get from the namespace database file at the domain level.
 5121: # This function retrieves a keyed item from a specific named database in the
 5122: # domain directory.
 5123: #
 5124: # Parameters:
 5125: #   $cmd             - Command request keyword (getdom).
 5126: #   $tail            - Tail of the command.  This is a colon separated list
 5127: #                      consisting of the domain and the 'namespace' 
 5128: #                      which selects the gdbm file to do the lookup in,
 5129: #                      & separated list of keys to lookup.  Note that
 5130: #                      the values are returned as an & separated list too.
 5131: #   $client          - File descriptor open on the client.
 5132: # Returns:
 5133: #   1       - Continue processing.
 5134: #   0       - Exit.
 5135: #  Side effects:
 5136: #     reply is written to $client.
 5137: #
 5138: 
 5139: sub get_domain_handler {
 5140:     my ($cmd, $tail, $client) = @_;
 5141: 
 5142:     my $userinput = "$cmd:$tail";
 5143: 
 5144:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
 5145:     if (($namespace =~ /^enc/) || ($namespace eq 'private')) {
 5146:         &Failure( $client, "refused\n", $userinput);
 5147:     } else {
 5148:         my $res = LONCAPA::Lond::get_dom($userinput);
 5149:         if ($res =~ /^error:/) {
 5150:             &Failure($client, \$res, $userinput);
 5151:         } else {
 5152:             &Reply($client, \$res, $userinput);
 5153:         }
 5154:     }
 5155: 
 5156:     return 1;
 5157: }
 5158: &register_handler("getdom", \&get_domain_handler, 0, 1, 0);
 5159: 
 5160: #
 5161: # Encrypted get from the namespace database file at the domain level.
 5162: # This function retrieves a keyed item from a specific named database in the
 5163: # domain directory.
 5164: #
 5165: # Parameters:
 5166: #   $cmd             - Command request keyword (egetdom).
 5167: #   $tail            - Tail of the command.  This is a colon separated list
 5168: #                      consisting of the domain and the 'namespace'
 5169: #                      which selects the gdbm file to do the lookup in,
 5170: #                      & separated list of keys to lookup.  Note that
 5171: #                      the values are returned as an & separated list too.
 5172: #   $client          - File descriptor open on the client.
 5173: # Returns:
 5174: #   1       - Continue processing.
 5175: #   0       - Exit.
 5176: #  Side effects:
 5177: #     reply is encrypted before being written to $client.
 5178: #
 5179: sub encrypted_get_domain_handler {
 5180:     my ($cmd, $tail, $client) = @_;
 5181: 
 5182:     my $userinput = "$cmd:$tail";
 5183: 
 5184:     my ($udom,$namespace,$what) = split(/:/,$tail,3);
 5185:     if ($namespace eq 'private') {
 5186:         &Failure( $client, "refused\n", $userinput);
 5187:     } else {
 5188:         my $res = LONCAPA::Lond::get_dom($userinput);
 5189:         if ($res =~ /^error:/) {
 5190:             &Failure($client, \$res, $userinput);
 5191:         } else {
 5192:             if ($cipher) {
 5193:                 my $cmdlength=length($res);
 5194:                 $res.="         ";
 5195:                 my $encres='';
 5196:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 5197:                     $encres.= unpack("H16",
 5198:                                      $cipher->encrypt(substr($res,
 5199:                                                              $encidx,
 5200:                                                              8)));
 5201:                 }
 5202:                 &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
 5203:             } else {
 5204:                 &Failure( $client, "error:no_key\n",$userinput);
 5205:             }
 5206:         }
 5207:     }
 5208:     return 1;
 5209: }
 5210: &register_handler("egetdom", \&encrypted_get_domain_handler, 1, 1, 0);
 5211: 
 5212: #
 5213: # Encrypted get from the namespace database file at the domain level.
 5214: # This function retrieves a keyed item from a specific named database in the
 5215: # domain directory.
 5216: #
 5217: # Parameters:
 5218: #   $cmd             - Command request keyword (lti).
 5219: #   $tail            - Tail of the command.  This is a colon-separated list
 5220: #                      consisting of the domain, coursenum, if for LTI-
 5221: #                      enabled deep-linking to course content using
 5222: #                      link protection configured within a course,
 5223: #                      context (=deeplink) if for LTI-enabled deep-linking
 5224: #                      to course content using LTI Provider settings
 5225: #                      configured within a course's domain, the (escaped)
 5226: #                      launch URL, the (escaped) method (typically POST),
 5227: #                      and a frozen hash of the LTI launch parameters
 5228: #                      from the LTI payload.
 5229: #   $client          - File descriptor open on the client.
 5230: # Returns:
 5231: #   1       - Continue processing.
 5232: #   0       - Exit.
 5233: #  Side effects:
 5234: #     The reply will contain an LTI itemID, if the signed LTI payload
 5235: #     could be verified using the consumer key and the shared secret 
 5236: #     available for that key (for the itemID) for either the course or domain, 
 5237: #     depending on values for cnum and context. The reply is encrypted before 
 5238: #     being written to $client.
 5239: #
 5240: sub lti_handler {
 5241:     my ($cmd, $tail, $client) = @_;
 5242: 
 5243:     my $userinput = "$cmd:$tail";
 5244: 
 5245:     my ($cdom,$cnum,$context,$escurl,$escmethod,$items) = split(/:/,$tail);
 5246:     my $url = &unescape($escurl);
 5247:     my $method = &unescape($escmethod);
 5248:     my $params = &Apache::lonnet::thaw_unescape($items);
 5249:     my $res;
 5250:     if ($cnum ne '') {
 5251:         $res = &LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
 5252:     } else {
 5253:         $res = &LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
 5254:     }
 5255:     if ($res =~ /^error:/) {
 5256:         &Failure($client, \$res, $userinput);
 5257:     } else {
 5258:         if ($cipher) {
 5259:             my $cmdlength=length($res);
 5260:             $res.="         ";
 5261:             my $encres='';
 5262:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 5263:                 $encres.= unpack("H16",
 5264:                                  $cipher->encrypt(substr($res,
 5265:                                                          $encidx,
 5266:                                                          8)));
 5267:             }
 5268:             &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
 5269:         } else {
 5270:             &Failure( $client, "error:no_key\n",$userinput);
 5271:         }
 5272:     }
 5273:     return 1;
 5274: }
 5275: &register_handler("lti", \&lti_handler, 1, 1, 0);
 5276: 
 5277: #
 5278: #  Puts an id to a domains id database. 
 5279: #
 5280: #  Parameters:
 5281: #   $cmd     - The command that triggered us.
 5282: #   $tail    - Remainder of the request other than the command. This is a 
 5283: #              colon separated list containing:
 5284: #              $domain  - The domain for which we are writing the id.
 5285: #              $pairs  - The id info to write... this is and & separated list
 5286: #                        of keyword=value.
 5287: #   $client  - Socket open on the client.
 5288: #  Returns:
 5289: #    1   - Continue processing.
 5290: #  Side effects:
 5291: #     reply is written to $client.
 5292: #
 5293: sub put_id_handler {
 5294:     my ($cmd,$tail,$client) = @_;
 5295: 
 5296: 
 5297:     my $userinput = "$cmd:$tail";
 5298: 
 5299:     my ($udom,$what)=split(/:/,$tail);
 5300:     chomp($what);
 5301:     my @pairs=split(/\&/,$what);
 5302:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
 5303: 				   "P", $what);
 5304:     if ($hashref) {
 5305: 	foreach my $pair (@pairs) {
 5306: 	    my ($key,$value)=split(/=/,$pair);
 5307: 	    $hashref->{$key}=$value;
 5308: 	}
 5309: 	if (&untie_domain_hash($hashref)) {
 5310: 	    &Reply($client, "ok\n", $userinput);
 5311: 	} else {
 5312: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5313: 		     "while attempting idput\n", $userinput);
 5314: 	}
 5315:     } else {
 5316: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 5317: 		  "while attempting idput\n", $userinput);
 5318:     }
 5319: 
 5320:     return 1;
 5321: }
 5322: &register_handler("idput", \&put_id_handler, 0, 1, 0);
 5323: 
 5324: #
 5325: #  Retrieves a set of id values from the id database.
 5326: #  Returns an & separated list of results, one for each requested id to the
 5327: #  client.
 5328: #
 5329: # Parameters:
 5330: #   $cmd       - Command keyword that caused us to be dispatched.
 5331: #   $tail      - Tail of the command.  Consists of a colon separated:
 5332: #               domain - the domain whose id table we dump
 5333: #               ids      Consists of an & separated list of
 5334: #                        id keywords whose values will be fetched.
 5335: #                        nonexisting keywords will have an empty value.
 5336: #   $client    - Socket open on the client.
 5337: #
 5338: # Returns:
 5339: #    1 - indicating processing should continue.
 5340: # Side effects:
 5341: #   An & separated list of results is written to $client.
 5342: #
 5343: sub get_id_handler {
 5344:     my ($cmd, $tail, $client) = @_;
 5345: 
 5346:     
 5347:     my $userinput = "$client:$tail";
 5348:     
 5349:     my ($udom,$what)=split(/:/,$tail);
 5350:     chomp($what);
 5351:     my @queries=split(/\&/,$what);
 5352:     my $qresult='';
 5353:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
 5354:     if ($hashref) {
 5355: 	for (my $i=0;$i<=$#queries;$i++) {
 5356: 	    $qresult.="$hashref->{$queries[$i]}&";
 5357: 	}
 5358: 	if (&untie_domain_hash($hashref)) {
 5359: 	    $qresult=~s/\&$//;
 5360: 	    &Reply($client, \$qresult, $userinput);
 5361: 	} else {
 5362: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 5363: 		      "while attempting idget\n",$userinput);
 5364: 	}
 5365:     } else {
 5366: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 5367: 		 "while attempting idget\n",$userinput);
 5368:     }
 5369:     
 5370:     return 1;
 5371: }
 5372: &register_handler("idget", \&get_id_handler, 0, 1, 0);
 5373: 
 5374: #   Deletes one or more ids in a domain's id database.
 5375: #
 5376: #   Parameters:
 5377: #       $cmd                  - Command keyword (iddel).
 5378: #       $tail                 - Command tail.  In this case a colon
 5379: #                               separated list containing:
 5380: #                               The domain for which we are deleting the id(s).
 5381: #                               &-separated list of id(s) to delete.
 5382: #       $client               - File open on client socket.
 5383: # Returns:
 5384: #     1   - Continue processing
 5385: #     0   - Exit server.
 5386: #     
 5387: #
 5388: 
 5389: sub del_id_handler {
 5390:     my ($cmd,$tail,$client) = @_;
 5391: 
 5392:     my $userinput = "$cmd:$tail";
 5393: 
 5394:     my ($udom,$what)=split(/:/,$tail);
 5395:     chomp($what);
 5396:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
 5397:                                    "D", $what);
 5398:     if ($hashref) {
 5399:         my @keys=split(/\&/,$what);
 5400:         foreach my $key (@keys) {
 5401:             delete($hashref->{$key});
 5402:         }
 5403:         if (&untie_user_hash($hashref)) {
 5404:             &Reply($client, "ok\n", $userinput);
 5405:         } else {
 5406:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5407:                     "while attempting iddel\n", $userinput);
 5408:         }
 5409:     } else {
 5410:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 5411:                  "while attempting iddel\n", $userinput);
 5412:     }
 5413:     return 1;
 5414: }
 5415: &register_handler("iddel", \&del_id_handler, 0, 1, 0);
 5416: 
 5417: #
 5418: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
 5419: #
 5420: # Parameters
 5421: #   $cmd       - Command keyword that caused us to be dispatched.
 5422: #   $tail      - Tail of the command.  Consists of a colon separated:
 5423: #               domain - the domain whose dcmail we are recording
 5424: #               email    Consists of key=value pair 
 5425: #                        where key is unique msgid
 5426: #                        and value is message (in XML)
 5427: #   $client    - Socket open on the client.
 5428: #
 5429: # Returns:
 5430: #    1 - indicating processing should continue.
 5431: # Side effects
 5432: #     reply is written to $client.
 5433: #
 5434: sub put_dcmail_handler {
 5435:     my ($cmd,$tail,$client) = @_;
 5436:     my $userinput = "$cmd:$tail";
 5437: 
 5438: 
 5439:     my ($udom,$what)=split(/:/,$tail);
 5440:     chomp($what);
 5441:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
 5442:     if ($hashref) {
 5443:         my ($key,$value)=split(/=/,$what);
 5444:         $hashref->{$key}=$value;
 5445:     }
 5446:     if (&untie_domain_hash($hashref)) {
 5447:         &Reply($client, "ok\n", $userinput);
 5448:     } else {
 5449:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5450:                  "while attempting dcmailput\n", $userinput);
 5451:     }
 5452:     return 1;
 5453: }
 5454: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
 5455: 
 5456: #
 5457: # Retrieves broadcast e-mail from nohist_dcmail database
 5458: # Returns to client an & separated list of key=value pairs,
 5459: # where key is msgid and value is message information.
 5460: #
 5461: # Parameters
 5462: #   $cmd       - Command keyword that caused us to be dispatched.
 5463: #   $tail      - Tail of the command.  Consists of a colon separated:
 5464: #               domain - the domain whose dcmail table we dump
 5465: #               startfilter - beginning of time window 
 5466: #               endfilter - end of time window
 5467: #               sendersfilter - & separated list of username:domain 
 5468: #                 for senders to search for.
 5469: #   $client    - Socket open on the client.
 5470: #
 5471: # Returns:
 5472: #    1 - indicating processing should continue.
 5473: # Side effects
 5474: #     reply (& separated list of msgid=messageinfo pairs) is 
 5475: #     written to $client.
 5476: #
 5477: sub dump_dcmail_handler {
 5478:     my ($cmd, $tail, $client) = @_;
 5479:                                                                                 
 5480:     my $userinput = "$cmd:$tail";
 5481:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
 5482:     chomp($sendersfilter);
 5483:     my @senders = ();
 5484:     if (defined($startfilter)) {
 5485:         $startfilter=&unescape($startfilter);
 5486:     } else {
 5487:         $startfilter='.';
 5488:     }
 5489:     if (defined($endfilter)) {
 5490:         $endfilter=&unescape($endfilter);
 5491:     } else {
 5492:         $endfilter='.';
 5493:     }
 5494:     if (defined($sendersfilter)) {
 5495:         $sendersfilter=&unescape($sendersfilter);
 5496: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
 5497:     }
 5498: 
 5499:     my $qresult='';
 5500:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
 5501:     if ($hashref) {
 5502:         while (my ($key,$value) = each(%$hashref)) {
 5503:             my $match = 1;
 5504:             my ($timestamp,$subj,$uname,$udom) = 
 5505: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
 5506:             $subj = &unescape($subj);
 5507:             unless ($startfilter eq '.' || !defined($startfilter)) {
 5508:                 if ($timestamp < $startfilter) {
 5509:                     $match = 0;
 5510:                 }
 5511:             }
 5512:             unless ($endfilter eq '.' || !defined($endfilter)) {
 5513:                 if ($timestamp > $endfilter) {
 5514:                     $match = 0;
 5515:                 }
 5516:             }
 5517:             unless (@senders < 1) {
 5518:                 unless (grep/^$uname:$udom$/,@senders) {
 5519:                     $match = 0;
 5520:                 }
 5521:             }
 5522:             if ($match == 1) {
 5523:                 $qresult.=$key.'='.$value.'&';
 5524:             }
 5525:         }
 5526:         if (&untie_domain_hash($hashref)) {
 5527:             chop($qresult);
 5528:             &Reply($client, \$qresult, $userinput);
 5529:         } else {
 5530:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5531:                     "while attempting dcmaildump\n", $userinput);
 5532:         }
 5533:     } else {
 5534:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 5535:                 "while attempting dcmaildump\n", $userinput);
 5536:     }
 5537:     return 1;
 5538: }
 5539: 
 5540: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
 5541: 
 5542: #
 5543: # Puts domain roles in nohist_domainroles database
 5544: #
 5545: # Parameters
 5546: #   $cmd       - Command keyword that caused us to be dispatched.
 5547: #   $tail      - Tail of the command.  Consists of a colon separated:
 5548: #               domain - the domain whose roles we are recording  
 5549: #               role -   Consists of key=value pair
 5550: #                        where key is unique role
 5551: #                        and value is start/end date information
 5552: #   $client    - Socket open on the client.
 5553: #
 5554: # Returns:
 5555: #    1 - indicating processing should continue.
 5556: # Side effects
 5557: #     reply is written to $client.
 5558: #
 5559: 
 5560: sub put_domainroles_handler {
 5561:     my ($cmd,$tail,$client) = @_;
 5562: 
 5563:     my $userinput = "$cmd:$tail";
 5564:     my ($udom,$what)=split(/:/,$tail);
 5565:     chomp($what);
 5566:     my @pairs=split(/\&/,$what);
 5567:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
 5568:     if ($hashref) {
 5569:         foreach my $pair (@pairs) {
 5570:             my ($key,$value)=split(/=/,$pair);
 5571:             $hashref->{$key}=$value;
 5572:         }
 5573:         if (&untie_domain_hash($hashref)) {
 5574:             &Reply($client, "ok\n", $userinput);
 5575:         } else {
 5576:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5577:                      "while attempting domroleput\n", $userinput);
 5578:         }
 5579:     } else {
 5580:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 5581:                   "while attempting domroleput\n", $userinput);
 5582:     }
 5583:                                                                                   
 5584:     return 1;
 5585: }
 5586: 
 5587: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
 5588: 
 5589: #
 5590: # Retrieves domain roles from nohist_domainroles database
 5591: # Returns to client an & separated list of key=value pairs,
 5592: # where key is role and value is start and end date information.
 5593: #
 5594: # Parameters
 5595: #   $cmd       - Command keyword that caused us to be dispatched.
 5596: #   $tail      - Tail of the command.  Consists of a colon separated:
 5597: #               domain - the domain whose domain roles table we dump
 5598: #   $client    - Socket open on the client.
 5599: #
 5600: # Returns:
 5601: #    1 - indicating processing should continue.
 5602: # Side effects
 5603: #     reply (& separated list of role=start/end info pairs) is
 5604: #     written to $client.
 5605: #
 5606: sub dump_domainroles_handler {
 5607:     my ($cmd, $tail, $client) = @_;
 5608:                                                                                            
 5609:     my $userinput = "$cmd:$tail";
 5610:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
 5611:     chomp($rolesfilter);
 5612:     my @roles = ();
 5613:     if (defined($startfilter)) {
 5614:         $startfilter=&unescape($startfilter);
 5615:     } else {
 5616:         $startfilter='.';
 5617:     }
 5618:     if (defined($endfilter)) {
 5619:         $endfilter=&unescape($endfilter);
 5620:     } else {
 5621:         $endfilter='.';
 5622:     }
 5623:     if (defined($rolesfilter)) {
 5624:         $rolesfilter=&unescape($rolesfilter);
 5625: 	@roles = split(/\&/,$rolesfilter);
 5626:     }
 5627: 
 5628:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
 5629:     if ($hashref) {
 5630:         my $qresult = '';
 5631:         while (my ($key,$value) = each(%$hashref)) {
 5632:             my $match = 1;
 5633:             my ($end,$start) = split(/:/,&unescape($value));
 5634:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
 5635:             unless (@roles < 1) {
 5636:                 unless (grep/^\Q$trole\E$/,@roles) {
 5637:                     $match = 0;
 5638:                     next;
 5639:                 }
 5640:             }
 5641:             unless ($startfilter eq '.' || !defined($startfilter)) {
 5642:                 if ((defined($start)) && ($start >= $startfilter)) {
 5643:                     $match = 0;
 5644:                     next;
 5645:                 }
 5646:             }
 5647:             unless ($endfilter eq '.' || !defined($endfilter)) {
 5648:                 if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
 5649:                     $match = 0;
 5650:                     next;
 5651:                 }
 5652:             }
 5653:             if ($match == 1) {
 5654:                 $qresult.=$key.'='.$value.'&';
 5655:             }
 5656:         }
 5657:         if (&untie_domain_hash($hashref)) {
 5658:             chop($qresult);
 5659:             &Reply($client, \$qresult, $userinput);
 5660:         } else {
 5661:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5662:                     "while attempting domrolesdump\n", $userinput);
 5663:         }
 5664:     } else {
 5665:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 5666:                 "while attempting domrolesdump\n", $userinput);
 5667:     }
 5668:     return 1;
 5669: }
 5670: 
 5671: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
 5672: 
 5673: 
 5674: #  Process the tmpput command I'm not sure what this does.. Seems to
 5675: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
 5676: # where Id is the client's ip concatenated with a sequence number.
 5677: # The file will contain some value that is passed in.  Is this e.g.
 5678: # a login token?
 5679: #
 5680: # Parameters:
 5681: #    $cmd     - The command that got us dispatched.
 5682: #    $tail    - The remainder of the request following $cmd:
 5683: #               In this case this will be the contents of the file.
 5684: #    $client  - Socket connected to the client.
 5685: # Returns:
 5686: #    1 indicating processing can continue.
 5687: # Side effects:
 5688: #   A file is created in the local filesystem.
 5689: #   A reply is sent to the client.
 5690: sub tmp_put_handler {
 5691:     my ($cmd, $what, $client) = @_;
 5692: 
 5693:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
 5694: 
 5695:     my ($record,$context) = split(/:/,$what);
 5696:     if ($context ne '') {
 5697:         chomp($context);
 5698:         $context = &unescape($context);
 5699:     }
 5700:     my ($id,$store);
 5701:     $tmpsnum++;
 5702:     my $numtries = 0;
 5703:     my $execdir=$perlvar{'lonDaemons'};
 5704:     if (($context eq 'resetpw') || ($context eq 'createaccount') ||
 5705:         ($context eq 'sso') || ($context eq 'link') || ($context eq 'retry')) {
 5706:         $id = &md5_hex(&md5_hex(time.{}.rand().$$.$tmpsnum));
 5707:         while ((-e "$execdir/tmp/$id.tmp") && ($numtries <10)) {
 5708:             undef($id);
 5709:             $id = &md5_hex(&md5_hex(time.{}.rand().$$.$tmpsnum));
 5710:             $numtries ++;
 5711:         }
 5712:     } else {
 5713:         $id = $$.'_'.$clientip.'_'.$tmpsnum;
 5714:     }
 5715:     $id=~s/\W/\_/g;
 5716:     $record=~s/\n//g;
 5717:     if (($id ne '') &&
 5718:         ($store=IO::File->new(">$execdir/tmp/$id.tmp"))) {
 5719: 	print $store $record;
 5720: 	close $store;
 5721: 	&Reply($client, \$id, $userinput);
 5722:     } else {
 5723: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
 5724: 		  "while attempting tmpput\n", $userinput);
 5725:     }
 5726:     return 1;
 5727:   
 5728: }
 5729: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
 5730: 
 5731: #   Processes the tmpget command.  This command returns the contents
 5732: #  of a temporary resource file(?) created via tmpput.
 5733: #
 5734: # Paramters:
 5735: #    $cmd      - Command that got us dispatched.
 5736: #    $id       - Tail of the command, contain the id of the resource
 5737: #                we want to fetch.
 5738: #    $client   - socket open on the client.
 5739: # Return:
 5740: #    1         - Inidcating processing can continue.
 5741: # Side effects:
 5742: #   A reply is sent to the client.
 5743: #
 5744: sub tmp_get_handler {
 5745:     my ($cmd, $id, $client) = @_;
 5746: 
 5747:     my $userinput = "$cmd:$id"; 
 5748:     
 5749: 
 5750:     $id=~s/\W/\_/g;
 5751:     my $store;
 5752:     my $execdir=$perlvar{'lonDaemons'};
 5753:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
 5754: 	my $reply=<$store>;
 5755: 	&Reply( $client, \$reply, $userinput);
 5756: 	close $store;
 5757:     } else {
 5758: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
 5759: 		  "while attempting tmpget\n", $userinput);
 5760:     }
 5761: 
 5762:     return 1;
 5763: }
 5764: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
 5765: 
 5766: #
 5767: #  Process the tmpdel command.  This command deletes a temp resource
 5768: #  created by the tmpput command.
 5769: #
 5770: # Parameters:
 5771: #   $cmd      - Command that got us here.
 5772: #   $id       - Id of the temporary resource created.
 5773: #   $client   - socket open on the client process.
 5774: #
 5775: # Returns:
 5776: #   1     - Indicating processing should continue.
 5777: # Side Effects:
 5778: #   A file is deleted
 5779: #   A reply is sent to the client.
 5780: sub tmp_del_handler {
 5781:     my ($cmd, $id, $client) = @_;
 5782:     
 5783:     my $userinput= "$cmd:$id";
 5784:     
 5785:     chomp($id);
 5786:     $id=~s/\W/\_/g;
 5787:     my $execdir=$perlvar{'lonDaemons'};
 5788:     if (unlink("$execdir/tmp/$id.tmp")) {
 5789: 	&Reply($client, "ok\n", $userinput);
 5790:     } else {
 5791: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
 5792: 		  "while attempting tmpdel\n", $userinput);
 5793:     }
 5794:     
 5795:     return 1;
 5796: 
 5797: }
 5798: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
 5799: 
 5800: #
 5801: #  Process the updatebalcookie command.  This command updates a
 5802: #  cookie in the lonBalancedir directory on a load balancer node.
 5803: #
 5804: # Parameters:
 5805: #   $cmd      - Command that got us here.
 5806: #   $tail     - Tail of the request (escaped cookie: escaped current entry)
 5807: #
 5808: #   $client   - socket open on the client process.
 5809: #
 5810: # Returns:
 5811: #   1     - Indicating processing should continue.
 5812: # Side Effects:
 5813: #   A cookie file is updated from the lonBalancedir directory
 5814: #   A reply is sent to the client.
 5815: #
 5816: sub update_balcookie_handler {
 5817:     my ($cmd, $tail, $client) = @_;
 5818: 
 5819:     my $userinput= "$cmd:$tail";
 5820:     chomp($tail);
 5821:     my ($cookie,$lastentry) = map { &unescape($_) } (split(/:/,$tail));
 5822: 
 5823:     my $updatedone;
 5824:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
 5825:         my $execdir=$perlvar{'lonBalanceDir'};
 5826:         if (-e "$execdir/$cookie.id") {
 5827:             my $doupdate;
 5828:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
 5829:                 while (my $line = <$fh>) {
 5830:                     chomp($line);
 5831:                     if ($line eq $lastentry) {
 5832:                         $doupdate = 1;
 5833:                         last;
 5834:                     }
 5835:                 }
 5836:                 close($fh);
 5837:             }
 5838:             if ($doupdate) {
 5839:                 if (open(my $fh,'>',"$execdir/$cookie.id")) {
 5840:                     print $fh $clientname;
 5841:                     close($fh);
 5842:                     $updatedone = 1;
 5843:                 }
 5844:             }
 5845:         }
 5846:     }
 5847:     if ($updatedone) {
 5848:         &Reply($client, "ok\n", $userinput);
 5849:     } else {
 5850:         &Failure( $client, "error: ".($!+0)."file update failed ".
 5851:                   "while attempting updatebalcookie\n", $userinput);
 5852:     }
 5853:     return 1;
 5854: }
 5855: &register_handler("updatebalcookie", \&update_balcookie_handler, 0, 1, 0);
 5856: 
 5857: #
 5858: #  Process the delbalcookie command. This command deletes a balancer
 5859: #  cookie in the lonBalancedir directory on a load balancer node.
 5860: #
 5861: # Parameters:
 5862: #   $cmd      - Command that got us here.
 5863: #   $cookie   - Cookie to be deleted.
 5864: #   $client   - socket open on the client process.
 5865: #
 5866: # Returns:
 5867: #   1     - Indicating processing should continue.
 5868: # Side Effects:
 5869: #   A cookie file is deleted from the lonBalancedir directory
 5870: #   A reply is sent to the client.
 5871: sub del_balcookie_handler {
 5872:     my ($cmd, $cookie, $client) = @_;
 5873: 
 5874:     my $userinput= "$cmd:$cookie";
 5875: 
 5876:     chomp($cookie);
 5877:     $cookie = &unescape($cookie);
 5878:     my $deleted = '';
 5879:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
 5880:         my $execdir=$perlvar{'lonBalanceDir'};
 5881:         if (-e "$execdir/$cookie.id") {
 5882:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
 5883:                 my $dodelete;
 5884:                 while (my $line = <$fh>) {
 5885:                     chomp($line);
 5886:                     if ($line eq $clientname) {
 5887:                         $dodelete = 1;
 5888:                         last;
 5889:                     }
 5890:                 }
 5891:                 close($fh);
 5892:                 if ($dodelete) {
 5893:                     if (unlink("$execdir/$cookie.id")) {
 5894:                         $deleted = 1;
 5895:                     }
 5896:                 }
 5897:             }
 5898:         }
 5899:     }
 5900:     if ($deleted) {
 5901:         &Reply($client, "ok\n", $userinput);
 5902:     } else {
 5903:         &Failure( $client, "error: ".($!+0)."Unlinking cookie file Failed ".
 5904:                   "while attempting delbalcookie\n", $userinput);
 5905:     }
 5906:     return 1;
 5907: }
 5908: &register_handler("delbalcookie", \&del_balcookie_handler, 0, 1, 0);
 5909: 
 5910: #
 5911: #   Processes the setannounce command.  This command
 5912: #   creates a file named announce.txt in the top directory of
 5913: #   the documentn root and sets its contents.  The announce.txt file is
 5914: #   printed in its entirety at the LonCAPA login page.  Note:
 5915: #   once the announcement.txt fileis created it cannot be deleted.
 5916: #   However, setting the contents of the file to empty removes the
 5917: #   announcement from the login page of loncapa so who cares.
 5918: #
 5919: # Parameters:
 5920: #    $cmd          - The command that got us dispatched.
 5921: #    $announcement - The text of the announcement.
 5922: #    $client       - Socket open on the client process.
 5923: # Retunrns:
 5924: #   1             - Indicating request processing should continue
 5925: # Side Effects:
 5926: #   The file {DocRoot}/announcement.txt is created.
 5927: #   A reply is sent to $client.
 5928: #
 5929: sub set_announce_handler {
 5930:     my ($cmd, $announcement, $client) = @_;
 5931:   
 5932:     my $userinput    = "$cmd:$announcement";
 5933: 
 5934:     chomp($announcement);
 5935:     $announcement=&unescape($announcement);
 5936:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
 5937: 				'/announcement.txt')) {
 5938: 	print $store $announcement;
 5939: 	close $store;
 5940: 	&Reply($client, "ok\n", $userinput);
 5941:     } else {
 5942: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
 5943:     }
 5944: 
 5945:     return 1;
 5946: }
 5947: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
 5948: 
 5949: #
 5950: #  Return the version of the daemon.  This can be used to determine
 5951: #  the compatibility of cross version installations or, alternatively to
 5952: #  simply know who's out of date and who isn't.  Note that the version
 5953: #  is returned concatenated with the tail.
 5954: # Parameters:
 5955: #   $cmd        - the request that dispatched to us.
 5956: #   $tail       - Tail of the request (client's version?).
 5957: #   $client     - Socket open on the client.
 5958: #Returns:
 5959: #   1 - continue processing requests.
 5960: # Side Effects:
 5961: #   Replies with version to $client.
 5962: sub get_version_handler {
 5963:     my ($cmd, $tail, $client) = @_;
 5964: 
 5965:     my $userinput  = $cmd.$tail;
 5966:     
 5967:     &Reply($client, &version($userinput)."\n", $userinput);
 5968: 
 5969: 
 5970:     return 1;
 5971: }
 5972: &register_handler("version", \&get_version_handler, 0, 1, 0);
 5973: 
 5974: #  Set the current host and domain.  This is used to support
 5975: #  multihomed systems.  Each IP of the system, or even separate daemons
 5976: #  on the same IP can be treated as handling a separate lonCAPA virtual
 5977: #  machine.  This command selects the virtual lonCAPA.  The client always
 5978: #  knows the right one since it is lonc and it is selecting the domain/system
 5979: #  from the hosts.tab file.
 5980: # Parameters:
 5981: #    $cmd      - Command that dispatched us.
 5982: #    $tail     - Tail of the command (domain/host requested).
 5983: #    $socket   - Socket open on the client.
 5984: #
 5985: # Returns:
 5986: #     1   - Indicates the program should continue to process requests.
 5987: # Side-effects:
 5988: #     The default domain/system context is modified for this daemon.
 5989: #     a reply is sent to the client.
 5990: #
 5991: sub set_virtual_host_handler {
 5992:     my ($cmd, $tail, $socket) = @_;
 5993:   
 5994:     my $userinput  ="$cmd:$tail";
 5995: 
 5996:     &Reply($client, &sethost($userinput)."\n", $userinput);
 5997: 
 5998: 
 5999:     return 1;
 6000: }
 6001: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
 6002: 
 6003: #  Process a request to exit:
 6004: #   - "bye" is sent to the client.
 6005: #   - The client socket is shutdown and closed.
 6006: #   - We indicate to the caller that we should exit.
 6007: # Formal Parameters:
 6008: #   $cmd                - The command that got us here.
 6009: #   $tail               - Tail of the command (empty).
 6010: #   $client             - Socket open on the tail.
 6011: # Returns:
 6012: #   0      - Indicating the program should exit!!
 6013: #
 6014: sub exit_handler {
 6015:     my ($cmd, $tail, $client) = @_;
 6016: 
 6017:     my $userinput = "$cmd:$tail";
 6018: 
 6019:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
 6020:     &Reply($client, "bye\n", $userinput);
 6021:     $client->shutdown(2);        # shutdown the socket forcibly.
 6022:     $client->close();
 6023: 
 6024:     return 0;
 6025: }
 6026: &register_handler("exit", \&exit_handler, 0,1,1);
 6027: &register_handler("init", \&exit_handler, 0,1,1);
 6028: &register_handler("quit", \&exit_handler, 0,1,1);
 6029: 
 6030: #  Determine if auto-enrollment is enabled.
 6031: #  Note that the original had what I believe to be a defect.
 6032: #  The original returned 0 if the requestor was not a registerd client.
 6033: #  It should return "refused".
 6034: # Formal Parameters:
 6035: #   $cmd       - The command that invoked us.
 6036: #   $tail      - The tail of the command (Extra command parameters.
 6037: #   $client    - The socket open on the client that issued the request.
 6038: # Returns:
 6039: #    1         - Indicating processing should continue.
 6040: #
 6041: sub enrollment_enabled_handler {
 6042:     my ($cmd, $tail, $client) = @_;
 6043:     my $userinput = $cmd.":".$tail; # For logging purposes.
 6044: 
 6045:     
 6046:     my ($cdom) = split(/:/, $tail, 2);   # Domain we're asking about.
 6047: 
 6048:     my $outcome  = &localenroll::run($cdom);
 6049:     &Reply($client, \$outcome, $userinput);
 6050: 
 6051:     return 1;
 6052: }
 6053: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
 6054: 
 6055: #
 6056: #   Validate an institutional code used for a LON-CAPA course.          
 6057: #
 6058: # Formal Parameters:
 6059: #   $cmd          - The command request that got us dispatched.
 6060: #   $tail         - The tail of the command.  In this case,
 6061: #                   this is a colon separated set of words that will be split
 6062: #                   into:
 6063: #                        $dom      - The domain for which the check of 
 6064: #                                    institutional course code will occur.
 6065: #
 6066: #                        $instcode - The institutional code for the course
 6067: #                                    being requested, or validated for rights
 6068: #                                    to request.
 6069: #
 6070: #                        $owner    - The course requestor (who will be the
 6071: #                                    course owner, in the form username:domain
 6072: #
 6073: #   $client       - Socket open on the client.
 6074: # Returns:
 6075: #    1           - Indicating processing should continue.
 6076: #
 6077: sub validate_instcode_handler {
 6078:     my ($cmd, $tail, $client) = @_;
 6079:     my $userinput = "$cmd:$tail";
 6080:     my ($dom,$instcode,$owner) = split(/:/, $tail);
 6081:     $instcode = &unescape($instcode);
 6082:     $owner = &unescape($owner);
 6083:     my ($outcome,$description,$credits) = 
 6084:         &localenroll::validate_instcode($dom,$instcode,$owner);
 6085:     my $result = &escape($outcome).'&'.&escape($description).'&'.
 6086:                  &escape($credits);
 6087:     &Reply($client, \$result, $userinput);
 6088: 
 6089:     return 1;
 6090: }
 6091: &register_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
 6092: 
 6093: #
 6094: #  Validate co-owner for cross-listed institutional code and
 6095: #  institutional course code itself used for a LON-CAPA course.
 6096: #
 6097: # Formal Parameters:
 6098: #   $cmd          - The command request that got us dispatched.
 6099: #   $tail         - The tail of the command.  In this case,
 6100: #                   this is a colon separated string containing:
 6101: #      $dom            - Course's LON-CAPA domain
 6102: #      $instcode       - Institutional course code for the course
 6103: #      $inst_xlist     - Institutional course Id for the crosslisting
 6104: #      $coowner        - Username of co-owner
 6105: #      (values for all but $dom have been escaped). 
 6106: #
 6107: #   $client       - Socket open on the client.
 6108: # Returns:
 6109: #    1           - Indicating processing should continue.
 6110: #
 6111: sub validate_instcrosslist_handler  {
 6112:     my ($cmd, $tail, $client) = @_;
 6113:     my $userinput = "$cmd:$tail";
 6114:     my ($dom,$instcode,$inst_xlist,$coowner) = split(/:/,$tail);
 6115:     $instcode = &unescape($instcode);
 6116:     $inst_xlist = &unescape($inst_xlist);
 6117:     $coowner = &unescape($coowner);
 6118:     my $outcome = &localenroll::validate_crosslist_access($dom,$instcode,
 6119:                                                           $inst_xlist,$coowner);
 6120:     &Reply($client, \$outcome, $userinput);
 6121: 
 6122:     return 1;
 6123: }
 6124: &register_handler("autovalidateinstcrosslist", \&validate_instcrosslist_handler, 0, 1, 0);
 6125: 
 6126: #   Get the official sections for which auto-enrollment is possible.
 6127: #   Since the admin people won't know about 'unofficial sections' 
 6128: #   we cannot auto-enroll on them.
 6129: # Formal Parameters:
 6130: #    $cmd     - The command request that got us dispatched here.
 6131: #    $tail    - The remainder of the request.  In our case this
 6132: #               will be split into:
 6133: #               $coursecode   - The course name from the admin point of view.
 6134: #               $cdom         - The course's domain(?).
 6135: #    $client  - Socket open on the client.
 6136: # Returns:
 6137: #    1    - Indiciting processing should continue.
 6138: #
 6139: sub get_sections_handler {
 6140:     my ($cmd, $tail, $client) = @_;
 6141:     my $userinput = "$cmd:$tail";
 6142: 
 6143:     my ($coursecode, $cdom) = split(/:/, $tail);
 6144:     my @secs = &localenroll::get_sections($coursecode,$cdom);
 6145:     my $seclist = &escape(join(':',@secs));
 6146: 
 6147:     &Reply($client, \$seclist, $userinput);
 6148:     
 6149: 
 6150:     return 1;
 6151: }
 6152: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
 6153: 
 6154: #   Validate the owner of a new course section.  
 6155: #
 6156: # Formal Parameters:
 6157: #   $cmd      - Command that got us dispatched.
 6158: #   $tail     - the remainder of the command.  For us this consists of a
 6159: #               colon separated string containing:
 6160: #                  $inst    - Course Id from the institutions point of view.
 6161: #                  $owner   - Proposed owner of the course.
 6162: #                  $cdom    - Domain of the course (from the institutions
 6163: #                             point of view?)..
 6164: #   $client   - Socket open on the client.
 6165: #
 6166: # Returns:
 6167: #   1        - Processing should continue.
 6168: #
 6169: sub validate_course_owner_handler {
 6170:     my ($cmd, $tail, $client)  = @_;
 6171:     my $userinput = "$cmd:$tail";
 6172:     my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
 6173:     
 6174:     $owner = &unescape($owner);
 6175:     $coowners = &unescape($coowners);
 6176:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
 6177:     &Reply($client, \$outcome, $userinput);
 6178: 
 6179: 
 6180: 
 6181:     return 1;
 6182: }
 6183: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
 6184: 
 6185: #
 6186: #   Validate a course section in the official schedule of classes
 6187: #   from the institutions point of view (part of autoenrollment).
 6188: #
 6189: # Formal Parameters:
 6190: #   $cmd          - The command request that got us dispatched.
 6191: #   $tail         - The tail of the command.  In this case,
 6192: #                   this is a colon separated set of words that will be split
 6193: #                   into:
 6194: #                        $inst_course_id - The course/section id from the
 6195: #                                          institutions point of view.
 6196: #                        $cdom           - The domain from the institutions
 6197: #                                          point of view.
 6198: #   $client       - Socket open on the client.
 6199: # Returns:
 6200: #    1           - Indicating processing should continue.
 6201: #
 6202: sub validate_course_section_handler {
 6203:     my ($cmd, $tail, $client) = @_;
 6204:     my $userinput = "$cmd:$tail";
 6205:     my ($inst_course_id, $cdom) = split(/:/, $tail);
 6206: 
 6207:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
 6208:     &Reply($client, \$outcome, $userinput);
 6209: 
 6210: 
 6211:     return 1;
 6212: }
 6213: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
 6214: 
 6215: #
 6216: #   Validate course owner's access to enrollment data for specific class section. 
 6217: #   
 6218: #
 6219: # Formal Parameters:
 6220: #    $cmd     - The command request that got us dispatched.
 6221: #    $tail    - The tail of the command.   In this case this is a colon separated
 6222: #               set of values that will be split into:
 6223: #               $inst_class  - Institutional code for the specific class section   
 6224: #               $ownerlist   - An escaped comma-separated list of username:domain 
 6225: #                              of the course owner, and co-owner(s).
 6226: #               $cdom        - The domain of the course from the institution's
 6227: #                              point of view.
 6228: #    $client  - The socket open on the client.
 6229: # Returns:
 6230: #    1 - continue processing.
 6231: #
 6232: 
 6233: sub validate_class_access_handler {
 6234:     my ($cmd, $tail, $client) = @_;
 6235:     my $userinput = "$cmd:$tail";
 6236:     my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
 6237:     my $owners = &unescape($ownerlist);
 6238:     my $outcome;
 6239:     eval {
 6240: 	local($SIG{__DIE__})='DEFAULT';
 6241: 	$outcome=&localenroll::check_section($inst_class,$owners,$cdom);
 6242:     };
 6243:     &Reply($client,\$outcome, $userinput);
 6244: 
 6245:     return 1;
 6246: }
 6247: &register_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
 6248: 
 6249: #
 6250: #    Modify institutional sections (using customized &instsec_reformat()
 6251: #    routine in localenroll.pm), to either clutter or declutter, for  
 6252: #    purposes of ensuring an institutional course section (string) can
 6253: #    be unambiguously separated into institutional course and section.
 6254: #
 6255: # Formal Parameters:
 6256: #    $cmd     - The command request that got us dispatched.
 6257: #    $tail    - The tail of the command.   In this case this is a colon separated
 6258: #               set of values that will be split into:
 6259: #               $cdom        - The LON-CAPA domain of the course.
 6260: #               $action      - Either: clutter or declutter
 6261: #                              clutter adds character(s) to eliminate ambiguity
 6262: #                              declutter removes the added characters (e.g., for
 6263: #                              display of the institutional course section string.
 6264: #               $info        - A frozen hash in which keys are: 
 6265: #                              LON-CAPA course number:Institutional course code
 6266: #                              and values are a reference to an array of the
 6267: #                              items to modify -- either institutional sections,
 6268: #                              or institutional course sections (for crosslistings). 
 6269: #    $client  - The socket open on the client.
 6270: # Returns:
 6271: #    1 - continue processing.
 6272: #   
 6273: 
 6274: sub instsec_reformat_handler {
 6275:     my ($cmd, $tail, $client) = @_;
 6276:     my $userinput = "$cmd:$tail";
 6277:     my ($cdom,$action,$info) = split(/:/,$tail);
 6278:     my $instsecref = &Apache::lonnet::thaw_unescape($info);
 6279:     my ($outcome,$result);
 6280:     eval {
 6281:         local($SIG{__DIE__})='DEFAULT';
 6282:         $outcome=&localenroll::instsec_reformat($cdom,$action,$instsecref);
 6283:         if ($outcome eq 'ok') {
 6284:             if (ref($instsecref) eq 'HASH') {
 6285:                 foreach my $key (keys(%{$instsecref})) {
 6286:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($instsecref->{$key}).'&';
 6287:                 }
 6288:                 $result =~ s/\&$//;
 6289:             }
 6290:         }
 6291:     };
 6292:     if (!$@) {
 6293:         if ($outcome eq 'ok') {
 6294:             &Reply( $client, \$result, $userinput);
 6295:         } else {
 6296:             &Reply($client,\$outcome, $userinput);
 6297:         }
 6298:     } else {
 6299:         &Failure($client,"unknown_cmd\n",$userinput);
 6300:     }
 6301:     return 1;
 6302: }
 6303: &register_handler("autoinstsecreformat",\&instsec_reformat_handler, 0, 1, 0);
 6304: 
 6305: #
 6306: #   Validate course owner or co-owners(s) access to enrollment data for all sections
 6307: #   and crosslistings for a particular course.
 6308: #
 6309: #
 6310: # Formal Parameters:
 6311: #    $cmd     - The command request that got us dispatched.
 6312: #    $tail    - The tail of the command.   In this case this is a colon separated
 6313: #               set of values that will be split into:
 6314: #               $ownerlist   - An escaped comma-separated list of username:domain
 6315: #                              of the course owner, and co-owner(s).
 6316: #               $cdom        - The domain of the course from the institution's
 6317: #                              point of view.
 6318: #               $classes     - Frozen hash of institutional course sections and
 6319: #                              crosslistings.
 6320: #    $client  - The socket open on the client.
 6321: # Returns:
 6322: #    1 - continue processing.
 6323: #
 6324: 
 6325: sub validate_classes_handler {
 6326:     my ($cmd, $tail, $client) = @_;
 6327:     my $userinput = "$cmd:$tail";
 6328:     my ($ownerlist,$cdom,$classes) = split(/:/, $tail);
 6329:     my $classesref = &Apache::lonnet::thaw_unescape($classes);
 6330:     my $owners = &unescape($ownerlist);
 6331:     my $result;
 6332:     eval {
 6333:         local($SIG{__DIE__})='DEFAULT';
 6334:         my %validations;
 6335:         my $response = &localenroll::check_instclasses($owners,$cdom,$classesref,
 6336:                                                        \%validations);
 6337:         if ($response eq 'ok') {
 6338:             foreach my $key (keys(%validations)) {
 6339:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
 6340:             }
 6341:             $result =~ s/\&$//;
 6342:         } else {
 6343:             $result = 'error';
 6344:         }
 6345:     };
 6346:     if (!$@) {
 6347:         &Reply($client, \$result, $userinput);
 6348:     } else {
 6349:         &Failure($client,"unknown_cmd\n",$userinput);
 6350:     }
 6351:     return 1;
 6352: }
 6353: &register_handler("autovalidateinstclasses", \&validate_classes_handler, 0, 1, 0);
 6354: 
 6355: #
 6356: #   Create a password for a new LON-CAPA user added by auto-enrollment.
 6357: #   Only used for case where authentication method for new user is localauth
 6358: #
 6359: # Formal Parameters:
 6360: #    $cmd     - The command request that got us dispatched.
 6361: #    $tail    - The tail of the command.   In this case this is a colon separated
 6362: #               set of words that will be split into:
 6363: #               $authparam - An authentication parameter (localauth parameter).
 6364: #               $cdom      - The domain of the course from the institution's
 6365: #                            point of view.
 6366: #    $client  - The socket open on the client.
 6367: # Returns:
 6368: #    1 - continue processing.
 6369: #
 6370: sub create_auto_enroll_password_handler {
 6371:     my ($cmd, $tail, $client) = @_;
 6372:     my $userinput = "$cmd:$tail";
 6373: 
 6374:     my ($authparam, $cdom) = split(/:/, $userinput);
 6375: 
 6376:     my ($create_passwd,$authchk);
 6377:     ($authparam,
 6378:      $create_passwd,
 6379:      $authchk) = &localenroll::create_password($authparam,$cdom);
 6380: 
 6381:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
 6382: 	   $userinput);
 6383: 
 6384: 
 6385:     return 1;
 6386: }
 6387: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
 6388: 		  0, 1, 0);
 6389: 
 6390: sub auto_export_grades_handler {
 6391:     my ($cmd, $tail, $client) = @_;
 6392:     my $userinput = "$cmd:$tail";
 6393:     my ($cdom,$cnum,$info,$data) = split(/:/,$tail);
 6394:     my $inforef = &Apache::lonnet::thaw_unescape($info);
 6395:     my $dataref = &Apache::lonnet::thaw_unescape($data);
 6396:     my ($outcome,$result);;
 6397:     eval {
 6398:         local($SIG{__DIE__})='DEFAULT';
 6399:         my %rtnhash;
 6400:         $outcome=&localenroll::export_grades($cdom,$cnum,$inforef,$dataref,\%rtnhash);
 6401:         if ($outcome eq 'ok') {
 6402:             foreach my $key (keys(%rtnhash)) {
 6403:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
 6404:             }
 6405:             $result =~ s/\&$//;
 6406:         }
 6407:     };
 6408:     if (!$@) {
 6409:         if ($outcome eq 'ok') {
 6410:             if ($cipher) {
 6411:                 my $cmdlength=length($result);
 6412:                 $result.="         ";
 6413:                 my $encresult='';
 6414:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 6415:                     $encresult.= unpack("H16",
 6416:                                         $cipher->encrypt(substr($result,
 6417:                                                                 $encidx,
 6418:                                                                 8)));
 6419:                 }
 6420:                 &Reply( $client, "enc:$cmdlength:$encresult\n", $userinput);
 6421:             } else {
 6422:                 &Failure( $client, "error:no_key\n", $userinput);
 6423:             }
 6424:         } else {
 6425:             &Reply($client, "$outcome\n", $userinput);
 6426:         }
 6427:     } else {
 6428:         &Failure($client,"export_error\n",$userinput);
 6429:     }
 6430:     return 1;
 6431: }
 6432: &register_handler("autoexportgrades", \&auto_export_grades_handler,
 6433:                   1, 1, 0);
 6434: 
 6435: #   Retrieve and remove temporary files created by/during autoenrollment.
 6436: #
 6437: # Formal Parameters:
 6438: #    $cmd      - The command that got us dispatched.
 6439: #    $tail     - The tail of the command.  In our case this is a colon 
 6440: #                separated list that will be split into:
 6441: #                $filename - The name of the file to retrieve.
 6442: #                            The filename is given as a path relative to
 6443: #                            the LonCAPA temp file directory.
 6444: #    $client   - Socket open on the client.
 6445: #
 6446: # Returns:
 6447: #   1     - Continue processing.
 6448: sub retrieve_auto_file_handler {
 6449:     my ($cmd, $tail, $client)    = @_;
 6450:     my $userinput                = "cmd:$tail";
 6451: 
 6452:     my ($filename)   = split(/:/, $tail);
 6453: 
 6454:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
 6455: 
 6456:     if ($filename =~m{/\.\./}) {
 6457:         &Failure($client, "refused\n", $userinput);
 6458:     } elsif ($filename !~ /^$LONCAPA::match_domain\_$LONCAPA::match_courseid\_.+_classlist\.xml$/) {
 6459:         &Failure($client, "refused\n", $userinput);
 6460:     } elsif ( (-e $source) && ($filename ne '') ) {
 6461: 	my $reply = '';
 6462: 	if (open(my $fh,$source)) {
 6463: 	    while (<$fh>) {
 6464: 		chomp($_);
 6465: 		$_ =~ s/^\s+//g;
 6466: 		$_ =~ s/\s+$//g;
 6467: 		$reply .= $_;
 6468: 	    }
 6469: 	    close($fh);
 6470: 	    &Reply($client, &escape($reply)."\n", $userinput);
 6471: 
 6472: #   Does this have to be uncommented??!?  (RF).
 6473: #
 6474: #                                unlink($source);
 6475: 	} else {
 6476: 	    &Failure($client, "error\n", $userinput);
 6477: 	}
 6478:     } else {
 6479: 	&Failure($client, "error\n", $userinput);
 6480:     }
 6481:     
 6482: 
 6483:     return 1;
 6484: }
 6485: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
 6486: 
 6487: sub crsreq_checks_handler {
 6488:     my ($cmd, $tail, $client) = @_;
 6489:     my $userinput = "$cmd:$tail";
 6490:     my $dom = $tail;
 6491:     my $result;
 6492:     my @reqtypes = ('official','unofficial','community','textbook','placement');
 6493:     eval {
 6494:         local($SIG{__DIE__})='DEFAULT';
 6495:         my %validations;
 6496:         my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
 6497:                                                    \%validations);
 6498:         if ($response eq 'ok') { 
 6499:             foreach my $key (keys(%validations)) {
 6500:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
 6501:             }
 6502:             $result =~ s/\&$//;
 6503:         } else {
 6504:             $result = 'error';
 6505:         }
 6506:     };
 6507:     if (!$@) {
 6508:         &Reply($client, \$result, $userinput);
 6509:     } else {
 6510:         &Failure($client,"unknown_cmd\n",$userinput);
 6511:     }
 6512:     return 1;
 6513: }
 6514: &register_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
 6515: 
 6516: sub validate_crsreq_handler {
 6517:     my ($cmd, $tail, $client) = @_;
 6518:     my $userinput = "$cmd:$tail";
 6519:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
 6520:     $instcode = &unescape($instcode);
 6521:     $owner = &unescape($owner);
 6522:     $crstype = &unescape($crstype);
 6523:     $inststatuslist = &unescape($inststatuslist);
 6524:     $instcode = &unescape($instcode);
 6525:     $instseclist = &unescape($instseclist);
 6526:     my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
 6527:     my $outcome;
 6528:     eval {
 6529:         local($SIG{__DIE__})='DEFAULT';
 6530:         $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
 6531:                                                  $inststatuslist,$instcode,
 6532:                                                  $instseclist,$custominfo);
 6533:     };
 6534:     if (!$@) {
 6535:         &Reply($client, \$outcome, $userinput);
 6536:     } else {
 6537:         &Failure($client,"unknown_cmd\n",$userinput);
 6538:     }
 6539:     return 1;
 6540: }
 6541: &register_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
 6542: 
 6543: sub crsreq_update_handler {
 6544:     my ($cmd, $tail, $client) = @_;
 6545:     my $userinput = "$cmd:$tail";
 6546:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
 6547:         $accessstart,$accessend,$infohashref) =
 6548:         split(/:/, $tail);
 6549:     $crstype = &unescape($crstype);
 6550:     $action = &unescape($action);
 6551:     $ownername = &unescape($ownername);
 6552:     $ownerdomain = &unescape($ownerdomain);
 6553:     $fullname = &unescape($fullname);
 6554:     $title = &unescape($title);
 6555:     $code = &unescape($code);
 6556:     $accessstart = &unescape($accessstart);
 6557:     $accessend = &unescape($accessend);
 6558:     my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
 6559:     my ($result,$outcome);
 6560:     eval {
 6561:         local($SIG{__DIE__})='DEFAULT';
 6562:         my %rtnhash;
 6563:         $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
 6564:                                                 $ownername,$ownerdomain,$fullname,
 6565:                                                 $title,$code,$accessstart,$accessend,
 6566:                                                 $incoming,\%rtnhash);
 6567:         if ($outcome eq 'ok') {
 6568:             my @posskeys = qw(createdweb createdmsg createdcustomized createdactions queuedweb queuedmsg formitems reviewweb validationjs onload javascript);
 6569:             foreach my $key (keys(%rtnhash)) {
 6570:                 if (grep(/^\Q$key\E/,@posskeys)) {
 6571:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
 6572:                 }
 6573:             }
 6574:             $result =~ s/\&$//;
 6575:         }
 6576:     };
 6577:     if (!$@) {
 6578:         if ($outcome eq 'ok') {
 6579:             &Reply($client, \$result, $userinput);
 6580:         } else {
 6581:             &Reply($client, "format_error\n", $userinput);
 6582:         }
 6583:     } else {
 6584:         &Failure($client,"unknown_cmd\n",$userinput);
 6585:     }
 6586:     return 1;
 6587: }
 6588: &register_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
 6589: 
 6590: #
 6591: #   Read and retrieve institutional code format (for support form).
 6592: # Formal Parameters:
 6593: #    $cmd        - Command that dispatched us.
 6594: #    $tail       - Tail of the command.  In this case it conatins 
 6595: #                  the course domain and the coursename.
 6596: #    $client     - Socket open on the client.
 6597: # Returns:
 6598: #    1     - Continue processing.
 6599: #
 6600: sub get_institutional_code_format_handler {
 6601:     my ($cmd, $tail, $client)   = @_;
 6602:     my $userinput               = "$cmd:$tail";
 6603: 
 6604:     my $reply;
 6605:     my($cdom,$course) = split(/:/,$tail);
 6606:     my @pairs = split/\&/,$course;
 6607:     my %instcodes = ();
 6608:     my %codes = ();
 6609:     my @codetitles = ();
 6610:     my %cat_titles = ();
 6611:     my %cat_order = ();
 6612:     foreach (@pairs) {
 6613: 	my ($key,$value) = split/=/,$_;
 6614: 	$instcodes{&unescape($key)} = &unescape($value);
 6615:     }
 6616:     my $formatreply = &localenroll::instcode_format($cdom,
 6617: 						    \%instcodes,
 6618: 						    \%codes,
 6619: 						    \@codetitles,
 6620: 						    \%cat_titles,
 6621: 						    \%cat_order);
 6622:     if ($formatreply eq 'ok') {
 6623: 	my $codes_str = &Apache::lonnet::hash2str(%codes);
 6624: 	my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
 6625: 	my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
 6626: 	my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
 6627: 	&Reply($client,
 6628: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
 6629: 	       .$cat_order_str."\n",
 6630: 	       $userinput);
 6631:     } else {
 6632: 	# this else branch added by RF since if not ok, lonc will
 6633: 	# hang waiting on reply until timeout.
 6634: 	#
 6635: 	&Reply($client, "format_error\n", $userinput);
 6636:     }
 6637:     
 6638:     return 1;
 6639: }
 6640: &register_handler("autoinstcodeformat",
 6641: 		  \&get_institutional_code_format_handler,0,1,0);
 6642: 
 6643: sub get_institutional_defaults_handler {
 6644:     my ($cmd, $tail, $client)   = @_;
 6645:     my $userinput               = "$cmd:$tail";
 6646: 
 6647:     my $dom = $tail;
 6648:     my %defaults_hash;
 6649:     my @code_order;
 6650:     my $outcome;
 6651:     eval {
 6652:         local($SIG{__DIE__})='DEFAULT';
 6653:         $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
 6654:                                                    \@code_order);
 6655:     };
 6656:     if (!$@) {
 6657:         if ($outcome eq 'ok') {
 6658:             my $result='';
 6659:             while (my ($key,$value) = each(%defaults_hash)) {
 6660:                 $result.=&escape($key).'='.&escape($value).'&';
 6661:             }
 6662:             $result .= 'code_order='.&escape(join('&',@code_order));
 6663:             &Reply($client,\$result,$userinput);
 6664:         } else {
 6665:             &Reply($client,"error\n", $userinput);
 6666:         }
 6667:     } else {
 6668:         &Failure($client,"unknown_cmd\n",$userinput);
 6669:     }
 6670: }
 6671: &register_handler("autoinstcodedefaults",
 6672:                   \&get_institutional_defaults_handler,0,1,0);
 6673: 
 6674: sub get_possible_instcodes_handler {
 6675:     my ($cmd, $tail, $client)   = @_;
 6676:     my $userinput               = "$cmd:$tail";
 6677: 
 6678:     my $reply;
 6679:     my $cdom = $tail;
 6680:     my (@codetitles,%cat_titles,%cat_order,@code_order);
 6681:     my $formatreply = &localenroll::possible_instcodes($cdom,
 6682:                                                        \@codetitles,
 6683:                                                        \%cat_titles,
 6684:                                                        \%cat_order,
 6685:                                                        \@code_order);
 6686:     if ($formatreply eq 'ok') {
 6687:         my $result = join('&',map {&escape($_);} (@codetitles)).':';
 6688:         $result .= join('&',map {&escape($_);} (@code_order)).':';
 6689:         foreach my $key (keys(%cat_titles)) {
 6690:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
 6691:         }
 6692:         $result =~ s/\&$//;
 6693:         $result .= ':';
 6694:         foreach my $key (keys(%cat_order)) {
 6695:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
 6696:         }
 6697:         $result =~ s/\&$//;
 6698:         &Reply($client,\$result,$userinput);
 6699:     } else {
 6700:         &Reply($client, "format_error\n", $userinput);
 6701:     }
 6702:     return 1;
 6703: }
 6704: &register_handler("autopossibleinstcodes",
 6705:                   \&get_possible_instcodes_handler,0,1,0);
 6706: 
 6707: sub get_institutional_user_rules {
 6708:     my ($cmd, $tail, $client)   = @_;
 6709:     my $userinput               = "$cmd:$tail";
 6710:     my $dom = &unescape($tail);
 6711:     my (%rules_hash,@rules_order);
 6712:     my $outcome;
 6713:     eval {
 6714:         local($SIG{__DIE__})='DEFAULT';
 6715:         $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
 6716:     };
 6717:     if (!$@) {
 6718:         if ($outcome eq 'ok') {
 6719:             my $result;
 6720:             foreach my $key (keys(%rules_hash)) {
 6721:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
 6722:             }
 6723:             $result =~ s/\&$//;
 6724:             $result .= ':';
 6725:             if (@rules_order > 0) {
 6726:                 foreach my $item (@rules_order) {
 6727:                     $result .= &escape($item).'&';
 6728:                 }
 6729:             }
 6730:             $result =~ s/\&$//;
 6731:             &Reply($client,\$result,$userinput);
 6732:         } else {
 6733:             &Reply($client,"error\n", $userinput);
 6734:         }
 6735:     } else {
 6736:         &Failure($client,"unknown_cmd\n",$userinput);
 6737:     }
 6738: }
 6739: &register_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
 6740: 
 6741: sub get_institutional_id_rules {
 6742:     my ($cmd, $tail, $client)   = @_;
 6743:     my $userinput               = "$cmd:$tail";
 6744:     my $dom = &unescape($tail);
 6745:     my (%rules_hash,@rules_order);
 6746:     my $outcome;
 6747:     eval {
 6748:         local($SIG{__DIE__})='DEFAULT';
 6749:         $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
 6750:     };
 6751:     if (!$@) {
 6752:         if ($outcome eq 'ok') {
 6753:             my $result;
 6754:             foreach my $key (keys(%rules_hash)) {
 6755:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
 6756:             }
 6757:             $result =~ s/\&$//;
 6758:             $result .= ':';
 6759:             if (@rules_order > 0) {
 6760:                 foreach my $item (@rules_order) {
 6761:                     $result .= &escape($item).'&';
 6762:                 }
 6763:             }
 6764:             $result =~ s/\&$//;
 6765:             &Reply($client,\$result,$userinput);
 6766:         } else {
 6767:             &Reply($client,"error\n", $userinput);
 6768:         }
 6769:     } else {
 6770:         &Failure($client,"unknown_cmd\n",$userinput);
 6771:     }
 6772: }
 6773: &register_handler("instidrules",\&get_institutional_id_rules,0,1,0);
 6774: 
 6775: sub get_institutional_selfcreate_rules {
 6776:     my ($cmd, $tail, $client)   = @_;
 6777:     my $userinput               = "$cmd:$tail";
 6778:     my $dom = &unescape($tail);
 6779:     my (%rules_hash,@rules_order);
 6780:     my $outcome;
 6781:     eval {
 6782:         local($SIG{__DIE__})='DEFAULT';
 6783:         $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
 6784:     };
 6785:     if (!$@) {
 6786:         if ($outcome eq 'ok') {
 6787:             my $result;
 6788:             foreach my $key (keys(%rules_hash)) {
 6789:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
 6790:             }
 6791:             $result =~ s/\&$//;
 6792:             $result .= ':';
 6793:             if (@rules_order > 0) {
 6794:                 foreach my $item (@rules_order) {
 6795:                     $result .= &escape($item).'&';
 6796:                 }
 6797:             }
 6798:             $result =~ s/\&$//;
 6799:             &Reply($client,\$result,$userinput);
 6800:         } else {
 6801:             &Reply($client,"error\n", $userinput);
 6802:         }
 6803:     } else {
 6804:         &Failure($client,"unknown_cmd\n",$userinput);
 6805:     }
 6806: }
 6807: &register_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
 6808: 
 6809: 
 6810: sub institutional_username_check {
 6811:     my ($cmd, $tail, $client)   = @_;
 6812:     my $userinput               = "$cmd:$tail";
 6813:     my %rulecheck;
 6814:     my $outcome;
 6815:     my ($udom,$uname,@rules) = split(/:/,$tail);
 6816:     $udom = &unescape($udom);
 6817:     $uname = &unescape($uname);
 6818:     @rules = map {&unescape($_);} (@rules);
 6819:     eval {
 6820:         local($SIG{__DIE__})='DEFAULT';
 6821:         $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
 6822:     };
 6823:     if (!$@) {
 6824:         if ($outcome eq 'ok') {
 6825:             my $result='';
 6826:             foreach my $key (keys(%rulecheck)) {
 6827:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
 6828:             }
 6829:             &Reply($client,\$result,$userinput);
 6830:         } else {
 6831:             &Reply($client,"error\n", $userinput);
 6832:         }
 6833:     } else {
 6834:         &Failure($client,"unknown_cmd\n",$userinput);
 6835:     }
 6836: }
 6837: &register_handler("instrulecheck",\&institutional_username_check,0,1,0);
 6838: 
 6839: sub institutional_id_check {
 6840:     my ($cmd, $tail, $client)   = @_;
 6841:     my $userinput               = "$cmd:$tail";
 6842:     my %rulecheck;
 6843:     my $outcome;
 6844:     my ($udom,$id,@rules) = split(/:/,$tail);
 6845:     $udom = &unescape($udom);
 6846:     $id = &unescape($id);
 6847:     @rules = map {&unescape($_);} (@rules);
 6848:     eval {
 6849:         local($SIG{__DIE__})='DEFAULT';
 6850:         $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
 6851:     };
 6852:     if (!$@) {
 6853:         if ($outcome eq 'ok') {
 6854:             my $result='';
 6855:             foreach my $key (keys(%rulecheck)) {
 6856:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
 6857:             }
 6858:             &Reply($client,\$result,$userinput);
 6859:         } else {
 6860:             &Reply($client,"error\n", $userinput);
 6861:         }
 6862:     } else {
 6863:         &Failure($client,"unknown_cmd\n",$userinput);
 6864:     }
 6865: }
 6866: &register_handler("instidrulecheck",\&institutional_id_check,0,1,0);
 6867: 
 6868: sub institutional_selfcreate_check {
 6869:     my ($cmd, $tail, $client)   = @_;
 6870:     my $userinput               = "$cmd:$tail";
 6871:     my %rulecheck;
 6872:     my $outcome;
 6873:     my ($udom,$email,@rules) = split(/:/,$tail);
 6874:     $udom = &unescape($udom);
 6875:     $email = &unescape($email);
 6876:     @rules = map {&unescape($_);} (@rules);
 6877:     eval {
 6878:         local($SIG{__DIE__})='DEFAULT';
 6879:         $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
 6880:     };
 6881:     if (!$@) {
 6882:         if ($outcome eq 'ok') {
 6883:             my $result='';
 6884:             foreach my $key (keys(%rulecheck)) {
 6885:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
 6886:             }
 6887:             &Reply($client,\$result,$userinput);
 6888:         } else {
 6889:             &Reply($client,"error\n", $userinput);
 6890:         }
 6891:     } else {
 6892:         &Failure($client,"unknown_cmd\n",$userinput);
 6893:     }
 6894: }
 6895: &register_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
 6896: 
 6897: # Get domain specific conditions for import of student photographs to a course
 6898: #
 6899: # Retrieves information from photo_permission subroutine in localenroll.
 6900: # Returns outcome (ok) if no processing errors, and whether course owner is 
 6901: # required to accept conditions of use (yes/no).
 6902: #
 6903: #    
 6904: sub photo_permission_handler {
 6905:     my ($cmd, $tail, $client)   = @_;
 6906:     my $userinput               = "$cmd:$tail";
 6907:     my $cdom = $tail;
 6908:     my ($perm_reqd,$conditions);
 6909:     my $outcome;
 6910:     eval {
 6911: 	local($SIG{__DIE__})='DEFAULT';
 6912: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
 6913: 						  \$conditions);
 6914:     };
 6915:     if (!$@) {
 6916: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
 6917: 	       $userinput);
 6918:     } else {
 6919: 	&Failure($client,"unknown_cmd\n",$userinput);
 6920:     }
 6921:     return 1;
 6922: }
 6923: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
 6924: 
 6925: #
 6926: # Checks if student photo is available for a user in the domain, in the user's
 6927: # directory (in /userfiles/internal/studentphoto.jpg).
 6928: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
 6929: # the student's photo.   
 6930: 
 6931: sub photo_check_handler {
 6932:     my ($cmd, $tail, $client)   = @_;
 6933:     my $userinput               = "$cmd:$tail";
 6934:     my ($udom,$uname,$pid) = split(/:/,$tail);
 6935:     $udom = &unescape($udom);
 6936:     $uname = &unescape($uname);
 6937:     $pid = &unescape($pid);
 6938:     my $path=&propath($udom,$uname).'/userfiles/internal/';
 6939:     if (!-e $path) {
 6940:         &mkpath($path);
 6941:     }
 6942:     my $response;
 6943:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
 6944:     $result .= ':'.$response;
 6945:     &Reply($client, &escape($result)."\n",$userinput);
 6946:     return 1;
 6947: }
 6948: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
 6949: 
 6950: #
 6951: # Retrieve information from localenroll about whether to provide a button     
 6952: # for users who have enbled import of student photos to initiate an 
 6953: # update of photo files for registered students. Also include 
 6954: # comment to display alongside button.  
 6955: 
 6956: sub photo_choice_handler {
 6957:     my ($cmd, $tail, $client) = @_;
 6958:     my $userinput             = "$cmd:$tail";
 6959:     my $cdom                  = &unescape($tail);
 6960:     my ($update,$comment);
 6961:     eval {
 6962: 	local($SIG{__DIE__})='DEFAULT';
 6963: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
 6964:     };
 6965:     if (!$@) {
 6966: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
 6967:     } else {
 6968: 	&Failure($client,"unknown_cmd\n",$userinput);
 6969:     }
 6970:     return 1;
 6971: }
 6972: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
 6973: 
 6974: #
 6975: # Gets a student's photo to exist (in the correct image type) in the user's 
 6976: # directory.
 6977: # Formal Parameters:
 6978: #    $cmd     - The command request that got us dispatched.
 6979: #    $tail    - A colon separated set of words that will be split into:
 6980: #               $domain - student's domain
 6981: #               $uname  - student username
 6982: #               $type   - image type desired
 6983: #    $client  - The socket open on the client.
 6984: # Returns:
 6985: #    1 - continue processing.
 6986: 
 6987: sub student_photo_handler {
 6988:     my ($cmd, $tail, $client) = @_;
 6989:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
 6990: 
 6991:     my $path=&propath($domain,$uname). '/userfiles/internal/';
 6992:     my $filename = 'studentphoto.'.$ext;
 6993:     if ($type eq 'thumbnail') {
 6994:         $filename = 'studentphoto_tn.'.$ext;
 6995:     }
 6996:     if (-e $path.$filename) {
 6997: 	&Reply($client,"ok\n","$cmd:$tail");
 6998: 	return 1;
 6999:     }
 7000:     &mkpath($path);
 7001:     my $file;
 7002:     if ($type eq 'thumbnail') {
 7003: 	eval {
 7004: 	    local($SIG{__DIE__})='DEFAULT';
 7005: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
 7006: 	};
 7007:     } else {
 7008:         $file=&localstudentphoto::fetch($domain,$uname);
 7009:     }
 7010:     if (!$file) {
 7011: 	&Failure($client,"unavailable\n","$cmd:$tail");
 7012: 	return 1;
 7013:     }
 7014:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
 7015:     if (-e $path.$filename) {
 7016: 	&Reply($client,"ok\n","$cmd:$tail");
 7017: 	return 1;
 7018:     }
 7019:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
 7020:     return 1;
 7021: }
 7022: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
 7023: 
 7024: sub inst_usertypes_handler {
 7025:     my ($cmd, $domain, $client) = @_;
 7026:     my $res;
 7027:     my $userinput = $cmd.":".$domain; # For logging purposes.
 7028:     my (%typeshash,@order,$result);
 7029:     eval {
 7030: 	local($SIG{__DIE__})='DEFAULT';
 7031: 	$result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
 7032:     };
 7033:     if ($result eq 'ok') {
 7034:         if (keys(%typeshash) > 0) {
 7035:             foreach my $key (keys(%typeshash)) {
 7036:                 $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
 7037:             }
 7038:         }
 7039:         $res=~s/\&$//;
 7040:         $res .= ':';
 7041:         if (@order > 0) {
 7042:             foreach my $item (@order) {
 7043:                 $res .= &escape($item).'&';
 7044:             }
 7045:         }
 7046:         $res=~s/\&$//;
 7047:     }
 7048:     &Reply($client, \$res, $userinput);
 7049:     return 1;
 7050: }
 7051: &register_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
 7052: 
 7053: # mkpath makes all directories for a file, expects an absolute path with a
 7054: # file or a trailing / if just a dir is passed
 7055: # returns 1 on success 0 on failure
 7056: sub mkpath {
 7057:     my ($file)=@_;
 7058:     my @parts=split(/\//,$file,-1);
 7059:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
 7060:     for (my $i=3;$i<= ($#parts-1);$i++) {
 7061: 	$now.='/'.$parts[$i]; 
 7062: 	if (!-e $now) {
 7063: 	    if  (!mkdir($now,0770)) { return 0; }
 7064: 	}
 7065:     }
 7066:     return 1;
 7067: }
 7068: 
 7069: #---------------------------------------------------------------
 7070: #
 7071: #   Getting, decoding and dispatching requests:
 7072: #
 7073: #
 7074: #   Get a Request:
 7075: #   Gets a Request message from the client.  The transaction
 7076: #   is defined as a 'line' of text.  We remove the new line
 7077: #   from the text line.  
 7078: #
 7079: sub get_request {
 7080:     my $input = <$client>;
 7081:     chomp($input);
 7082: 
 7083:     &Debug("get_request: Request = $input\n");
 7084: 
 7085:     &status('Processing '.$clientname.':'.$input);
 7086: 
 7087:     return $input;
 7088: }
 7089: #---------------------------------------------------------------
 7090: #
 7091: #  Process a request.  This sub should shrink as each action
 7092: #  gets farmed out into a separat sub that is registered 
 7093: #  with the dispatch hash.  
 7094: #
 7095: # Parameters:
 7096: #    user_input   - The request received from the client (lonc).
 7097: #
 7098: # Returns:
 7099: #    true to keep processing, false if caller should exit.
 7100: #
 7101: sub process_request {
 7102:     my ($userinput) = @_; # Easier for now to break style than to
 7103:                           # fix all the userinput -> user_input.
 7104:     my $wasenc    = 0;		# True if request was encrypted.
 7105: # ------------------------------------------------------------ See if encrypted
 7106:     # for command
 7107:     # sethost:<server>
 7108:     # <command>:<args>
 7109:     #   we just send it to the processor
 7110:     # for
 7111:     # sethost:<server>:<command>:<args>
 7112:     #  we do the implict set host and then do the command
 7113:     if ($userinput =~ /^sethost:/) {
 7114: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
 7115: 	if (defined($userinput)) {
 7116: 	    &sethost("$cmd:$newid");
 7117: 	} else {
 7118: 	    $userinput = "$cmd:$newid";
 7119: 	}
 7120:     }
 7121: 
 7122:     if ($userinput =~ /^enc/) {
 7123: 	$userinput = decipher($userinput);
 7124: 	$wasenc=1;
 7125: 	if(!$userinput) {	# Cipher not defined.
 7126: 	    &Failure($client, "error: Encrypted data without negotated key\n");
 7127: 	    return 0;
 7128: 	}
 7129:     }
 7130:     Debug("process_request: $userinput\n");
 7131:     
 7132:     #  
 7133:     #   The 'correct way' to add a command to lond is now to
 7134:     #   write a sub to execute it and Add it to the command dispatch
 7135:     #   hash via a call to register_handler..  The comments to that
 7136:     #   sub should give you enough to go on to show how to do this
 7137:     #   along with the examples that are building up as this code
 7138:     #   is getting refactored.   Until all branches of the
 7139:     #   if/elseif monster below have been factored out into
 7140:     #   separate procesor subs, if the dispatch hash is missing
 7141:     #   the command keyword, we will fall through to the remainder
 7142:     #   of the if/else chain below in order to keep this thing in 
 7143:     #   working order throughout the transmogrification.
 7144: 
 7145:     my ($command, $tail) = split(/:/, $userinput, 2);
 7146:     chomp($command);
 7147:     chomp($tail);
 7148:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
 7149:     $command =~ s/(\r)//;	# And this too for parameterless commands.
 7150:     if(!$tail) {
 7151: 	$tail ="";		# defined but blank.
 7152:     }
 7153: 
 7154:     &Debug("Command received: $command, encoded = $wasenc");
 7155: 
 7156:     if(defined $Dispatcher{$command}) {
 7157: 
 7158: 	my $dispatch_info = $Dispatcher{$command};
 7159: 	my $handler       = $$dispatch_info[0];
 7160: 	my $need_encode   = $$dispatch_info[1];
 7161: 	my $client_types  = $$dispatch_info[2];
 7162: 	Debug("Matched dispatch hash: mustencode: $need_encode "
 7163: 	      ."ClientType $client_types");
 7164:       
 7165: 	#  Validate the request:
 7166:       
 7167: 	my $ok = 1;
 7168: 	my $requesterprivs = 0;
 7169: 	if(&isClient()) {
 7170: 	    $requesterprivs |= $CLIENT_OK;
 7171: 	}
 7172: 	if(&isManager()) {
 7173: 	    $requesterprivs |= $MANAGER_OK;
 7174: 	}
 7175: 	if($need_encode && (!$wasenc)) {
 7176: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
 7177: 	    $ok = 0;
 7178: 	}
 7179: 	if(($client_types & $requesterprivs) == 0) {
 7180: 	    Debug("Client not privileged to do this operation");
 7181: 	    $ok = 0;
 7182: 	}
 7183:         if ($ok) {
 7184:             my $realcommand = $command;
 7185:             if ($command eq 'querysend') {
 7186:                 my ($query,$rest)=split(/\:/,$tail,2);
 7187:                 $query=~s/\n*$//g;
 7188:                 my @possqueries = 
 7189:                     qw(userlog courselog fetchenrollment institutionalphotos usersearch instdirsearch getinstuser getmultinstusers);
 7190:                 if (grep(/^\Q$query\E$/,@possqueries)) {
 7191:                     $command .= '_'.$query;
 7192:                 } elsif ($query eq 'prepare activity log') {
 7193:                     $command .= '_activitylog';
 7194:                 }
 7195:             }
 7196:             if (ref($trust{$command}) eq 'HASH') {
 7197:                 my $donechecks;
 7198:                 if ($trust{$command}{'anywhere'}) {
 7199:                    $donechecks = 1;
 7200:                 } elsif ($trust{$command}{'manageronly'}) {
 7201:                     unless (&isManager()) {
 7202:                         $ok = 0;
 7203:                     }
 7204:                     $donechecks = 1;
 7205:                 } elsif ($trust{$command}{'institutiononly'}) {
 7206:                     unless ($clientsameinst) {
 7207:                         $ok = 0;
 7208:                     }
 7209:                     $donechecks = 1;
 7210:                 } elsif ($clientsameinst) {
 7211:                     $donechecks = 1;
 7212:                 }
 7213:                 unless ($donechecks) {
 7214:                     foreach my $rule (keys(%{$trust{$command}})) {
 7215:                         next if ($rule eq 'remote');
 7216:                         if ($trust{$command}{$rule}) {
 7217:                             if ($clientprohibited{$rule}) {
 7218:                                 $ok = 0;
 7219:                             } else {
 7220:                                 $ok = 1;
 7221:                                 $donechecks = 1;
 7222:                                 last;
 7223:                             }
 7224:                         }
 7225:                     }
 7226:                 }
 7227:                 unless ($donechecks) {
 7228:                     if ($trust{$command}{'remote'}) {
 7229:                         if ($clientremoteok) {
 7230:                             $ok = 1;
 7231:                         } else {
 7232:                             $ok = 0;
 7233:                         } 
 7234:                     }
 7235:                 }
 7236:             }
 7237:             $command = $realcommand;
 7238:         }
 7239: 
 7240: 	if($ok) {
 7241: 	    Debug("Dispatching to handler $command $tail");
 7242: 	    my $keep_going = &$handler($command, $tail, $client);
 7243: 	    return $keep_going;
 7244: 	} else {
 7245: 	    Debug("Refusing to dispatch because client did not match requirements");
 7246: 	    Failure($client, "refused\n", $userinput);
 7247: 	    return 1;
 7248: 	}
 7249:     }
 7250: 
 7251:     print $client "unknown_cmd\n";
 7252: # -------------------------------------------------------------------- complete
 7253:     Debug("process_request - returning 1");
 7254:     return 1;
 7255: }
 7256: #
 7257: #   Decipher encoded traffic
 7258: #  Parameters:
 7259: #     input      - Encoded data.
 7260: #  Returns:
 7261: #     Decoded data or undef if encryption key was not yet negotiated.
 7262: #  Implicit input:
 7263: #     cipher  - This global holds the negotiated encryption key.
 7264: #
 7265: sub decipher {
 7266:     my ($input)  = @_;
 7267:     my $output = '';
 7268:     
 7269:     
 7270:     if($cipher) {
 7271: 	my($enc, $enclength, $encinput) = split(/:/, $input);
 7272: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
 7273: 	    $output .= 
 7274: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
 7275: 	}
 7276: 	return substr($output, 0, $enclength);
 7277:     } else {
 7278: 	return undef;
 7279:     }
 7280: }
 7281: 
 7282: #
 7283: #   Register a command processor.  This function is invoked to register a sub
 7284: #   to process a request.  Once registered, the ProcessRequest sub can automatically
 7285: #   dispatch requests to an appropriate sub, and do the top level validity checking
 7286: #   as well:
 7287: #    - Is the keyword recognized.
 7288: #    - Is the proper client type attempting the request.
 7289: #    - Is the request encrypted if it has to be.
 7290: #   Parameters:
 7291: #    $request_name         - Name of the request being registered.
 7292: #                           This is the command request that will match
 7293: #                           against the hash keywords to lookup the information
 7294: #                           associated with the dispatch information.
 7295: #    $procedure           - Reference to a sub to call to process the request.
 7296: #                           All subs get called as follows:
 7297: #                             Procedure($cmd, $tail, $replyfd, $key)
 7298: #                             $cmd    - the actual keyword that invoked us.
 7299: #                             $tail   - the tail of the request that invoked us.
 7300: #                             $replyfd- File descriptor connected to the client
 7301: #    $must_encode          - True if the request must be encoded to be good.
 7302: #    $client_ok            - True if it's ok for a client to request this.
 7303: #    $manager_ok           - True if it's ok for a manager to request this.
 7304: # Side effects:
 7305: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
 7306: #      - On failure, the program will die as it's a bad internal bug to try to 
 7307: #        register a duplicate command handler.
 7308: #
 7309: sub register_handler {
 7310:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
 7311: 
 7312:     #  Don't allow duplication#
 7313:    
 7314:     if (defined $Dispatcher{$request_name}) {
 7315: 	die "Attempting to define a duplicate request handler for $request_name\n";
 7316:     }
 7317:     #   Build the client type mask:
 7318:     
 7319:     my $client_type_mask = 0;
 7320:     if($client_ok) {
 7321: 	$client_type_mask  |= $CLIENT_OK;
 7322:     }
 7323:     if($manager_ok) {
 7324: 	$client_type_mask  |= $MANAGER_OK;
 7325:     }
 7326:    
 7327:     #  Enter the hash:
 7328:       
 7329:     my @entry = ($procedure, $must_encode, $client_type_mask);
 7330:    
 7331:     $Dispatcher{$request_name} = \@entry;
 7332:    
 7333: }
 7334: 
 7335: 
 7336: #------------------------------------------------------------------
 7337: 
 7338: 
 7339: 
 7340: 
 7341: #
 7342: #  Convert an error return code from lcpasswd to a string value.
 7343: #
 7344: sub lcpasswdstrerror {
 7345:     my $ErrorCode = shift;
 7346:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
 7347: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
 7348:     } else {
 7349: 	return $passwderrors[$ErrorCode];
 7350:     }
 7351: }
 7352: 
 7353: # grabs exception and records it to log before exiting
 7354: sub catchexception {
 7355:     my ($error)=@_;
 7356:     $SIG{'QUIT'}='DEFAULT';
 7357:     $SIG{__DIE__}='DEFAULT';
 7358:     &status("Catching exception");
 7359:     &logthis("<font color='red'>CRITICAL: "
 7360:      ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
 7361:      ."a crash with this error msg->[$error]</font>");
 7362:     &logthis('Famous last words: '.$status.' - '.$lastlog);
 7363:     if ($client) { print $client "error: $error\n"; }
 7364:     $server->close();
 7365:     die($error);
 7366: }
 7367: sub timeout {
 7368:     &status("Handling Timeout");
 7369:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
 7370:     &catchexception('Timeout');
 7371: }
 7372: # -------------------------------- Set signal handlers to record abnormal exits
 7373: 
 7374: 
 7375: $SIG{'QUIT'}=\&catchexception;
 7376: $SIG{__DIE__}=\&catchexception;
 7377: 
 7378: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
 7379: &status("Read loncapa.conf and loncapa_apache.conf");
 7380: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
 7381: %perlvar=%{$perlvarref};
 7382: undef $perlvarref;
 7383: 
 7384: # ----------------------------- Make sure this process is running from user=www
 7385: my $wwwid=getpwnam('www');
 7386: if ($wwwid!=$<) {
 7387:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
 7388:    my $subj="LON: $currenthostid User ID mismatch";
 7389:    system("echo 'User ID mismatch.  lond must be run as user www.' |".
 7390:           " mail -s '$subj' $emailto > /dev/null");
 7391:    exit 1;
 7392: }
 7393: 
 7394: # --------------------------------------------- Check if other instance running
 7395: 
 7396: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
 7397: 
 7398: if (-e $pidfile) {
 7399:    my $lfh=IO::File->new("$pidfile");
 7400:    my $pide=<$lfh>;
 7401:    chomp($pide);
 7402:    if (kill 0 => $pide) { die "already running"; }
 7403: }
 7404: 
 7405: # ------------------------------------------------------------- Read hosts file
 7406: 
 7407: 
 7408: 
 7409: # establish SERVER socket, bind and listen.
 7410: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
 7411:                                 Type      => SOCK_STREAM,
 7412:                                 Proto     => 'tcp',
 7413:                                 ReuseAddr     => 1,
 7414:                                 Listen    => 10 )
 7415:   or die "making socket: $@\n";
 7416: 
 7417: # --------------------------------------------------------- Do global variables
 7418: 
 7419: # global variables
 7420: 
 7421: my %children               = ();       # keys are current child process IDs
 7422: 
 7423: sub REAPER {                        # takes care of dead children
 7424:     $SIG{CHLD} = \&REAPER;
 7425:     &status("Handling child death");
 7426:     my $pid;
 7427:     do {
 7428: 	$pid = waitpid(-1,&WNOHANG());
 7429: 	if (defined($children{$pid})) {
 7430: 	    &logthis("Child $pid died");
 7431: 	    delete($children{$pid});
 7432: 	} elsif ($pid > 0) {
 7433: 	    &logthis("Unknown Child $pid died");
 7434: 	}
 7435:     } while ( $pid > 0 );
 7436:     foreach my $child (keys(%children)) {
 7437: 	$pid = waitpid($child,&WNOHANG());
 7438: 	if ($pid > 0) {
 7439: 	    &logthis("Child $child - $pid looks like we missed it's death");
 7440: 	    delete($children{$pid});
 7441: 	}
 7442:     }
 7443:     &status("Finished Handling child death");
 7444: }
 7445: 
 7446: sub HUNTSMAN {                      # signal handler for SIGINT
 7447:     &status("Killing children (INT)");
 7448:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
 7449:     kill 'INT' => keys %children;
 7450:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
 7451:     my $execdir=$perlvar{'lonDaemons'};
 7452:     unlink("$execdir/logs/lond.pid");
 7453:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
 7454:     &status("Done killing children");
 7455:     exit;                           # clean up with dignity
 7456: }
 7457: 
 7458: sub HUPSMAN {                      # signal handler for SIGHUP
 7459:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
 7460:     &status("Killing children for restart (HUP)");
 7461:     kill 'INT' => keys %children;
 7462:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
 7463:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
 7464:     my $execdir=$perlvar{'lonDaemons'};
 7465:     unlink("$execdir/logs/lond.pid");
 7466:     &status("Restarting self (HUP)");
 7467:     exec("$execdir/lond");         # here we go again
 7468: }
 7469: 
 7470: #
 7471: #  Reload the Apache daemon's state.
 7472: #  This is done by invoking /home/httpd/perl/apachereload
 7473: #  a setuid perl script that can be root for us to do this job.
 7474: #
 7475: sub ReloadApache {
 7476: # --------------------------- Handle case of another apachereload process (locking)
 7477:     if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
 7478:         my $execdir = $perlvar{'lonDaemons'};
 7479:         my $script  = $execdir."/apachereload";
 7480:         system($script);
 7481:         unlink('/tmp/lock_apachereload'); #  Remove the lock file.
 7482:     }
 7483: }
 7484: 
 7485: #
 7486: #   Called in response to a USR2 signal.
 7487: #   - Reread hosts.tab
 7488: #   - All children connected to hosts that were removed from hosts.tab
 7489: #     are killed via SIGINT
 7490: #   - All children connected to previously existing hosts are sent SIGUSR1
 7491: #   - Our internal hosts hash is updated to reflect the new contents of
 7492: #     hosts.tab causing connections from hosts added to hosts.tab to
 7493: #     now be honored.
 7494: #
 7495: sub UpdateHosts {
 7496:     &status("Reload hosts.tab");
 7497:     logthis('<font color="blue"> Updating connections </font>');
 7498:     #
 7499:     #  The %children hash has the set of IP's we currently have children
 7500:     #  on.  These need to be matched against records in the hosts.tab
 7501:     #  Any ip's no longer in the table get killed off they correspond to
 7502:     #  either dropped or changed hosts.  Note that the re-read of the table
 7503:     #  will take care of new and changed hosts as connections come into being.
 7504: 
 7505:     &Apache::lonnet::reset_hosts_info();
 7506:     my %active;
 7507: 
 7508:     foreach my $child (keys(%children)) {
 7509: 	my $childip = $children{$child};
 7510: 	if ($childip ne '127.0.0.1'
 7511: 	    && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
 7512: 	    logthis('<font color="blue"> UpdateHosts killing child '
 7513: 		    ." $child for ip $childip </font>");
 7514: 	    kill('INT', $child);
 7515: 	} else {
 7516:             $active{$child} = $childip;
 7517: 	    logthis('<font color="green"> keeping child for ip '
 7518: 		    ." $childip (pid=$child) </font>");
 7519: 	}
 7520:     }
 7521: 
 7522:     my %oldconf = %secureconf;
 7523:     my %connchange;
 7524:     if (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
 7525:         logthis('<font color="blue"> Reloaded SSL connection rules and cleared CRL checking history </font>');
 7526:     } else {
 7527:         logthis('<font color="yellow"> Failed to reload SSL connection rules and clear CRL checking history </font>');
 7528:     }
 7529:     if ((ref($oldconf{'connfrom'}) eq 'HASH') && (ref($secureconf{'connfrom'}) eq 'HASH')) {
 7530:         foreach my $type ('dom','intdom','other') {
 7531:             if ((($oldconf{'connfrom'}{$type} eq 'no') && ($secureconf{'connfrom'}{$type} eq 'req')) ||
 7532:                 (($oldconf{'connfrom'}{$type} eq 'req') && ($secureconf{'connfrom'}{$type} eq 'no'))) {
 7533:                 $connchange{$type} = 1;
 7534:             }
 7535:         }
 7536:     }
 7537:     if (keys(%connchange)) {
 7538:         foreach my $child (keys(%active)) {
 7539:             my $childip = $active{$child};
 7540:             if ($childip ne '127.0.0.1') {
 7541:                 my $childhostname  = gethostbyaddr(Socket::inet_aton($childip),AF_INET);
 7542:                 if ($childhostname ne '') {
 7543:                     my $childlonhost = &Apache::lonnet::get_server_homeID($childhostname);
 7544:                     my ($samedom,$sameinst) = &set_client_info($childlonhost);
 7545:                     if ($samedom) {
 7546:                         if ($connchange{'dom'}) {
 7547:                             logthis('<font color="blue"> UpdateHosts killing child '
 7548:                                    ." $child for ip $childip </font>");
 7549:                             kill('INT', $child);
 7550:                         }
 7551:                     } elsif ($sameinst) {
 7552:                         if ($connchange{'intdom'}) {
 7553:                             logthis('<font color="blue"> UpdateHosts killing child '
 7554:                                    ." $child for ip $childip </font>");
 7555:                            kill('INT', $child);
 7556:                         }
 7557:                     } else {
 7558:                         if ($connchange{'other'}) {
 7559:                             logthis('<font color="blue"> UpdateHosts killing child '
 7560:                                    ." $child for ip $childip </font>");
 7561:                             kill('INT', $child);
 7562:                         }
 7563:                     }
 7564:                 }
 7565:             }
 7566:         }
 7567:     }
 7568:     ReloadApache;
 7569:     &status("Finished reloading hosts.tab");
 7570: }
 7571: 
 7572: sub checkchildren {
 7573:     &status("Checking on the children (sending signals)");
 7574:     &initnewstatus();
 7575:     &logstatus();
 7576:     &logthis('Going to check on the children');
 7577:     my $docdir=$perlvar{'lonDocRoot'};
 7578:     foreach (sort keys %children) {
 7579: 	#sleep 1;
 7580:         unless (kill 'USR1' => $_) {
 7581: 	    &logthis ('Child '.$_.' is dead');
 7582:             &logstatus($$.' is dead');
 7583: 	    delete($children{$_});
 7584:         } 
 7585:     }
 7586:     sleep 5;
 7587:     $SIG{ALRM} = sub { Debug("timeout"); 
 7588: 		       die "timeout";  };
 7589:     $SIG{__DIE__} = 'DEFAULT';
 7590:     &status("Checking on the children (waiting for reports)");
 7591:     foreach (sort keys %children) {
 7592:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
 7593:           eval {
 7594:             alarm(300);
 7595: 	    &logthis('Child '.$_.' did not respond');
 7596: 	    kill 9 => $_;
 7597: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
 7598: 	    #$subj="LON: $currenthostid killed lond process $_";
 7599: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
 7600: 	    #$execdir=$perlvar{'lonDaemons'};
 7601: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
 7602: 	    delete($children{$_});
 7603: 	    alarm(0);
 7604: 	  }
 7605:         }
 7606:     }
 7607:     $SIG{ALRM} = 'DEFAULT';
 7608:     $SIG{__DIE__} = \&catchexception;
 7609:     &status("Finished checking children");
 7610:     &logthis('Finished Checking children');
 7611: }
 7612: 
 7613: # --------------------------------------------------------------------- Logging
 7614: 
 7615: sub logthis {
 7616:     my $message=shift;
 7617:     my $execdir=$perlvar{'lonDaemons'};
 7618:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
 7619:     my $now=time;
 7620:     my $local=localtime($now);
 7621:     $lastlog=$local.': '.$message;
 7622:     print $fh "$local ($$): $message\n";
 7623: }
 7624: 
 7625: # ------------------------- Conditional log if $DEBUG true.
 7626: sub Debug {
 7627:     my $message = shift;
 7628:     if($DEBUG) {
 7629: 	&logthis($message);
 7630:     }
 7631: }
 7632: 
 7633: #
 7634: #   Sub to do replies to client.. this gives a hook for some
 7635: #   debug tracing too:
 7636: #  Parameters:
 7637: #     fd      - File open on client.
 7638: #     reply   - Text to send to client.
 7639: #     request - Original request from client.
 7640: #
 7641: #NOTE $reply must be terminated by exactly *one* \n. If $reply is a reference
 7642: #this is done automatically ($$reply must not contain any \n in this case). 
 7643: #If $reply is a string the caller has to ensure this.
 7644: sub Reply {
 7645:     my ($fd, $reply, $request) = @_;
 7646:     if (ref($reply)) {
 7647: 	print $fd $$reply;
 7648: 	print $fd "\n";
 7649: 	if ($DEBUG) { Debug("Request was $request  Reply was $$reply"); }
 7650:     } else {
 7651: 	print $fd $reply;
 7652: 	if ($DEBUG) { Debug("Request was $request  Reply was $reply"); }
 7653:     }
 7654:     $Transactions++;
 7655: }
 7656: 
 7657: 
 7658: #
 7659: #    Sub to report a failure.
 7660: #    This function:
 7661: #     -   Increments the failure statistic counters.
 7662: #     -   Invokes Reply to send the error message to the client.
 7663: # Parameters:
 7664: #    fd       - File descriptor open on the client
 7665: #    reply    - Reply text to emit.
 7666: #    request  - The original request message (used by Reply
 7667: #               to debug if that's enabled.
 7668: # Implicit outputs:
 7669: #    $Failures- The number of failures is incremented.
 7670: #    Reply (invoked here) sends a message to the 
 7671: #    client:
 7672: #
 7673: sub Failure {
 7674:     my $fd      = shift;
 7675:     my $reply   = shift;
 7676:     my $request = shift;
 7677:    
 7678:     $Failures++;
 7679:     Reply($fd, $reply, $request);      # That's simple eh?
 7680: }
 7681: # ------------------------------------------------------------------ Log status
 7682: 
 7683: sub logstatus {
 7684:     &status("Doing logging");
 7685:     my $docdir=$perlvar{'lonDocRoot'};
 7686:     {
 7687: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
 7688:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
 7689:         $fh->close();
 7690:     }
 7691:     &status("Finished $$.txt");
 7692:     {
 7693: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
 7694: 	flock(LOG,LOCK_EX);
 7695: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
 7696: 	    .$status."\t".$lastlog."\t $keymode\n";
 7697: 	flock(LOG,LOCK_UN);
 7698: 	close(LOG);
 7699:     }
 7700:     &status("Finished logging");
 7701: }
 7702: 
 7703: sub initnewstatus {
 7704:     my $docdir=$perlvar{'lonDocRoot'};
 7705:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
 7706:     my $now=time();
 7707:     my $local=localtime($now);
 7708:     print $fh "LOND status $local - parent $$\n\n";
 7709:     opendir(DIR,"$docdir/lon-status/londchld");
 7710:     while (my $filename=readdir(DIR)) {
 7711:         unlink("$docdir/lon-status/londchld/$filename");
 7712:     }
 7713:     closedir(DIR);
 7714: }
 7715: 
 7716: # -------------------------------------------------------------- Status setting
 7717: 
 7718: sub status {
 7719:     my $what=shift;
 7720:     my $now=time;
 7721:     my $local=localtime($now);
 7722:     $status=$local.': '.$what;
 7723:     $0='lond: '.$what.' '.$local;
 7724: }
 7725: 
 7726: # -------------------------------------------------------------- Talk to lonsql
 7727: 
 7728: sub sql_reply {
 7729:     my ($cmd)=@_;
 7730:     my $answer=&sub_sql_reply($cmd);
 7731:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
 7732:     return $answer;
 7733: }
 7734: 
 7735: sub sub_sql_reply {
 7736:     my ($cmd)=@_;
 7737:     my $unixsock="mysqlsock";
 7738:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
 7739:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
 7740:                                       Type    => SOCK_STREAM,
 7741:                                       Timeout => 10)
 7742:        or return "con_lost";
 7743:     print $sclient "$cmd:$currentdomainid\n";
 7744:     my $answer=<$sclient>;
 7745:     chomp($answer);
 7746:     if (!$answer) { $answer="con_lost"; }
 7747:     return $answer;
 7748: }
 7749: 
 7750: # --------------------------------------- Is this the home server of an author?
 7751: 
 7752: sub ishome {
 7753:     my $author=shift;
 7754:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 7755:     my ($udom,$uname)=split(/\//,$author);
 7756:     my $proname=propath($udom,$uname);
 7757:     if (-e $proname) {
 7758: 	return 'owner';
 7759:     } else {
 7760:         return 'not_owner';
 7761:     }
 7762: }
 7763: 
 7764: # ======================================================= Continue main program
 7765: # ---------------------------------------------------- Fork once and dissociate
 7766: 
 7767: my $fpid=fork;
 7768: exit if $fpid;
 7769: die "Couldn't fork: $!" unless defined ($fpid);
 7770: 
 7771: POSIX::setsid() or die "Can't start new session: $!";
 7772: 
 7773: # ------------------------------------------------------- Write our PID on disk
 7774: 
 7775: my $execdir=$perlvar{'lonDaemons'};
 7776: open (PIDSAVE,">$execdir/logs/lond.pid");
 7777: print PIDSAVE "$$\n";
 7778: close(PIDSAVE);
 7779: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
 7780: &status('Starting');
 7781: 
 7782: 
 7783: 
 7784: # ----------------------------------------------------- Install signal handlers
 7785: 
 7786: 
 7787: $SIG{CHLD} = \&REAPER;
 7788: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 7789: $SIG{HUP}  = \&HUPSMAN;
 7790: $SIG{USR1} = \&checkchildren;
 7791: $SIG{USR2} = \&UpdateHosts;
 7792: 
 7793: #  Read the host hashes:
 7794: &Apache::lonnet::load_hosts_tab();
 7795: my %iphost = &Apache::lonnet::get_iphost(1);
 7796: 
 7797: $dist=`$perlvar{'lonDaemons'}/distprobe`;
 7798: 
 7799: my $arch = `uname -i`;
 7800: chomp($arch);
 7801: if ($arch eq 'unknown') {
 7802:     $arch = `uname -m`;
 7803:     chomp($arch);
 7804: }
 7805: 
 7806: unless (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
 7807:     &logthis('<font color="blue">No connectionrules table. Will fallback to loncapa.conf</font>');
 7808: }
 7809: 
 7810: # --------------------------------------------------------------
 7811: #   Accept connections.  When a connection comes in, it is validated
 7812: #   and if good, a child process is created to process transactions
 7813: #   along the connection.
 7814: 
 7815: while (1) {
 7816:     &status('Starting accept');
 7817:     $client = $server->accept() or next;
 7818:     &status('Accepted '.$client.' off to spawn');
 7819:     make_new_child($client);
 7820:     &status('Finished spawning');
 7821: }
 7822: 
 7823: sub make_new_child {
 7824:     my $pid;
 7825: #    my $cipher;     # Now global
 7826:     my $sigset;
 7827: 
 7828:     $client = shift;
 7829:     &status('Starting new child '.$client);
 7830:     &logthis('<font color="green"> Attempting to start child ('.$client.
 7831: 	     ")</font>");    
 7832:     # block signal for fork
 7833:     $sigset = POSIX::SigSet->new(SIGINT);
 7834:     sigprocmask(SIG_BLOCK, $sigset)
 7835:         or die "Can't block SIGINT for fork: $!\n";
 7836: 
 7837:     die "fork: $!" unless defined ($pid = fork);
 7838: 
 7839:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
 7840: 	                               # connection liveness.
 7841: 
 7842:     #
 7843:     #  Figure out who we're talking to so we can record the peer in 
 7844:     #  the pid hash.
 7845:     #
 7846:     my $caller = getpeername($client);
 7847:     my ($port,$iaddr);
 7848:     if (defined($caller) && length($caller) > 0) {
 7849: 	($port,$iaddr)=unpack_sockaddr_in($caller);
 7850:     } else {
 7851: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
 7852:     }
 7853:     if (defined($iaddr)) {
 7854: 	$clientip  = inet_ntoa($iaddr);
 7855: 	Debug("Connected with $clientip");
 7856:     } else {
 7857: 	&logthis("Unable to determine clientip");
 7858: 	$clientip='Unavailable';
 7859:     }
 7860:     
 7861:     if ($pid) {
 7862:         # Parent records the child's birth and returns.
 7863:         sigprocmask(SIG_UNBLOCK, $sigset)
 7864:             or die "Can't unblock SIGINT for fork: $!\n";
 7865:         $children{$pid} = $clientip;
 7866:         &status('Started child '.$pid);
 7867: 	close($client);
 7868:         return;
 7869:     } else {
 7870:         # Child can *not* return from this subroutine.
 7871:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
 7872:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
 7873:                                 #don't get intercepted
 7874:         $SIG{USR1}= \&logstatus;
 7875:         $SIG{ALRM}= \&timeout;
 7876: 	#
 7877: 	# Block sigpipe as it gets thrownon socket disconnect and we want to 
 7878: 	# deal with that as a read faiure instead.
 7879: 	#
 7880: 	my $blockset = POSIX::SigSet->new(SIGPIPE);
 7881: 	sigprocmask(SIG_BLOCK, $blockset);
 7882: 
 7883:         $lastlog='Forked ';
 7884:         $status='Forked';
 7885: 
 7886:         # unblock signals
 7887:         sigprocmask(SIG_UNBLOCK, $sigset)
 7888:             or die "Can't unblock SIGINT for fork: $!\n";
 7889: 
 7890: #        my $tmpsnum=0;            # Now global
 7891: #---------------------------------------------------- kerberos 5 initialization
 7892:         &Authen::Krb5::init_context();
 7893: 
 7894:         my $no_ets;
 7895:         if ($dist =~ /^(?:centos|rhes|scientific|oracle|rocky|alma)(\d+)/) {
 7896:             if ($1 >= 7) {
 7897:                 $no_ets = 1;
 7898:             }
 7899:         } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
 7900:             if (($1 eq '9.3') || ($1 >= 12.2)) {
 7901:                 $no_ets = 1; 
 7902:             }
 7903:         } elsif ($dist =~ /^sles(\d+)$/) {
 7904:             if ($1 > 11) {
 7905:                 $no_ets = 1;
 7906:             }
 7907:         } elsif ($dist =~ /^fedora(\d+)$/) {
 7908:             if ($1 < 7) {
 7909:                 $no_ets = 1;
 7910:             }
 7911:         }
 7912:         unless ($no_ets) {
 7913: 	    &Authen::Krb5::init_ets();
 7914: 	}
 7915: 
 7916: 	&status('Accepted connection');
 7917: # =============================================================================
 7918:             # do something with the connection
 7919: # -----------------------------------------------------------------------------
 7920: 	# see if we know client and 'check' for spoof IP by ineffective challenge
 7921: 
 7922: 	my $outsideip=$clientip;
 7923: 	if ($clientip eq '127.0.0.1') {
 7924: 	    $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
 7925: 	}
 7926: 	&ReadManagerTable();
 7927: 	my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
 7928: 	my $ismanager=($managers{$outsideip}    ne undef);
 7929: 	$clientname  = "[unknown]";
 7930: 	if($clientrec) {	# Establish client type.
 7931: 	    $ConnectionType = "client";
 7932: 	    $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
 7933: 	    if($ismanager) {
 7934: 		$ConnectionType = "both";
 7935: 	    }
 7936: 	} else {
 7937: 	    $ConnectionType = "manager";
 7938: 	    $clientname = $managers{$outsideip};
 7939: 	}
 7940: 	my $clientok;
 7941: 
 7942: 	if ($clientrec || $ismanager) {
 7943: 	    &status("Waiting for init from $clientip $clientname");
 7944: 	    &logthis('<font color="yellow">INFO: Connection, '.
 7945: 		     $clientip.
 7946: 		  " ($clientname) connection type = $ConnectionType </font>" );
 7947: 	    &status("Connecting $clientip  ($clientname))"); 
 7948: 	    my $remotereq=<$client>;
 7949: 	    chomp($remotereq);
 7950: 	    Debug("Got init: $remotereq");
 7951: 
 7952: 	    if ($remotereq =~ /^init/) {
 7953: 		&sethost("sethost:$perlvar{'lonHostID'}");
 7954: 		#
 7955: 		#  If the remote is attempting a local init... give that a try:
 7956: 		#
 7957: 		(my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
 7958:         # For LON-CAPA 2.9, the  client session will have sent its LON-CAPA
 7959:         # version when initiating the connection. For LON-CAPA 2.8 and older,
 7960:         # the version is retrieved from the global %loncaparevs in lonnet.pm.            
 7961:         # $clientversion contains path to keyfile if $inittype eq 'local'
 7962:         # it's overridden below in this case
 7963:         $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
 7964: 
 7965: 		# If the connection type is ssl, but I didn't get my
 7966: 		# certificate files yet, then I'll drop  back to 
 7967: 		# insecure (if allowed).
 7968: 
 7969:                 if ($inittype eq "ssl") {
 7970:                     my $context;
 7971:                     if ($clientsamedom) {
 7972:                         $context = 'dom';
 7973:                         if ($secureconf{'connfrom'}{'dom'} eq 'no') {
 7974:                             $inittype = "";
 7975:                         }
 7976:                     } elsif ($clientsameinst) {
 7977:                         $context = 'intdom';
 7978:                         if ($secureconf{'connfrom'}{'intdom'} eq 'no') {
 7979:                             $inittype = "";
 7980:                         }
 7981:                     } else {
 7982:                         $context = 'other';
 7983:                         if ($secureconf{'connfrom'}{'other'} eq 'no') {
 7984:                             $inittype = "";
 7985:                         }
 7986:                     }
 7987:                     if ($inittype eq '') {
 7988:                         &logthis("<font color=\"blue\"> Domain config set "
 7989:                                 ."to no ssl for $clientname (context: $context)"
 7990:                                 ." -- trying insecure auth</font>");
 7991:                     }
 7992:                 }
 7993: 
 7994: 		if($inittype eq "ssl") {
 7995: 		    my ($ca, $cert) = lonssl::CertificateFile;
 7996: 		    my $kfile       = lonssl::KeyFile;
 7997: 		    if((!$ca)   || 
 7998: 		       (!$cert) || 
 7999: 		       (!$kfile)) {
 8000: 			$inittype = ""; # This forces insecure attempt.
 8001: 			&logthis("<font color=\"blue\"> Certificates not "
 8002: 				 ."installed -- trying insecure auth</font>");
 8003: 		    } else {	# SSL certificates are in place so
 8004: 		    }		# Leave the inittype alone.
 8005: 		}
 8006: 
 8007: 		if($inittype eq "local") {
 8008:                     $clientversion = $perlvar{'lonVersion'};
 8009: 		    my $key = LocalConnection($client, $remotereq);
 8010: 		    if($key) {
 8011: 			Debug("Got local key $key");
 8012: 			$clientok     = 1;
 8013: 			my $cipherkey = pack("H32", $key);
 8014: 			$cipher       = new IDEA($cipherkey);
 8015: 			print $client "ok:local\n";
 8016: 			&logthis('<font color="green">'
 8017: 				 . "Successful local authentication </font>");
 8018: 			$keymode = "local"
 8019: 		    } else {
 8020: 			Debug("Failed to get local key");
 8021: 			$clientok = 0;
 8022: 			shutdown($client, 3);
 8023: 			close $client;
 8024: 		    }
 8025: 		} elsif ($inittype eq "ssl") {
 8026: 		    my $key = SSLConnection($client,$clientname);
 8027: 		    if ($key) {
 8028: 			$clientok = 1;
 8029: 			my $cipherkey = pack("H32", $key);
 8030: 			$cipher       = new IDEA($cipherkey);
 8031: 			&logthis('<font color="green">'
 8032: 				 ."Successfull ssl authentication with $clientname </font>");
 8033: 			$keymode = "ssl";
 8034: 	     
 8035: 		    } else {
 8036: 			$clientok = 0;
 8037: 			close $client;
 8038: 		    }
 8039: 	   
 8040: 		} else {
 8041: 		    my $ok = InsecureConnection($client);
 8042: 		    if($ok) {
 8043: 			$clientok = 1;
 8044: 			&logthis('<font color="green">'
 8045: 				 ."Successful insecure authentication with $clientname </font>");
 8046: 			print $client "ok\n";
 8047: 			$keymode = "insecure";
 8048: 		    } else {
 8049: 			&logthis('<font color="yellow">'
 8050: 				  ."Attempted insecure connection disallowed </font>");
 8051: 			close $client;
 8052: 			$clientok = 0;
 8053: 		    }
 8054: 		}
 8055: 	    } else {
 8056: 		&logthis(
 8057: 			 "<font color='blue'>WARNING: "
 8058: 			 ."$clientip failed to initialize: >$remotereq< </font>");
 8059: 		&status('No init '.$clientip);
 8060: 	    }
 8061: 	} else {
 8062: 	    &logthis(
 8063: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
 8064: 	    &status('Hung up on '.$clientip);
 8065: 	}
 8066:  
 8067: 	if ($clientok) {
 8068: # ---------------- New known client connecting, could mean machine online again
 8069: 	    if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip 
 8070: 		&& $clientip ne '127.0.0.1') {
 8071: 		&Apache::lonnet::reconlonc($clientname);
 8072: 	    }
 8073: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
 8074: 	    &status('Will listen to '.$clientname);
 8075: # ------------------------------------------------------------ Process requests
 8076: 	    my $keep_going = 1;
 8077: 	    my $user_input;
 8078: 
 8079: 	    while(($user_input = get_request) && $keep_going) {
 8080: 		alarm(120);
 8081: 		Debug("Main: Got $user_input\n");
 8082: 		$keep_going = &process_request($user_input);
 8083: 		alarm(0);
 8084: 		&status('Listening to '.$clientname." ($keymode)");
 8085: 	    }
 8086: 
 8087: # --------------------------------------------- client unknown or fishy, refuse
 8088: 	}  else {
 8089: 	    print $client "refused\n";
 8090: 	    $client->close();
 8091: 	    &logthis("<font color='blue'>WARNING: "
 8092: 		     ."Rejected client $clientip, closing connection</font>");
 8093: 	}
 8094:     }
 8095:     
 8096: # =============================================================================
 8097:     
 8098:     &logthis("<font color='red'>CRITICAL: "
 8099: 	     ."Disconnect from $clientip ($clientname)</font>");    
 8100: 
 8101: 
 8102:     # this exit is VERY important, otherwise the child will become
 8103:     # a producer of more and more children, forking yourself into
 8104:     # process death.
 8105:     exit;
 8106:     
 8107: }
 8108: 
 8109: #
 8110: #  Used to determine if a particular client is from the same domain
 8111: #  as the current server, or from the same internet domain, and
 8112: #  also if the client can host sessions for the domain's users.
 8113: #  A hash is populated with keys set to commands sent by the client
 8114: #  which may not be executed for this domain.
 8115: #
 8116: #  Optional input -- the client to check for domain and internet domain.
 8117: #  If not specified, defaults to the package variable: $clientname
 8118: #
 8119: #  If called in array context will not set package variables, but will
 8120: #  instead return an array of two values - (a) true if client is in the
 8121: #  same domain as the server, and (b) true if client is in the same 
 8122: #  internet domain.
 8123: #
 8124: #  If called in scalar context, sets package variables for current client:
 8125: #
 8126: #  $clienthomedom    - LonCAPA domain of homeID for client.
 8127: #  $clientsamedom    - LonCAPA domain same for this host and client.
 8128: #  $clientintdom     - LonCAPA "internet domain" for client.
 8129: #  $clientsameinst   - LonCAPA "internet domain" same for this host & client.
 8130: #  $clientremoteok   - If current domain permits hosting on this client: 1
 8131: #  %clientprohibited - Commands prohibited for domain's users for this client.
 8132: #
 8133: #  if the host and client have the same "internet domain", then the value
 8134: #  of $clientremoteok is not used, and no commands are prohibited.
 8135: #
 8136: #  returns 1 to indicate package variables have been set for current client.
 8137: #
 8138: 
 8139: sub set_client_info {
 8140:     my ($lonhost) = @_;
 8141:     $lonhost ||= $clientname;
 8142:     my $clienthost = &Apache::lonnet::hostname($lonhost);
 8143:     my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
 8144:     my $homedom = &Apache::lonnet::host_domain($clientserverhomeID);
 8145:     my $samedom = 0;
 8146:     if ($perlvar{'lonDefDomain'} eq $homedom) {
 8147:         $samedom = 1;
 8148:     }
 8149:     my $intdom = &Apache::lonnet::internet_dom($clientserverhomeID);
 8150:     my $sameinst = 0;
 8151:     if ($intdom ne '') {
 8152:         my $internet_names = &Apache::lonnet::get_internet_names($currenthostid);
 8153:         if (ref($internet_names) eq 'ARRAY') {
 8154:             if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 8155:                 $sameinst = 1;
 8156:             }
 8157:         }
 8158:     }
 8159:     if (wantarray) {
 8160:         return ($samedom,$sameinst);
 8161:     } else {
 8162:         $clienthomedom = $homedom;
 8163:         $clientsamedom = $samedom;
 8164:         $clientintdom = $intdom;
 8165:         $clientsameinst = $sameinst;
 8166:         if ($clientsameinst) {
 8167:             undef($clientremoteok);
 8168:             undef(%clientprohibited);
 8169:         } else {
 8170:             $clientremoteok = &get_remote_hostable($currentdomainid);
 8171:             %clientprohibited = &get_prohibited($currentdomainid);
 8172:         }
 8173:         return 1;
 8174:     }
 8175: }
 8176: 
 8177: #
 8178: #   Determine if a user is an author for the indicated domain.
 8179: #
 8180: # Parameters:
 8181: #    domain          - domain to check in .
 8182: #    user            - Name of user to check.
 8183: #
 8184: # Return:
 8185: #     1             - User is an author for domain.
 8186: #     0             - User is not an author for domain.
 8187: sub is_author {
 8188:     my ($domain, $user) = @_;
 8189: 
 8190:     &Debug("is_author: $user @ $domain");
 8191: 
 8192:     my $hashref = &tie_user_hash($domain, $user, "roles",
 8193: 				 &GDBM_READER());
 8194: 
 8195:     #  Author role should show up as a key /domain/_au
 8196: 
 8197:     my $value;
 8198:     if ($hashref) {
 8199: 
 8200: 	my $key    = "/$domain/_au";
 8201: 	if (defined($hashref)) {
 8202: 	    $value = $hashref->{$key};
 8203: 	    if(!untie_user_hash($hashref)) {
 8204: 		return 'error: ' .  ($!+0)." untie (GDBM) Failed";
 8205: 	    }
 8206: 	}
 8207: 	
 8208: 	if(defined($value)) {
 8209: 	    &Debug("$user @ $domain is an author");
 8210: 	}
 8211:     } else {
 8212: 	return 'error: '.($!+0)." tie (GDBM) Failed";
 8213:     }
 8214: 
 8215:     return defined($value);
 8216: }
 8217: #
 8218: #   Checks to see if the input roleput request was to set
 8219: # an author role.  If so, creates construction space 
 8220: # Parameters:
 8221: #    request   - The request sent to the rolesput subchunk.
 8222: #                We're looking for  /domain/_au
 8223: #    domain    - The domain in which the user is having roles doctored.
 8224: #    user      - Name of the user for which the role is being put.
 8225: #    authtype  - The authentication type associated with the user.
 8226: #
 8227: sub manage_permissions {
 8228:     my ($request, $domain, $user, $authtype) = @_;
 8229:     # See if the request is of the form /$domain/_au
 8230:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
 8231:         my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
 8232:         unless (-e $path) {        
 8233:            mkdir($path);
 8234:         }
 8235:         unless (-e $path.'/'.$user) {
 8236:            mkdir($path.'/'.$user);
 8237:         }
 8238:     }
 8239: }
 8240: 
 8241: 
 8242: #
 8243: #  Return the full path of a user password file, whether it exists or not.
 8244: # Parameters:
 8245: #   domain     - Domain in which the password file lives.
 8246: #   user       - name of the user.
 8247: # Returns:
 8248: #    Full passwd path:
 8249: #
 8250: sub password_path {
 8251:     my ($domain, $user) = @_;
 8252:     return &propath($domain, $user).'/passwd';
 8253: }
 8254: 
 8255: #   Password Filename
 8256: #   Returns the path to a passwd file given domain and user... only if
 8257: #  it exists.
 8258: # Parameters:
 8259: #   domain    - Domain in which to search.
 8260: #   user      - username.
 8261: # Returns:
 8262: #   - If the password file exists returns its path.
 8263: #   - If the password file does not exist, returns undefined.
 8264: #
 8265: sub password_filename {
 8266:     my ($domain, $user) = @_;
 8267: 
 8268:     Debug ("PasswordFilename called: dom = $domain user = $user");
 8269: 
 8270:     my $path  = &password_path($domain, $user);
 8271:     Debug("PasswordFilename got path: $path");
 8272:     if(-e $path) {
 8273: 	return $path;
 8274:     } else {
 8275: 	return undef;
 8276:     }
 8277: }
 8278: 
 8279: #
 8280: #   Rewrite the contents of the user's passwd file.
 8281: #  Parameters:
 8282: #    domain    - domain of the user.
 8283: #    name      - User's name.
 8284: #    contents  - New contents of the file.
 8285: #    saveold   - (optional). If true save old file in a passwd.bak file.
 8286: # Returns:
 8287: #   0    - Failed.
 8288: #   1    - Success.
 8289: #
 8290: sub rewrite_password_file {
 8291:     my ($domain, $user, $contents, $saveold) = @_;
 8292: 
 8293:     my $file = &password_filename($domain, $user);
 8294:     if (defined $file) {
 8295:         if ($saveold) {
 8296:             my $bakfile = $file.'.bak';
 8297:             if (CopyFile($file,$bakfile)) {
 8298:                 chmod(0400,$bakfile);
 8299:                 &logthis("Old password saved in passwd.bak for internally authenticated user: $user:$domain");
 8300:             } else {
 8301:                 &logthis("Failed to save old password in passwd.bak for internally authenticated user: $user:$domain");
 8302:             }
 8303:         }
 8304: 	my $pf = IO::File->new(">$file");
 8305: 	if($pf) {
 8306: 	    print $pf "$contents\n";
 8307: 	    return 1;
 8308: 	} else {
 8309: 	    return 0;
 8310: 	}
 8311:     } else {
 8312: 	return 0;
 8313:     }
 8314: 
 8315: }
 8316: 
 8317: #
 8318: #   get_auth_type - Determines the authorization type of a user in a domain.
 8319: 
 8320: #     Returns the authorization type or nouser if there is no such user.
 8321: #
 8322: sub get_auth_type {
 8323:     my ($domain, $user)  = @_;
 8324: 
 8325:     Debug("get_auth_type( $domain, $user ) \n");
 8326:     my $proname    = &propath($domain, $user); 
 8327:     my $passwdfile = "$proname/passwd";
 8328:     if( -e $passwdfile ) {
 8329: 	my $pf = IO::File->new($passwdfile);
 8330: 	my $realpassword = <$pf>;
 8331: 	chomp($realpassword);
 8332: 	Debug("Password info = $realpassword\n");
 8333: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
 8334: 	Debug("Authtype = $authtype, content = $contentpwd\n");
 8335: 	return "$authtype:$contentpwd";     
 8336:     } else {
 8337: 	Debug("Returning nouser");
 8338: 	return "nouser";
 8339:     }
 8340: }
 8341: 
 8342: #
 8343: #  Validate a user given their domain, name and password.  This utility
 8344: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
 8345: #  to validate the login credentials of a user.
 8346: # Parameters:
 8347: #    $domain    - The domain being logged into (this is required due to
 8348: #                 the capability for multihomed systems.
 8349: #    $user      - The name of the user being validated.
 8350: #    $password  - The user's propoposed password.
 8351: #
 8352: # Returns:
 8353: #     1        - The domain,user,pasword triplet corresponds to a valid
 8354: #                user.
 8355: #     0        - The domain,user,password triplet is not a valid user.
 8356: #
 8357: sub validate_user {
 8358:     my ($domain, $user, $password, $checkdefauth) = @_;
 8359: 
 8360:     # Why negative ~pi you may well ask?  Well this function is about
 8361:     # authentication, and therefore very important to get right.
 8362:     # I've initialized the flag that determines whether or not I've 
 8363:     # validated correctly to a value it's not supposed to get.
 8364:     # At the end of this function. I'll ensure that it's not still that
 8365:     # value so we don't just wind up returning some accidental value
 8366:     # as a result of executing an unforseen code path that
 8367:     # did not set $validated.  At the end of valid execution paths,
 8368:     # validated shoule be 1 for success or 0 for failuer.
 8369: 
 8370:     my $validated = -3.14159;
 8371: 
 8372:     #  How we authenticate is determined by the type of authentication
 8373:     #  the user has been assigned.  If the authentication type is
 8374:     #  "nouser", the user does not exist so we will return 0.
 8375: 
 8376:     my $contents = &get_auth_type($domain, $user);
 8377:     my ($howpwd, $contentpwd) = split(/:/, $contents);
 8378: 
 8379:     my $null = pack("C",0);	# Used by kerberos auth types.
 8380: 
 8381:     if ($howpwd eq 'nouser') {
 8382:         if ($checkdefauth) {
 8383:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 8384:             if ($domdefaults{'auth_def'} eq 'localauth') {
 8385:                 $howpwd = $domdefaults{'auth_def'};
 8386:                 $contentpwd = $domdefaults{'auth_arg_def'};
 8387:             } elsif ((($domdefaults{'auth_def'} eq 'krb4') || 
 8388:                       ($domdefaults{'auth_def'} eq 'krb5')) &&
 8389:                      ($domdefaults{'auth_arg_def'} ne '')) {
 8390:                 #
 8391:                 # Don't attempt authentication for username and password supplied
 8392:                 # for user without an account if uername contains @ to avoid
 8393:                 # call to &Authen::Krb5::parse_name() which will result in con_lost 
 8394:                 #
 8395:                 unless ($user =~ /\@/) {
 8396:                     $howpwd = $domdefaults{'auth_def'};
 8397:                     $contentpwd = $domdefaults{'auth_arg_def'};
 8398:                 }
 8399:             }
 8400:         }
 8401:     }
 8402:     if ($howpwd ne 'nouser') {
 8403: 	if($howpwd eq "internal") { # Encrypted is in local password file.
 8404:             if (length($contentpwd) == 13) {
 8405:                 $validated = (crypt($password,$contentpwd) eq $contentpwd);
 8406:                 if ($validated) {
 8407:                     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 8408:                     if ($domdefaults{'intauth_switch'}) {
 8409:                         my $ncpass = &hash_passwd($domain,$password);
 8410:                         my $saveold;
 8411:                         if ($domdefaults{'intauth_switch'} == 2) {
 8412:                             $saveold = 1;
 8413:                         }
 8414:                         if (&rewrite_password_file($domain,$user,"$howpwd:$ncpass",$saveold)) {
 8415:                             &update_passwd_history($user,$domain,$howpwd,'conversion');
 8416:                             &logthis("Validated password hashed with bcrypt for $user:$domain");
 8417:                         }
 8418:                     }
 8419:                 }
 8420:             } else {
 8421:                 $validated = &check_internal_passwd($password,$contentpwd,$domain,$user);
 8422:             }
 8423: 	}
 8424: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
 8425: 	    $contentpwd = (getpwnam($user))[1];
 8426: 	    if($contentpwd) {
 8427: 		if($contentpwd eq 'x') { # Shadow password file...
 8428: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
 8429: 		    open PWAUTH,  "|$pwauth_path" or
 8430: 			die "Cannot invoke authentication";
 8431: 		    print PWAUTH "$user\n$password\n";
 8432: 		    close PWAUTH;
 8433: 		    $validated = ! $?;
 8434: 
 8435: 		} else { 	         # Passwords in /etc/passwd. 
 8436: 		    $validated = (crypt($password,
 8437: 					$contentpwd) eq $contentpwd);
 8438: 		}
 8439: 	    } else {
 8440: 		$validated = 0;
 8441: 	    }
 8442: 	} elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
 8443:             my $checkwithkrb5 = 0;
 8444:             if ($dist =~/^fedora(\d+)$/) {
 8445:                 if ($1 > 11) {
 8446:                     $checkwithkrb5 = 1;
 8447:                 }
 8448:             } elsif ($dist =~ /^suse([\d.]+)$/) {
 8449:                 if ($1 > 11.1) {
 8450:                     $checkwithkrb5 = 1; 
 8451:                 }
 8452:             }
 8453:             if ($checkwithkrb5) {
 8454:                 $validated = &krb5_authen($password,$null,$user,$contentpwd);
 8455:             } else {
 8456:                 $validated = &krb4_authen($password,$null,$user,$contentpwd);
 8457:             }
 8458: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
 8459:             $validated = &krb5_authen($password,$null,$user,$contentpwd);
 8460: 	} elsif ($howpwd eq "localauth") { 
 8461: 	    #  Authenticate via installation specific authentcation method:
 8462: 	    $validated = &localauth::localauth($user, 
 8463: 					       $password, 
 8464: 					       $contentpwd,
 8465: 					       $domain);
 8466: 	    if ($validated < 0) {
 8467: 		&logthis("localauth for $contentpwd $user:$domain returned a $validated");
 8468: 		$validated = 0;
 8469: 	    }
 8470: 	} else {			# Unrecognized auth is also bad.
 8471: 	    $validated = 0;
 8472: 	}
 8473:     } else {
 8474: 	$validated = 0;
 8475:     }
 8476:     #
 8477:     #  $validated has the correct stat of the authentication:
 8478:     #
 8479: 
 8480:     unless ($validated != -3.14159) {
 8481: 	#  I >really really< want to know if this happens.
 8482: 	#  since it indicates that user authentication is badly
 8483: 	#  broken in some code path.
 8484:         #
 8485: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
 8486:     }
 8487:     return $validated;
 8488: }
 8489: 
 8490: sub check_internal_passwd {
 8491:     my ($plainpass,$stored,$domain,$user) = @_;
 8492:     my (undef,$method,@rest) = split(/!/,$stored);
 8493:     if ($method eq 'bcrypt') {
 8494:         my $result = &hash_passwd($domain,$plainpass,@rest);
 8495:         if ($result ne $stored) {
 8496:             return 0;
 8497:         }
 8498:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 8499:         if ($domdefaults{'intauth_check'}) {
 8500:             # Upgrade to a larger number of rounds if necessary
 8501:             my $defaultcost = $domdefaults{'intauth_cost'};
 8502:             if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
 8503:                 $defaultcost = 10;
 8504:             }
 8505:             if (int($rest[0])<int($defaultcost)) {
 8506:                 if ($domdefaults{'intauth_check'} == 1) { 
 8507:                     my $ncpass = &hash_passwd($domain,$plainpass);
 8508:                     if (&rewrite_password_file($domain,$user,"internal:$ncpass")) {
 8509:                         &update_passwd_history($user,$domain,'internal','update cost');
 8510:                         &logthis("Validated password hashed with bcrypt for $user:$domain");
 8511:                     }
 8512:                     return 1;
 8513:                 } elsif ($domdefaults{'intauth_check'} == 2) {
 8514:                     return 0;
 8515:                 }
 8516:             }
 8517:         } else {
 8518:             return 1;
 8519:         }
 8520:     }
 8521:     return 0;
 8522: }
 8523: 
 8524: sub get_last_authchg {
 8525:     my ($domain,$user) = @_;
 8526:     my $lastmod;
 8527:     my $logname = &propath($domain,$user).'/passwd.log';
 8528:     if (-e "$logname") {
 8529:         $lastmod = (stat("$logname"))[9];
 8530:     }
 8531:     return $lastmod;
 8532: }
 8533: 
 8534: sub krb4_authen {
 8535:     my ($password,$null,$user,$contentpwd) = @_;
 8536:     my $validated = 0;
 8537:     if (!($password =~ /$null/) ) {  # Null password not allowed.
 8538:         eval {
 8539:             require Authen::Krb4;
 8540:         };
 8541:         if (!$@) {
 8542:             my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
 8543:                                                        "",
 8544:                                                        $contentpwd,,
 8545:                                                        'krbtgt',
 8546:                                                        $contentpwd,
 8547:                                                        1,
 8548:                                                        $password);
 8549:             if(!$k4error) {
 8550:                 $validated = 1;
 8551:             } else {
 8552:                 $validated = 0;
 8553:                 &logthis('krb4: '.$user.', '.$contentpwd.', '.
 8554:                           &Authen::Krb4::get_err_txt($Authen::Krb4::error));
 8555:             }
 8556:         } else {
 8557:             $validated = krb5_authen($password,$null,$user,$contentpwd);
 8558:         }
 8559:     }
 8560:     return $validated;
 8561: }
 8562: 
 8563: sub krb5_authen {
 8564:     my ($password,$null,$user,$contentpwd) = @_;
 8565:     my $validated = 0;
 8566:     if(!($password =~ /$null/)) { # Null password not allowed.
 8567:         my $krbclient = &Authen::Krb5::parse_name($user.'@'
 8568:                                                   .$contentpwd);
 8569:         my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
 8570:         my $krbserver  = &Authen::Krb5::parse_name($krbservice);
 8571:         my $credentials= &Authen::Krb5::cc_default();
 8572:         $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
 8573:                                                             .$contentpwd));
 8574:         my $krbreturn;
 8575:         if (exists(&Authen::Krb5::get_init_creds_password)) {
 8576:             $krbreturn =
 8577:                 &Authen::Krb5::get_init_creds_password($krbclient,$password,
 8578:                                                           $krbservice);
 8579:             $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
 8580:         } else {
 8581:             $krbreturn  =
 8582:                 &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
 8583:                                                          $password,$credentials);
 8584:             $validated = ($krbreturn == 1);
 8585:         }
 8586:         if (!$validated) {
 8587:             &logthis('krb5: '.$user.', '.$contentpwd.', '.
 8588:                      &Authen::Krb5::error());
 8589:         }
 8590:     }
 8591:     return $validated;
 8592: }
 8593: 
 8594: sub addline {
 8595:     my ($fname,$hostid,$ip,$newline)=@_;
 8596:     my $contents;
 8597:     my $found=0;
 8598:     my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
 8599:     my $sh;
 8600:     if ($sh=IO::File->new("$fname.subscription")) {
 8601: 	while (my $subline=<$sh>) {
 8602: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
 8603: 	}
 8604: 	$sh->close();
 8605:     }
 8606:     $sh=IO::File->new(">$fname.subscription");
 8607:     if ($contents) { print $sh $contents; }
 8608:     if ($newline) { print $sh $newline; }
 8609:     $sh->close();
 8610:     return $found;
 8611: }
 8612: 
 8613: sub get_chat {
 8614:     my ($cdom,$cname,$udom,$uname,$group)=@_;
 8615: 
 8616:     my @entries=();
 8617:     my $namespace = 'nohist_chatroom';
 8618:     my $namespace_inroom = 'nohist_inchatroom';
 8619:     if ($group ne '') {
 8620:         $namespace .= '_'.$group;
 8621:         $namespace_inroom .= '_'.$group;
 8622:     }
 8623:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
 8624: 				 &GDBM_READER());
 8625:     if ($hashref) {
 8626: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
 8627: 	&untie_user_hash($hashref);
 8628:     }
 8629:     my @participants=();
 8630:     my $cutoff=time-60;
 8631:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
 8632: 			      &GDBM_WRCREAT());
 8633:     if ($hashref) {
 8634:         $hashref->{$uname.':'.$udom}=time;
 8635:         foreach my $user (sort(keys(%$hashref))) {
 8636: 	    if ($hashref->{$user}>$cutoff) {
 8637: 		push(@participants, 'active_participant:'.$user);
 8638:             }
 8639:         }
 8640:         &untie_user_hash($hashref);
 8641:     }
 8642:     return (@participants,@entries);
 8643: }
 8644: 
 8645: sub chat_add {
 8646:     my ($cdom,$cname,$newchat,$group)=@_;
 8647:     my @entries=();
 8648:     my $time=time;
 8649:     my $namespace = 'nohist_chatroom';
 8650:     my $logfile = 'chatroom.log';
 8651:     if ($group ne '') {
 8652:         $namespace .= '_'.$group;
 8653:         $logfile = 'chatroom_'.$group.'.log';
 8654:     }
 8655:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
 8656: 				 &GDBM_WRCREAT());
 8657:     if ($hashref) {
 8658: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
 8659: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
 8660: 	my ($thentime,$idnum)=split(/\_/,$lastid);
 8661: 	my $newid=$time.'_000000';
 8662: 	if ($thentime==$time) {
 8663: 	    $idnum=~s/^0+//;
 8664: 	    $idnum++;
 8665: 	    $idnum=substr('000000'.$idnum,-6,6);
 8666: 	    $newid=$time.'_'.$idnum;
 8667: 	}
 8668: 	$hashref->{$newid}=$newchat;
 8669: 	my $expired=$time-3600;
 8670: 	foreach my $comment (keys(%$hashref)) {
 8671: 	    my ($thistime) = ($comment=~/(\d+)\_/);
 8672: 	    if ($thistime<$expired) {
 8673: 		delete $hashref->{$comment};
 8674: 	    }
 8675: 	}
 8676: 	{
 8677: 	    my $proname=&propath($cdom,$cname);
 8678: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
 8679: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
 8680: 	    }
 8681: 	    close(CHATLOG);
 8682: 	}
 8683: 	&untie_user_hash($hashref);
 8684:     }
 8685: }
 8686: 
 8687: sub unsub {
 8688:     my ($fname,$clientip)=@_;
 8689:     my $result;
 8690:     my $unsubs = 0;		# Number of successful unsubscribes:
 8691: 
 8692: 
 8693:     # An old way subscriptions were handled was to have a 
 8694:     # subscription marker file:
 8695: 
 8696:     Debug("Attempting unlink of $fname.$clientname");
 8697:     if (unlink("$fname.$clientname")) {
 8698: 	$unsubs++;		# Successful unsub via marker file.
 8699:     } 
 8700: 
 8701:     # The more modern way to do it is to have a subscription list
 8702:     # file:
 8703: 
 8704:     if (-e "$fname.subscription") {
 8705: 	my $found=&addline($fname,$clientname,$clientip,'');
 8706: 	if ($found) { 
 8707: 	    $unsubs++;
 8708: 	}
 8709:     } 
 8710: 
 8711:     #  If either or both of these mechanisms succeeded in unsubscribing a 
 8712:     #  resource we can return ok:
 8713: 
 8714:     if($unsubs) {
 8715: 	$result = "ok\n";
 8716:     } else {
 8717: 	$result = "not_subscribed\n";
 8718:     }
 8719: 
 8720:     return $result;
 8721: }
 8722: 
 8723: sub currentversion {
 8724:     my $fname=shift;
 8725:     my $version=-1;
 8726:     my $ulsdir='';
 8727:     if ($fname=~/^(.+)\/[^\/]+$/) {
 8728:        $ulsdir=$1;
 8729:     }
 8730:     my ($fnamere1,$fnamere2);
 8731:     # remove version if already specified
 8732:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
 8733:     # get the bits that go before and after the version number
 8734:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
 8735: 	$fnamere1=$1;
 8736: 	$fnamere2='.'.$2;
 8737:     }
 8738:     if (-e $fname) { $version=1; }
 8739:     if (-e $ulsdir) {
 8740: 	if(-d $ulsdir) {
 8741: 	    if (opendir(LSDIR,$ulsdir)) {
 8742: 		my $ulsfn;
 8743: 		while ($ulsfn=readdir(LSDIR)) {
 8744: # see if this is a regular file (ignore links produced earlier)
 8745: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
 8746: 		    unless (-l $thisfile) {
 8747: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
 8748: 			    if ($1>$version) { $version=$1; }
 8749: 			}
 8750: 		    }
 8751: 		}
 8752: 		closedir(LSDIR);
 8753: 		$version++;
 8754: 	    }
 8755: 	}
 8756:     }
 8757:     return $version;
 8758: }
 8759: 
 8760: sub thisversion {
 8761:     my $fname=shift;
 8762:     my $version=-1;
 8763:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
 8764: 	$version=$1;
 8765:     }
 8766:     return $version;
 8767: }
 8768: 
 8769: sub subscribe {
 8770:     my ($userinput,$clientip)=@_;
 8771:     my $result;
 8772:     my ($cmd,$fname)=split(/:/,$userinput,2);
 8773:     my $ownership=&ishome($fname);
 8774:     if ($ownership eq 'owner') {
 8775: # explitly asking for the current version?
 8776:         unless (-e $fname) {
 8777:             my $currentversion=&currentversion($fname);
 8778: 	    if (&thisversion($fname)==$currentversion) {
 8779:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
 8780: 		    my $root=$1;
 8781:                     my $extension=$2;
 8782:                     symlink($root.'.'.$extension,
 8783:                             $root.'.'.$currentversion.'.'.$extension);
 8784:                     unless ($extension=~/\.meta$/) {
 8785:                        symlink($root.'.'.$extension.'.meta',
 8786:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
 8787: 		    }
 8788:                 }
 8789:             }
 8790:         }
 8791: 	if (-e $fname) {
 8792: 	    if (-d $fname) {
 8793: 		$result="directory\n";
 8794: 	    } else {
 8795: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
 8796: 		my $now=time;
 8797: 		my $found=&addline($fname,$clientname,$clientip,
 8798: 				   "$clientname:$clientip:$now\n");
 8799: 		if ($found) { $result="$fname\n"; }
 8800: 		# if they were subscribed to only meta data, delete that
 8801:                 # subscription, when you subscribe to a file you also get
 8802:                 # the metadata
 8803: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
 8804: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
 8805:                 my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
 8806:                 $protocol = 'http' if ($protocol ne 'https');
 8807: 		$fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
 8808: 		$result="$fname\n";
 8809: 	    }
 8810: 	} else {
 8811: 	    $result="not_found\n";
 8812: 	}
 8813:     } else {
 8814: 	$result="rejected\n";
 8815:     }
 8816:     return $result;
 8817: }
 8818: #  Change the passwd of a unix user.  The caller must have
 8819: #  first verified that the user is a loncapa user.
 8820: #
 8821: # Parameters:
 8822: #    user      - Unix user name to change.
 8823: #    pass      - New password for the user.
 8824: # Returns:
 8825: #    ok    - if success
 8826: #    other - Some meaningfule error message string.
 8827: # NOTE:
 8828: #    invokes a setuid script to change the passwd.
 8829: sub change_unix_password {
 8830:     my ($user, $pass) = @_;
 8831: 
 8832:     &Debug("change_unix_password");
 8833:     my $execdir=$perlvar{'lonDaemons'};
 8834:     &Debug("Opening lcpasswd pipeline");
 8835:     my $pf = IO::File->new("|$execdir/lcpasswd > "
 8836: 			   ."$perlvar{'lonDaemons'}"
 8837: 			   ."/logs/lcpasswd.log");
 8838:     print $pf "$user\n$pass\n$pass\n";
 8839:     close $pf;
 8840:     my $err = $?;
 8841:     return ($err < @passwderrors) ? $passwderrors[$err] : 
 8842: 	"pwchange_falure - unknown error";
 8843: 
 8844:     
 8845: }
 8846: 
 8847: 
 8848: sub make_passwd_file {
 8849:     my ($uname,$udom,$umode,$npass,$passfilename,$action)=@_;
 8850:     my $result="ok";
 8851:     if ($umode eq 'krb4' or $umode eq 'krb5') {
 8852: 	{
 8853: 	    my $pf = IO::File->new(">$passfilename");
 8854: 	    if ($pf) {
 8855: 		print $pf "$umode:$npass\n";
 8856:                 &update_passwd_history($uname,$udom,$umode,$action);
 8857: 	    } else {
 8858: 		$result = "pass_file_failed_error";
 8859: 	    }
 8860: 	}
 8861:     } elsif ($umode eq 'internal') {
 8862:         my $ncpass = &hash_passwd($udom,$npass);
 8863: 	{
 8864: 	    &Debug("Creating internal auth");
 8865: 	    my $pf = IO::File->new(">$passfilename");
 8866: 	    if($pf) {
 8867: 		print $pf "internal:$ncpass\n";
 8868:                 &update_passwd_history($uname,$udom,$umode,$action); 
 8869: 	    } else {
 8870: 		$result = "pass_file_failed_error";
 8871: 	    }
 8872: 	}
 8873:     } elsif ($umode eq 'localauth') {
 8874: 	{
 8875: 	    my $pf = IO::File->new(">$passfilename");
 8876: 	    if($pf) {
 8877: 		print $pf "localauth:$npass\n";
 8878:                 &update_passwd_history($uname,$udom,$umode,$action);
 8879: 	    } else {
 8880: 		$result = "pass_file_failed_error";
 8881: 	    }
 8882: 	}
 8883:     } elsif ($umode eq 'unix') {
 8884: 	&logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
 8885: 	$result="no_new_unix_accounts";
 8886:     } elsif ($umode eq 'none') {
 8887: 	{
 8888: 	    my $pf = IO::File->new("> $passfilename");
 8889: 	    if($pf) {
 8890: 		print $pf "none:\n";
 8891: 	    } else {
 8892: 		$result = "pass_file_failed_error";
 8893: 	    }
 8894: 	}
 8895:     } elsif ($umode eq 'lti') {
 8896:         my $pf = IO::File->new(">$passfilename");
 8897:         if($pf) {
 8898:             print $pf "lti:\n";
 8899:             &update_passwd_history($uname,$udom,$umode,$action);
 8900:         } else {
 8901:             $result = "pass_file_failed_error";
 8902:         }
 8903:     } else {
 8904: 	$result="auth_mode_error";
 8905:     }
 8906:     return $result;
 8907: }
 8908: 
 8909: sub convert_photo {
 8910:     my ($start,$dest)=@_;
 8911:     system("convert $start $dest");
 8912: }
 8913: 
 8914: sub sethost {
 8915:     my ($remotereq) = @_;
 8916:     my (undef,$hostid)=split(/:/,$remotereq);
 8917:     # ignore sethost if we are already correct
 8918:     if ($hostid eq $currenthostid) {
 8919: 	return 'ok';
 8920:     }
 8921: 
 8922:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
 8923:     if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'}) 
 8924: 	eq &Apache::lonnet::get_host_ip($hostid)) {
 8925: 	$currenthostid  =$hostid;
 8926: 	$currentdomainid=&Apache::lonnet::host_domain($hostid);
 8927:         &set_client_info();
 8928: #	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
 8929:     } else {
 8930: 	&logthis("Requested host id $hostid not an alias of ".
 8931: 		 $perlvar{'lonHostID'}." refusing connection");
 8932: 	return 'unable_to_set';
 8933:     }
 8934:     return 'ok';
 8935: }
 8936: 
 8937: sub version {
 8938:     my ($userinput)=@_;
 8939:     $remoteVERSION=(split(/:/,$userinput))[1];
 8940:     return "version:$VERSION";
 8941: }
 8942: 
 8943: sub get_usersession_config {
 8944:     my ($dom,$name) = @_;
 8945:     my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
 8946:     if (defined($cached)) {
 8947:         return $usersessionconf;
 8948:     } else {
 8949:         my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
 8950:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
 8951:         return $domconfig{'usersessions'};
 8952:     }
 8953:     return;
 8954: }
 8955: 
 8956: sub get_usersearch_config {
 8957:     my ($dom,$name) = @_;
 8958:     my ($usersearchconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
 8959:     if (defined($cached)) {
 8960:         return $usersearchconf;
 8961:     } else {
 8962:         my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$dom);
 8963:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'directorysrch'},600);
 8964:         return $domconfig{'directorysrch'};
 8965:     }
 8966:     return;
 8967: }
 8968: 
 8969: sub get_prohibited {
 8970:     my ($dom) = @_;
 8971:     my $name = 'trust';
 8972:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
 8973:     unless (defined($cached)) {
 8974:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$dom);
 8975:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'trust'},3600);
 8976:         $trustconfig = $domconfig{'trust'};
 8977:     }
 8978:     my %prohibited;
 8979:     if (ref($trustconfig)) {
 8980:         foreach my $prefix (keys(%{$trustconfig})) {
 8981:             if (ref($trustconfig->{$prefix}) eq 'HASH') {
 8982:                 my $reject;
 8983:                 if (ref($trustconfig->{$prefix}->{'exc'}) eq 'ARRAY') {
 8984:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'exc'}})) {
 8985:                         $reject = 1;
 8986:                     }
 8987:                 }
 8988:                 if (ref($trustconfig->{$prefix}->{'inc'}) eq 'ARRAY') {
 8989:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'inc'}})) {
 8990:                         $reject = 0;
 8991:                     } else {
 8992:                         $reject = 1;
 8993:                     }
 8994:                 }
 8995:                 if ($reject) {
 8996:                     $prohibited{$prefix} = 1;
 8997:                 }
 8998:             }
 8999:         }
 9000:     }
 9001:     return %prohibited;
 9002: }
 9003: 
 9004: sub get_remote_hostable {
 9005:     my ($dom) = @_;
 9006:     my $result;
 9007:     if ($clientintdom) {
 9008:         $result = 1;
 9009:         my $remsessconf = &get_usersession_config($dom,'remotesession');
 9010:         if (ref($remsessconf) eq 'HASH') {
 9011:             if (ref($remsessconf->{'remote'}) eq 'HASH') {
 9012:                 if (ref($remsessconf->{'remote'}->{'excludedomain'}) eq 'ARRAY') {
 9013:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'excludedomain'}})) {
 9014:                         $result = 0;
 9015:                     }
 9016:                 }
 9017:                 if (ref($remsessconf->{'remote'}->{'includedomain'}) eq 'ARRAY') {
 9018:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'includedomain'}})) {
 9019:                         $result = 1;
 9020:                     } else {
 9021:                         $result = 0;
 9022:                     }
 9023:                 }
 9024:             }
 9025:         }
 9026:     }
 9027:     return $result;
 9028: }
 9029: 
 9030: sub distro_and_arch {
 9031:     return $dist.':'.$arch;
 9032: }
 9033: 
 9034: # ----------------------------------- POD (plain old documentation, CPAN style)
 9035: 
 9036: =head1 NAME
 9037: 
 9038: lond - "LON Daemon" Server (port "LOND" 5663)
 9039: 
 9040: =head1 SYNOPSIS
 9041: 
 9042: Usage: B<lond>
 9043: 
 9044: Should only be run as user=www.  This is a command-line script which
 9045: is invoked by B<loncron>.  There is no expectation that a typical user
 9046: will manually start B<lond> from the command-line.  (In other words,
 9047: DO NOT START B<lond> YOURSELF.)
 9048: 
 9049: =head1 DESCRIPTION
 9050: 
 9051: There are two characteristics associated with the running of B<lond>,
 9052: PROCESS MANAGEMENT (starting, stopping, handling child processes)
 9053: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
 9054: subscriptions, etc).  These are described in two large
 9055: sections below.
 9056: 
 9057: B<PROCESS MANAGEMENT>
 9058: 
 9059: Preforker - server who forks first. Runs as a daemon. HUPs.
 9060: Uses IDEA encryption
 9061: 
 9062: B<lond> forks off children processes that correspond to the other servers
 9063: in the network.  Management of these processes can be done at the
 9064: parent process level or the child process level.
 9065: 
 9066: B<logs/lond.log> is the location of log messages.
 9067: 
 9068: The process management is now explained in terms of linux shell commands,
 9069: subroutines internal to this code, and signal assignments:
 9070: 
 9071: =over 4
 9072: 
 9073: =item *
 9074: 
 9075: PID is stored in B<logs/lond.pid>
 9076: 
 9077: This is the process id number of the parent B<lond> process.
 9078: 
 9079: =item *
 9080: 
 9081: SIGTERM and SIGINT
 9082: 
 9083: Parent signal assignment:
 9084:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 9085: 
 9086: Child signal assignment:
 9087:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
 9088: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
 9089:  to restart a new child.)
 9090: 
 9091: Command-line invocations:
 9092:  B<kill> B<-s> SIGTERM I<PID>
 9093:  B<kill> B<-s> SIGINT I<PID>
 9094: 
 9095: Subroutine B<HUNTSMAN>:
 9096:  This is only invoked for the B<lond> parent I<PID>.
 9097: This kills all the children, and then the parent.
 9098: The B<lonc.pid> file is cleared.
 9099: 
 9100: =item *
 9101: 
 9102: SIGHUP
 9103: 
 9104: Current bug:
 9105:  This signal can only be processed the first time
 9106: on the parent process.  Subsequent SIGHUP signals
 9107: have no effect.
 9108: 
 9109: Parent signal assignment:
 9110:  $SIG{HUP}  = \&HUPSMAN;
 9111: 
 9112: Child signal assignment:
 9113:  none (nothing happens)
 9114: 
 9115: Command-line invocations:
 9116:  B<kill> B<-s> SIGHUP I<PID>
 9117: 
 9118: Subroutine B<HUPSMAN>:
 9119:  This is only invoked for the B<lond> parent I<PID>,
 9120: This kills all the children, and then the parent.
 9121: The B<lond.pid> file is cleared.
 9122: 
 9123: =item *
 9124: 
 9125: SIGUSR1
 9126: 
 9127: Parent signal assignment:
 9128:  $SIG{USR1} = \&USRMAN;
 9129: 
 9130: Child signal assignment:
 9131:  $SIG{USR1}= \&logstatus;
 9132: 
 9133: Command-line invocations:
 9134:  B<kill> B<-s> SIGUSR1 I<PID>
 9135: 
 9136: Subroutine B<USRMAN>:
 9137:  When invoked for the B<lond> parent I<PID>,
 9138: SIGUSR1 is sent to all the children, and the status of
 9139: each connection is logged.
 9140: 
 9141: =item *
 9142: 
 9143: SIGUSR2
 9144: 
 9145: Parent Signal assignment:
 9146:     $SIG{USR2} = \&UpdateHosts
 9147: 
 9148: Child signal assignment:
 9149:     NONE
 9150: 
 9151: 
 9152: =item *
 9153: 
 9154: SIGCHLD
 9155: 
 9156: Parent signal assignment:
 9157:  $SIG{CHLD} = \&REAPER;
 9158: 
 9159: Child signal assignment:
 9160:  none
 9161: 
 9162: Command-line invocations:
 9163:  B<kill> B<-s> SIGCHLD I<PID>
 9164: 
 9165: Subroutine B<REAPER>:
 9166:  This is only invoked for the B<lond> parent I<PID>.
 9167: Information pertaining to the child is removed.
 9168: The socket port is cleaned up.
 9169: 
 9170: =back
 9171: 
 9172: B<SERVER-SIDE ACTIVITIES>
 9173: 
 9174: Server-side information can be accepted in an encrypted or non-encrypted
 9175: method.
 9176: 
 9177: =over 4
 9178: 
 9179: =item ping
 9180: 
 9181: Query a client in the hosts.tab table; "Are you there?"
 9182: 
 9183: =item pong
 9184: 
 9185: Respond to a ping query.
 9186: 
 9187: =item ekey
 9188: 
 9189: Read in encrypted key, make cipher.  Respond with a buildkey.
 9190: 
 9191: =item load
 9192: 
 9193: Respond with CPU load based on a computation upon /proc/loadavg.
 9194: 
 9195: =item currentauth
 9196: 
 9197: Reply with current authentication information (only over an
 9198: encrypted channel).
 9199: 
 9200: =item auth
 9201: 
 9202: Only over an encrypted channel, reply as to whether a user's
 9203: authentication information can be validated.
 9204: 
 9205: =item passwd
 9206: 
 9207: Allow for a password to be set.
 9208: 
 9209: =item makeuser
 9210: 
 9211: Make a user.
 9212: 
 9213: =item changeuserauth
 9214: 
 9215: Allow for authentication mechanism and password to be changed.
 9216: 
 9217: =item home
 9218: 
 9219: Respond to a question "are you the home for a given user?"
 9220: 
 9221: =item update
 9222: 
 9223: Update contents of a subscribed resource.
 9224: 
 9225: =item unsubscribe
 9226: 
 9227: The server is unsubscribing from a resource.
 9228: 
 9229: =item subscribe
 9230: 
 9231: The server is subscribing to a resource.
 9232: 
 9233: =item log
 9234: 
 9235: Place in B<logs/lond.log>
 9236: 
 9237: =item put
 9238: 
 9239: stores hash in namespace
 9240: 
 9241: =item rolesput
 9242: 
 9243: put a role into a user's environment
 9244: 
 9245: =item get
 9246: 
 9247: returns hash with keys from array
 9248: reference filled in from namespace
 9249: 
 9250: =item eget
 9251: 
 9252: returns hash with keys from array
 9253: reference filled in from namesp (encrypts the return communication)
 9254: 
 9255: =item rolesget
 9256: 
 9257: get a role from a user's environment
 9258: 
 9259: =item del
 9260: 
 9261: deletes keys out of array from namespace
 9262: 
 9263: =item keys
 9264: 
 9265: returns namespace keys
 9266: 
 9267: =item dump
 9268: 
 9269: dumps the complete (or key matching regexp) namespace into a hash
 9270: 
 9271: =item store
 9272: 
 9273: stores hash permanently
 9274: for this url; hashref needs to be given and should be a \%hashname; the
 9275: remaining args aren't required and if they aren't passed or are '' they will
 9276: be derived from the ENV
 9277: 
 9278: =item restore
 9279: 
 9280: returns a hash for a given url
 9281: 
 9282: =item querysend
 9283: 
 9284: Tells client about the lonsql process that has been launched in response
 9285: to a sent query.
 9286: 
 9287: =item queryreply
 9288: 
 9289: Accept information from lonsql and make appropriate storage in temporary
 9290: file space.
 9291: 
 9292: =item idput
 9293: 
 9294: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
 9295: for each student, defined perhaps by the institutional Registrar.)
 9296: 
 9297: =item idget
 9298: 
 9299: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
 9300: for each student, defined perhaps by the institutional Registrar.)
 9301: 
 9302: =item iddel
 9303: 
 9304: Deletes one or more ids in a domain's id database.
 9305: 
 9306: =item tmpput
 9307: 
 9308: Accept and store information in temporary space.
 9309: 
 9310: =item tmpget
 9311: 
 9312: Send along temporarily stored information.
 9313: 
 9314: =item ls
 9315: 
 9316: List part of a user's directory.
 9317: 
 9318: =item pushtable
 9319: 
 9320: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
 9321: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
 9322: must be restored manually in case of a problem with the new table file.
 9323: pushtable requires that the request be encrypted and validated via
 9324: ValidateManager.  The form of the command is:
 9325: enc:pushtable tablename <tablecontents> \n
 9326: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
 9327: cleartext newline.
 9328: 
 9329: =item Hanging up (exit or init)
 9330: 
 9331: What to do when a client tells the server that they (the client)
 9332: are leaving the network.
 9333: 
 9334: =item unknown command
 9335: 
 9336: If B<lond> is sent an unknown command (not in the list above),
 9337: it replys to the client "unknown_cmd".
 9338: 
 9339: 
 9340: =item UNKNOWN CLIENT
 9341: 
 9342: If the anti-spoofing algorithm cannot verify the client,
 9343: the client is rejected (with a "refused" message sent
 9344: to the client, and the connection is closed.
 9345: 
 9346: =back
 9347: 
 9348: =head1 PREREQUISITES
 9349: 
 9350: IO::Socket
 9351: IO::File
 9352: Apache::File
 9353: POSIX
 9354: Crypt::IDEA
 9355: GDBM_File
 9356: Authen::Krb4
 9357: Authen::Krb5
 9358: 
 9359: =head1 COREQUISITES
 9360: 
 9361: none
 9362: 
 9363: =head1 OSNAMES
 9364: 
 9365: linux
 9366: 
 9367: =head1 SCRIPT CATEGORIES
 9368: 
 9369: Server/Process
 9370: 
 9371: =cut
 9372: 
 9373: 
 9374: =pod
 9375: 
 9376: =head1 LOG MESSAGES
 9377: 
 9378: The messages below can be emitted in the lond log.  This log is located
 9379: in ~httpd/perl/logs/lond.log  Many log messages have HTML encapsulation
 9380: to provide coloring if examined from inside a web page. Some do not.
 9381: Where color is used, the colors are; Red for sometihhng to get excited
 9382: about and to follow up on. Yellow for something to keep an eye on to
 9383: be sure it does not get worse, Green,and Blue for informational items.
 9384: 
 9385: In the discussions below, sometimes reference is made to ~httpd
 9386: when describing file locations.  There isn't really an httpd 
 9387: user, however there is an httpd directory that gets installed in the
 9388: place that user home directories go.  On linux, this is usually
 9389: (always?) /home/httpd.
 9390: 
 9391: 
 9392: Some messages are colorless.  These are usually (not always)
 9393: Green/Blue color level messages.
 9394: 
 9395: =over 2
 9396: 
 9397: =item (Red)  LocalConnection rejecting non local: <ip> ne 127.0.0.1
 9398: 
 9399: A local connection negotiation was attempted by
 9400: a host whose IP address was not 127.0.0.1.
 9401: The socket is closed and the child will exit.
 9402: lond has three ways to establish an encyrption
 9403: key with a client:
 9404: 
 9405: =over 2
 9406: 
 9407: =item local 
 9408: 
 9409: The key is written and read from a file.
 9410: This is only valid for connections from localhost.
 9411: 
 9412: =item insecure 
 9413: 
 9414: The key is generated by the server and
 9415: transmitted to the client.
 9416: 
 9417: =item  ssl (secure)
 9418: 
 9419: An ssl connection is negotiated with the client,
 9420: the key is generated by the server and sent to the 
 9421: client across this ssl connection before the
 9422: ssl connectionis terminated and clear text
 9423: transmission resumes.
 9424: 
 9425: =back
 9426: 
 9427: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
 9428: 
 9429: The client is local but has not sent an initialization
 9430: string that is the literal "init:local"  The connection
 9431: is closed and the child exits.
 9432: 
 9433: =item Red CRITICAL Can't get key file <error>        
 9434: 
 9435: SSL key negotiation is being attempted but the call to
 9436: lonssl::KeyFile failed.  This usually means that the
 9437: configuration file is not correctly defining or protecting
 9438: the directories/files lonCertificateDirectory or
 9439: lonnetPrivateKey
 9440: <error> is a string that describes the reason that
 9441: the key file could not be located.
 9442: 
 9443: =item (Red) CRITICAL  Can't get certificates <error>  
 9444: 
 9445: SSL key negotiation failed because we were not able to retrives our certificate
 9446: or the CA's certificate in the call to lonssl::CertificateFile
 9447: <error> is the textual reason this failed.  Usual reasons:
 9448: 
 9449: =over 2
 9450: 
 9451: =item Apache config file for loncapa  incorrect:
 9452: 
 9453: one of the variables 
 9454: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
 9455: undefined or incorrect
 9456: 
 9457: =item Permission error:
 9458: 
 9459: The directory pointed to by lonCertificateDirectory is not readable by lond
 9460: 
 9461: =item Permission error:
 9462: 
 9463: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
 9464: 
 9465: =item Installation error:                         
 9466: 
 9467: Either the certificate authority file or the certificate have not
 9468: been installed in lonCertificateDirectory.
 9469: 
 9470: =item (Red) CRITICAL SSL Socket promotion failed:  <err> 
 9471: 
 9472: The promotion of the connection from plaintext to SSL failed
 9473: <err> is the reason for the failure.  There are two
 9474: system calls involved in the promotion (one of which failed), 
 9475: a dup to produce
 9476: a second fd on the raw socket over which the encrypted data
 9477: will flow and IO::SOcket::SSL->new_from_fd which creates
 9478: the SSL connection on the duped fd.
 9479: 
 9480: =item (Blue)   WARNING client did not respond to challenge 
 9481: 
 9482: This occurs on an insecure (non SSL) connection negotiation request.
 9483: lond generates some number from the time, the PID and sends it to
 9484: the client.  The client must respond by echoing this information back.
 9485: If the client does not do so, that's a violation of the challenge
 9486: protocols and the connection will be failed.
 9487: 
 9488: =item (Red) No manager table. Nobody can manage!!    
 9489: 
 9490: lond has the concept of privileged hosts that
 9491: can perform remote management function such
 9492: as update the hosts.tab.   The manager hosts
 9493: are described in the 
 9494: ~httpd/lonTabs/managers.tab file.
 9495: this message is logged if this file is missing.
 9496: 
 9497: 
 9498: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
 9499: 
 9500: Reports the successful parse and registration
 9501: of a specific manager. 
 9502: 
 9503: =item Green existing host <clustername:dnsname>  
 9504: 
 9505: The manager host is already defined in the hosts.tab
 9506: the information in that table, rather than the info in the
 9507: manager table will be used to determine the manager's ip.
 9508: 
 9509: =item (Red) Unable to craete <filename>                 
 9510: 
 9511: lond has been asked to create new versions of an administrative
 9512: file (by a manager).  When this is done, the new file is created
 9513: in a temp file and then renamed into place so that there are always
 9514: usable administrative files, even if the update fails.  This failure
 9515: message means that the temp file could not be created.
 9516: The update is abandoned, and the old file is available for use.
 9517: 
 9518: =item (Green) CopyFile from <oldname> to <newname> failed
 9519: 
 9520: In an update of administrative files, the copy of the existing file to a
 9521: backup file failed.  The installation of the new file may still succeed,
 9522: but there will not be a back up file to rever to (this should probably
 9523: be yellow).
 9524: 
 9525: =item (Green) Pushfile: backed up <oldname> to <newname>
 9526: 
 9527: See above, the backup of the old administrative file succeeded.
 9528: 
 9529: =item (Red)  Pushfile: Unable to install <filename> <reason>
 9530: 
 9531: The new administrative file could not be installed.  In this case,
 9532: the old administrative file is still in use.
 9533: 
 9534: =item (Green) Installed new < filename>.                      
 9535: 
 9536: The new administrative file was successfullly installed.                                               
 9537: 
 9538: =item (Red) Reinitializing lond pid=<pid>                    
 9539: 
 9540: The lonc child process <pid> will be sent a USR2 
 9541: signal.
 9542: 
 9543: =item (Red) Reinitializing self                                    
 9544: 
 9545: We've been asked to re-read our administrative files,and
 9546: are doing so.
 9547: 
 9548: =item (Yellow) error:Invalid process identifier <ident>  
 9549: 
 9550: A reinit command was received, but the target part of the 
 9551: command was not valid.  It must be either
 9552: 'lond' or 'lonc' but was <ident>
 9553: 
 9554: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
 9555: 
 9556: Checking to see if lond has been handed a valid edit
 9557: command.  It is possible the edit command is not valid
 9558: in that case there are no log messages to indicate that.
 9559: 
 9560: =item Result of password change for  <username> pwchange_success
 9561: 
 9562: The password for <username> was
 9563: successfully changed.
 9564: 
 9565: =item Unable to open <user> passwd to change password
 9566: 
 9567: Could not rewrite the 
 9568: internal password file for a user
 9569: 
 9570: =item Result of password change for <user> : <result>
 9571: 
 9572: A unix password change for <user> was attempted 
 9573: and the pipe returned <result>  
 9574: 
 9575: =item LWP GET: <message> for <fname> (<remoteurl>)
 9576: 
 9577: The lightweight process fetch for a resource failed
 9578: with <message> the local filename that should
 9579: have existed/been created was  <fname> the
 9580: corresponding URI: <remoteurl>  This is emitted in several
 9581: places.
 9582: 
 9583: =item Unable to move <transname> to <destname>     
 9584: 
 9585: From fetch_user_file_handler - the user file was replicated but could not
 9586: be mv'd to its final location.
 9587: 
 9588: =item Looking for <domain> <username>              
 9589: 
 9590: From user_has_session_handler - This should be a Debug call instead
 9591: it indicates lond is about to check whether the specified user has a 
 9592: session active on the specified domain on the local host.
 9593: 
 9594: =item Client <ip> (<name>) hanging up: <input>     
 9595: 
 9596: lond has been asked to exit by its client.  The <ip> and <name> identify the
 9597: client systemand <input> is the full exit command sent to the server.
 9598: 
 9599: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
 9600: 
 9601: A lond child terminated.  NOte that this termination can also occur when the
 9602: child receives the QUIT or DIE signals.  <pid> is the process id of the child,
 9603: <hostname> the host lond is working for, and <message> the reason the child died
 9604: to the best of our ability to get it (I would guess that any numeric value
 9605: represents and errno value).  This is immediately followed by
 9606: 
 9607: =item  Famous last words: Catching exception - <log> 
 9608: 
 9609: Where log is some recent information about the state of the child.
 9610: 
 9611: =item Red CRITICAL: TIME OUT <pid>                     
 9612: 
 9613: Some timeout occured for server <pid>.  THis is normally a timeout on an LWP
 9614: doing an HTTP::GET.
 9615: 
 9616: =item child <pid> died                              
 9617: 
 9618: The reaper caught a SIGCHILD for the lond child process <pid>
 9619: This should be modified to also display the IP of the dying child
 9620: $children{$pid}
 9621: 
 9622: =item Unknown child 0 died                           
 9623: A child died but the wait for it returned a pid of zero which really should not
 9624: ever happen. 
 9625: 
 9626: =item Child <which> - <pid> looks like we missed it's death 
 9627: 
 9628: When a sigchild is received, the reaper process checks all children to see if they are
 9629: alive.  If children are dying quite quickly, the lack of signal queuing can mean
 9630: that a signal hearalds the death of more than one child.  If so this message indicates
 9631: which other one died. <which> is the ip of a dead child
 9632: 
 9633: =item Free socket: <shutdownretval>                
 9634: 
 9635: The HUNTSMAN sub was called due to a SIGINT in a child process.  The socket is being shutdown.
 9636: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
 9637: to return anything. This is followed by: 
 9638: 
 9639: =item Red CRITICAL: Shutting down                       
 9640: 
 9641: Just prior to exit.
 9642: 
 9643: =item Free socket: <shutdownretval>                 
 9644: 
 9645: The HUPSMAN sub was called due to a SIGHUP.  all children get killsed, and lond execs itself.
 9646: This is followed by:
 9647: 
 9648: =item (Red) CRITICAL: Restarting                         
 9649: 
 9650: lond is about to exec itself to restart.
 9651: 
 9652: =item (Blue) Updating connections                        
 9653: 
 9654: (In response to a USR2).  All the children (except the one for localhost)
 9655: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
 9656: 
 9657: =item (Blue) UpdateHosts killing child <pid> for ip <ip>   
 9658: 
 9659: Due to USR2 as above.
 9660: 
 9661: =item (Green) keeping child for ip <ip> (pid = <pid>)    
 9662: 
 9663: In response to USR2 as above, the child indicated is not being restarted because
 9664: it's assumed that we'll always need a child for the localhost.
 9665: 
 9666: 
 9667: =item Going to check on the children                
 9668: 
 9669: Parent is about to check on the health of the child processes.
 9670: Note that this is in response to a USR1 sent to the parent lond.
 9671: there may be one or more of the next two messages:
 9672: 
 9673: =item <pid> is dead                                 
 9674: 
 9675: A child that we have in our child hash as alive has evidently died.
 9676: 
 9677: =item  Child <pid> did not respond                   
 9678: 
 9679: In the health check the child <pid> did not update/produce a pid_.txt
 9680: file when sent it's USR1 signal.  That process is killed with a 9 signal, as it's
 9681: assumed to be hung in some un-fixable way.
 9682: 
 9683: =item Finished checking children                   
 9684: 
 9685: Master processs's USR1 processing is cojmplete.
 9686: 
 9687: =item (Red) CRITICAL: ------- Starting ------            
 9688: 
 9689: (There are more '-'s on either side).  Lond has forked itself off to 
 9690: form a new session and is about to start actual initialization.
 9691: 
 9692: =item (Green) Attempting to start child (<client>)       
 9693: 
 9694: Started a new child process for <client>.  Client is IO::Socket object
 9695: connected to the child.  This was as a result of a TCP/IP connection from a client.
 9696: 
 9697: =item Unable to determine who caller was, getpeername returned nothing
 9698: 
 9699: In child process initialization.  either getpeername returned undef or
 9700: a zero sized object was returned.  Processing continues, but in my opinion,
 9701: this should be cause for the child to exit.
 9702: 
 9703: =item Unable to determine clientip                  
 9704: 
 9705: In child process initialization.  The peer address from getpeername was not defined.
 9706: The client address is stored as "Unavailable" and processing continues.
 9707: 
 9708: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
 9709: 
 9710: In child initialization.  A good connectionw as received from <ip>.
 9711: 
 9712: =over 2
 9713: 
 9714: =item <name> 
 9715: 
 9716: is the name of the client from hosts.tab.
 9717: 
 9718: =item <type> 
 9719: 
 9720: Is the connection type which is either 
 9721: 
 9722: =over 2
 9723: 
 9724: =item manager 
 9725: 
 9726: The connection is from a manager node, not in hosts.tab
 9727: 
 9728: =item client  
 9729: 
 9730: the connection is from a non-manager in the hosts.tab
 9731: 
 9732: =item both
 9733: 
 9734: The connection is from a manager in the hosts.tab.
 9735: 
 9736: =back
 9737: 
 9738: =back
 9739: 
 9740: =item (Blue) Certificates not installed -- trying insecure auth
 9741: 
 9742: One of the certificate file, key file or
 9743: certificate authority file could not be found for a client attempting
 9744: SSL connection intiation.  COnnection will be attemptied in in-secure mode.
 9745: (this would be a system with an up to date lond that has not gotten a 
 9746: certificate from us).
 9747: 
 9748: =item (Green)  Successful local authentication            
 9749: 
 9750: A local connection successfully negotiated the encryption key. 
 9751: In this case the IDEA key is in a file (that is hopefully well protected).
 9752: 
 9753: =item (Green) Successful ssl authentication with <client>  
 9754: 
 9755: The client (<client> is the peer's name in hosts.tab), has successfully
 9756: negotiated an SSL connection with this child process.
 9757: 
 9758: =item (Green) Successful insecure authentication with <client>
 9759: 
 9760: 
 9761: The client has successfully negotiated an  insecure connection withthe child process.
 9762: 
 9763: =item (Yellow) Attempted insecure connection disallowed    
 9764: 
 9765: The client attempted and failed to successfully negotiate a successful insecure
 9766: connection.  This can happen either because the variable londAllowInsecure is false
 9767: or undefined, or becuse the child did not successfully echo back the challenge
 9768: string.
 9769: 
 9770: 
 9771: =back
 9772: 
 9773: =back
 9774: 
 9775: 
 9776: =cut

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