File:  [LON-CAPA] / loncom / lond
Revision 1.576: download - view: text, annotated - select for diffs
Mon Jul 25 23:31:40 2022 UTC (20 months, 3 weeks ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Typo

    1: #!/usr/bin/perl
    2: # The LearningOnline Network
    3: # lond "LON Daemon" Server (port "LOND" 5663)
    4: #
    5: # $Id: lond,v 1.576 2022/07/25 23:31:40 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.576 $'; #' 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:                instunamemapcheck => {remote => 1,},  
  263:                instuserrules => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
  264:                keys => {remote => 1,},
  265:                load => {anywhere => 1},
  266:                log => {anywhere => 1},
  267:                ls => {remote => 1, enroll => 1, content => 1,},
  268:                ls2 => {remote => 1, enroll => 1, content => 1,},
  269:                ls3 => {remote => 1, enroll => 1, content => 1,},
  270:                lti => {institutiononly => 1},
  271:                makeuser => {remote => 1, enroll => 1, domroles => 1,},
  272:                mkdiruserfile => {remote => 1, enroll => 1,},
  273:                newput => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1,},
  274:                passwd => {remote => 1},
  275:                ping => {anywhere => 1},
  276:                pong => {anywhere => 1},
  277:                pushfile => {manageronly => 1},
  278:                put => {remote => 1, enroll => 1, domroles => 1, msg => 1, content => 1, shared => 1},
  279:                putdom => {remote => 1, domroles => 1,},
  280:                putstore => {remote => 1, enroll => 1},
  281:                queryreply => {anywhere => 1},
  282:                querysend => {anywhere => 1},
  283:                querysend_activitylog => {remote => 1},
  284:                querysend_allusers => {remote => 1, domroles => 1},
  285:                querysend_courselog => {remote => 1},
  286:                querysend_fetchenrollment => {remote => 1},
  287:                querysend_getinstuser => {remote => 1},
  288:                querysend_getmultinstusers => {remote => 1},
  289:                querysend_instdirsearch => {remote => 1, domroles => 1, coaurem => 1},
  290:                querysend_institutionalphotos => {remote => 1},
  291:                querysend_portfolio_metadata => {remote => 1, content => 1},
  292:                querysend_userlog => {remote => 1, domroles => 1},
  293:                querysend_usersearch => {remote => 1, enroll => 1, coaurem => 1},
  294:                quit => {anywhere => 1},
  295:                readlonnetglobal => {institutiononly => 1},
  296:                reinit => {manageronly => 1}, #not used currently
  297:                removeuserfile => {remote => 1, enroll => 1},
  298:                renameuserfile => {remote => 1,},
  299:                restore => {remote => 1, enroll => 1, reqcrs => 1,},
  300:                rolesdel => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
  301:                rolesput => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
  302:                servercerts => {institutiononly => 1},
  303:                serverdistarch => {anywhere => 1},
  304:                serverhomeID => {anywhere => 1},
  305:                serverloncaparev => {anywhere => 1},
  306:                servertimezone => {remote => 1, enroll => 1},
  307:                setannounce => {remote => 1, domroles => 1},
  308:                sethost => {anywhere => 1},
  309:                store => {remote => 1, enroll => 1, reqcrs => 1,},
  310:                studentphoto => {remote => 1, enroll => 1},
  311:                sub => {content => 1,},
  312:                tmpdel => {institutiononly => 1},
  313:                tmpget => {institutiononly => 1},
  314:                tmpput => {remote => 1, othcoau => 1},
  315:                tokenauthuserfile => {anywhere => 1},
  316:                unamemaprules => {remote => 1,},
  317:                unsub => {content => 1,},
  318:                update => {shared => 1},
  319:                updatebalcookie => {institutiononly => 1},
  320:                updateclickers => {remote => 1},
  321:                userhassession => {anywhere => 1},
  322:                userload => {anywhere => 1},
  323:                version => {anywhere => 1}, #not used
  324:             );
  325: 
  326: #
  327: #   Statistics that are maintained and dislayed in the status line.
  328: #
  329: my $Transactions = 0;		# Number of attempted transactions.
  330: my $Failures     = 0;		# Number of transcations failed.
  331: 
  332: #   ResetStatistics: 
  333: #      Resets the statistics counters:
  334: #
  335: sub ResetStatistics {
  336:     $Transactions = 0;
  337:     $Failures     = 0;
  338: }
  339: 
  340: #------------------------------------------------------------------------
  341: #
  342: #   LocalConnection
  343: #     Completes the formation of a locally authenticated connection.
  344: #     This function will ensure that the 'remote' client is really the
  345: #     local host.  If not, the connection is closed, and the function fails.
  346: #     If so, initcmd is parsed for the name of a file containing the
  347: #     IDEA session key.  The fie is opened, read, deleted and the session
  348: #     key returned to the caller.
  349: #
  350: # Parameters:
  351: #   $Socket      - Socket open on client.
  352: #   $initcmd     - The full text of the init command.
  353: #
  354: # Returns:
  355: #     IDEA session key on success.
  356: #     undef on failure.
  357: #
  358: sub LocalConnection {
  359:     my ($Socket, $initcmd) = @_;
  360:     Debug("Attempting local connection: $initcmd client: $clientip");
  361:     if($clientip ne "127.0.0.1") {
  362: 	&logthis('<font color="red"> LocalConnection rejecting non local: '
  363: 		 ."$clientip ne 127.0.0.1 </font>");
  364: 	close $Socket;
  365: 	return undef;
  366:     }  else {
  367: 	chomp($initcmd);	# Get rid of \n in filename.
  368: 	my ($init, $type, $name) = split(/:/, $initcmd);
  369: 	Debug(" Init command: $init $type $name ");
  370: 
  371: 	# Require that $init = init, and $type = local:  Otherwise
  372: 	# the caller is insane:
  373: 
  374: 	if(($init ne "init") && ($type ne "local")) {
  375: 	    &logthis('<font color = "red"> LocalConnection: caller is insane! '
  376: 		     ."init = $init, and type = $type </font>");
  377: 	    close($Socket);;
  378: 	    return undef;
  379: 		
  380: 	}
  381: 	#  Now get the key filename:
  382: 
  383: 	my $IDEAKey = lonlocal::ReadKeyFile($name);
  384: 	return $IDEAKey;
  385:     }
  386: }
  387: #------------------------------------------------------------------------------
  388: #
  389: #  SSLConnection
  390: #   Completes the formation of an ssh authenticated connection. The
  391: #   socket is promoted to an ssl socket.  If this promotion and the associated
  392: #   certificate exchange are successful, the IDEA key is generated and sent
  393: #   to the remote peer via the SSL tunnel. The IDEA key is also returned to
  394: #   the caller after the SSL tunnel is torn down.
  395: #
  396: # Parameters:
  397: #   Name              Type             Purpose
  398: #   $Socket          IO::Socket::INET  Plaintext socket.
  399: #
  400: # Returns:
  401: #    IDEA key on success.
  402: #    undef on failure.
  403: #
  404: sub SSLConnection {
  405:     my $Socket   = shift;
  406: 
  407:     Debug("SSLConnection: ");
  408:     my $KeyFile         = lonssl::KeyFile();
  409:     if(!$KeyFile) {
  410: 	my $err = lonssl::LastError();
  411: 	&logthis("<font color=\"red\"> CRITICAL"
  412: 		 ."Can't get key file $err </font>");
  413: 	return undef;
  414:     }
  415:     my ($CACertificate,
  416: 	$Certificate) = lonssl::CertificateFile();
  417: 
  418: 
  419:     # If any of the key, certificate or certificate authority 
  420:     # certificate filenames are not defined, this can't work.
  421: 
  422:     if((!$Certificate) || (!$CACertificate)) {
  423: 	my $err = lonssl::LastError();
  424: 	&logthis("<font color=\"red\"> CRITICAL"
  425: 		 ."Can't get certificates: $err </font>");
  426: 
  427: 	return undef;
  428:     }
  429:     Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
  430: 
  431:     # Indicate to our peer that we can procede with
  432:     # a transition to ssl authentication:
  433: 
  434:     print $Socket "ok:ssl\n";
  435: 
  436:     Debug("Approving promotion -> ssl");
  437:     #  And do so:
  438: 
  439:     my $CRLFile;
  440:     unless ($crlchecked{$clientname}) {
  441:         $CRLFile = lonssl::CRLFile();
  442:         $crlchecked{$clientname} = 1;
  443:     }
  444: 
  445:     my $SSLSocket = lonssl::PromoteServerSocket($Socket,
  446: 						$CACertificate,
  447: 						$Certificate,
  448: 						$KeyFile,
  449: 						$clientname,
  450:                                                 $CRLFile,
  451:                                                 $clientversion);
  452:     if(! ($SSLSocket) ) {	# SSL socket promotion failed.
  453: 	my $err = lonssl::LastError();
  454: 	&logthis("<font color=\"red\"> CRITICAL "
  455: 		 ."SSL Socket promotion failed: $err </font>");
  456: 	return undef;
  457:     }
  458:     Debug("SSL Promotion successful");
  459: 
  460:     # 
  461:     #  The only thing we'll use the socket for is to send the IDEA key
  462:     #  to the peer:
  463: 
  464:     my $Key = lonlocal::CreateCipherKey();
  465:     print $SSLSocket "$Key\n";
  466: 
  467:     lonssl::Close($SSLSocket); 
  468: 
  469:     Debug("Key exchange complete: $Key");
  470: 
  471:     return $Key;
  472: }
  473: #
  474: #     InsecureConnection: 
  475: #        If insecure connections are allowd,
  476: #        exchange a challenge with the client to 'validate' the
  477: #        client (not really, but that's the protocol):
  478: #        We produce a challenge string that's sent to the client.
  479: #        The client must then echo the challenge verbatim to us.
  480: #
  481: #  Parameter:
  482: #      Socket      - Socket open on the client.
  483: #  Returns:
  484: #      1           - success.
  485: #      0           - failure (e.g.mismatch or insecure not allowed).
  486: #
  487: sub InsecureConnection {
  488:     my $Socket  =  shift;
  489: 
  490:     #   Don't even start if insecure connections are not allowed.
  491:     #   return 0 if Insecure connections not allowed.
  492:     #
  493:     if (ref($secureconf{'connfrom'}) eq 'HASH') {
  494:         if ($clientsamedom) {
  495:             if ($secureconf{'connfrom'}{'dom'} eq 'req') {
  496:                 return 0;
  497:             } 
  498:         } elsif ($clientsameinst) {
  499:             if ($secureconf{'connfrom'}{'intdom'} eq 'req') {
  500:                 return 0;
  501:             }
  502:         } else {
  503:             if ($secureconf{'connfrom'}{'other'} eq 'req') {
  504:                 return 0;
  505:             }
  506:         }
  507:     } elsif (!$perlvar{londAllowInsecure}) {
  508: 	return 0;
  509:     }
  510: 
  511:     #   Fabricate a challenge string and send it..
  512: 
  513:     my $challenge = "$$".time;	# pid + time.
  514:     print $Socket "$challenge\n";
  515:     &status("Waiting for challenge reply");
  516: 
  517:     my $answer = <$Socket>;
  518:     $answer    =~s/\W//g;
  519:     if($challenge eq $answer) {
  520: 	return 1;
  521:     } else {
  522: 	logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
  523: 	&status("No challenge reqply");
  524: 	return 0;
  525:     }
  526:     
  527: 
  528: }
  529: #
  530: #   Safely execute a command (as long as it's not a shel command and doesn
  531: #   not require/rely on shell escapes.   The function operates by doing a
  532: #   a pipe based fork and capturing stdout and stderr  from the pipe.
  533: #
  534: # Formal Parameters:
  535: #     $line                    - A line of text to be executed as a command.
  536: # Returns:
  537: #     The output from that command.  If the output is multiline the caller
  538: #     must know how to split up the output.
  539: #
  540: #
  541: sub execute_command {
  542:     my ($line)    = @_;
  543:     my @words     = split(/\s/, $line);	# Bust the command up into words.
  544:     my $output    = "";
  545: 
  546:     my $pid = open(CHILD, "-|");
  547:     
  548:     if($pid) {			# Parent process
  549: 	Debug("In parent process for execute_command");
  550: 	my @data = <CHILD>;	# Read the child's outupt...
  551: 	close CHILD;
  552: 	foreach my $output_line (@data) {
  553: 	    Debug("Adding $output_line");
  554: 	    $output .= $output_line; # Presumably has a \n on it.
  555: 	}
  556: 
  557:     } else {			# Child process
  558: 	close (STDERR);
  559: 	open  (STDERR, ">&STDOUT");# Combine stderr, and stdout...
  560: 	exec(@words);		# won't return.
  561:     }
  562:     return $output;
  563: }
  564: 
  565: 
  566: #   GetCertificate: Given a transaction that requires a certificate,
  567: #   this function will extract the certificate from the transaction
  568: #   request.  Note that at this point, the only concept of a certificate
  569: #   is the hostname to which we are connected.
  570: #
  571: #   Parameter:
  572: #      request   - The request sent by our client (this parameterization may
  573: #                  need to change when we really use a certificate granting
  574: #                  authority.
  575: #
  576: sub GetCertificate {
  577:     my $request = shift;
  578: 
  579:     return $clientip;
  580: }
  581: 
  582: #
  583: #   Return true if client is a manager.
  584: #
  585: sub isManager {
  586:     return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
  587: }
  588: #
  589: #   Return tru if client can do client functions
  590: #
  591: sub isClient {
  592:     return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
  593: }
  594: 
  595: 
  596: #
  597: #   ReadManagerTable: Reads in the current manager table. For now this is
  598: #                     done on each manager authentication because:
  599: #                     - These authentications are not frequent
  600: #                     - This allows dynamic changes to the manager table
  601: #                       without the need to signal to the lond.
  602: #
  603: sub ReadManagerTable {
  604: 
  605:     &Debug("Reading manager table");
  606:     #   Clean out the old table first..
  607: 
  608:    foreach my $key (keys %managers) {
  609:       delete $managers{$key};
  610:    }
  611: 
  612:    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
  613:    if (!open (MANAGERS, $tablename)) {
  614:        my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
  615:        if (&Apache::lonnet::is_LC_dns($hostname)) {
  616:            &logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
  617:        }
  618:        return;
  619:    }
  620:    while(my $host = <MANAGERS>) {
  621:       chomp($host);
  622:       if ($host =~ "^#") {                  # Comment line.
  623:          next;
  624:       }
  625:       if (!defined &Apache::lonnet::get_host_ip($host)) { # This is a non cluster member
  626: 	    #  The entry is of the form:
  627: 	    #    cluname:hostname
  628: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
  629: 	    #            the host key.
  630: 	    #  hostname- The dns name of the host.
  631: 	    #
  632:           my($cluname, $dnsname) = split(/:/, $host);
  633:           
  634:           my $ip = gethostbyname($dnsname);
  635:           if(defined($ip)) {                 # bad names don't deserve entry.
  636:             my $hostip = inet_ntoa($ip);
  637:             $managers{$hostip} = $cluname;
  638:             logthis('<font color="green"> registering manager '.
  639:                     "$dnsname as $cluname with $hostip </font>\n");
  640:          }
  641:       } else {
  642:          logthis('<font color="green"> existing host'." $host</font>\n");
  643:          $managers{&Apache::lonnet::get_host_ip($host)} = $host;  # Use info from cluster tab if cluster memeber
  644:       }
  645:    }
  646: }
  647: 
  648: #
  649: #  ValidManager: Determines if a given certificate represents a valid manager.
  650: #                in this primitive implementation, the 'certificate' is
  651: #                just the connecting loncapa client name.  This is checked
  652: #                against a valid client list in the configuration.
  653: #
  654: #                  
  655: sub ValidManager {
  656:     my $certificate = shift; 
  657: 
  658:     return isManager;
  659: }
  660: #
  661: #  CopyFile:  Called as part of the process of installing a 
  662: #             new configuration file.  This function copies an existing
  663: #             file to a backup file.
  664: # Parameters:
  665: #     oldfile  - Name of the file to backup.
  666: #     newfile  - Name of the backup file.
  667: # Return:
  668: #     0   - Failure (errno has failure reason).
  669: #     1   - Success.
  670: #
  671: sub CopyFile {
  672: 
  673:     my ($oldfile, $newfile) = @_;
  674: 
  675:     if (! copy($oldfile,$newfile)) {
  676:         return 0;
  677:     }
  678:     chmod(0660, $newfile);
  679:     return 1;
  680: }
  681: #
  682: #  Host files are passed out with externally visible host IPs.
  683: #  If, for example, we are behind a fire-wall or NAT host, our 
  684: #  internally visible IP may be different than the externally
  685: #  visible IP.  Therefore, we always adjust the contents of the
  686: #  host file so that the entry for ME is the IP that we believe
  687: #  we have.  At present, this is defined as the entry that
  688: #  DNS has for us.  If by some chance we are not able to get a
  689: #  DNS translation for us, then we assume that the host.tab file
  690: #  is correct.  
  691: #    BUGBUGBUG - in the future, we really should see if we can
  692: #       easily query the interface(s) instead.
  693: # Parameter(s):
  694: #     contents    - The contents of the host.tab to check.
  695: # Returns:
  696: #     newcontents - The adjusted contents.
  697: #
  698: #
  699: sub AdjustHostContents {
  700:     my $contents  = shift;
  701:     my $adjusted;
  702:     my $me        = $perlvar{'lonHostID'};
  703: 
  704:     foreach my $line (split(/\n/,$contents)) {
  705: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/) ||
  706:              ($line =~ /^\s*\^/))) {
  707: 	    chomp($line);
  708: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
  709: 	    if ($id eq $me) {
  710: 		my $ip = gethostbyname($name);
  711: 		my $ipnew = inet_ntoa($ip);
  712: 		$ip = $ipnew;
  713: 		#  Reconstruct the host line and append to adjusted:
  714: 		
  715: 		my $newline = "$id:$domain:$role:$name:$ip";
  716: 		if($maxcon ne "") { # Not all hosts have loncnew tuning params
  717: 		    $newline .= ":$maxcon:$idleto:$mincon";
  718: 		}
  719: 		$adjusted .= $newline."\n";
  720: 		
  721: 	    } else {		# Not me, pass unmodified.
  722: 		$adjusted .= $line."\n";
  723: 	    }
  724: 	} else {                  # Blank or comment never re-written.
  725: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
  726: 	}
  727:     }
  728:     return $adjusted;
  729: }
  730: #
  731: #   InstallFile: Called to install an administrative file:
  732: #       - The file is created int a temp directory called <name>.tmp
  733: #       - lcinstall file is called to install the file.
  734: #         since the web app has no direct write access to the table directory
  735: #
  736: #  Parameters:
  737: #       Name of the file
  738: #       File Contents.
  739: #  Return:
  740: #      nonzero - success.
  741: #      0       - failure and $! has an errno.
  742: # Assumptions:
  743: #    File installtion is a relatively infrequent
  744: #
  745: sub InstallFile {
  746: 
  747:     my ($Filename, $Contents) = @_;
  748: #     my $TempFile = $Filename.".tmp";
  749:     my $exedir = $perlvar{'lonDaemons'};
  750:     my $tmpdir = $exedir.'/tmp/';
  751:     my $TempFile = $tmpdir."TempTableFile.tmp";
  752: 
  753:     #  Open the file for write:
  754: 
  755:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
  756:     if(!(defined $fh)) {
  757: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
  758: 	return 0;
  759:     }
  760:     #  write the contents of the file:
  761: 
  762:     print $fh ($Contents); 
  763:     $fh->close;			# In case we ever have a filesystem w. locking
  764: 
  765:     chmod(0664, $TempFile);	# Everyone can write it.
  766: 
  767:     # Use lcinstall file to put the file in the table directory...
  768: 
  769:     &Debug("Opening pipe to $exedir/lcinstallfile $TempFile $Filename");
  770:     my $pf = IO::File->new("| $exedir/lcinstallfile   $TempFile $Filename > $exedir/logs/lcinstallfile.log");
  771:     close $pf;
  772:     my $err = $?;
  773:     &Debug("Status is $err");
  774:     if ($err != 0) {
  775: 	my $msg = $err;
  776: 	if ($err < @installerrors) {
  777: 	    $msg = $installerrors[$err];
  778: 	}
  779: 	&logthis("Install failed for table file $Filename : $msg");
  780: 	return 0;
  781:     }
  782: 
  783:     # Remove the temp file:
  784: 
  785:     unlink($TempFile);
  786: 
  787:     return 1;
  788: }
  789: 
  790: 
  791: #
  792: #   ConfigFileFromSelector: converts a configuration file selector
  793: #                 into a configuration file pathname.
  794: #                 Supports the following file selectors: 
  795: #                 hosts, domain, dns_hosts, dns_domain  
  796: #
  797: #
  798: #  Parameters:
  799: #      selector  - Configuration file selector.
  800: #  Returns:
  801: #      Full path to the file or undef if the selector is invalid.
  802: #
  803: sub ConfigFileFromSelector {
  804:     my $selector   = shift;
  805:     my $tablefile;
  806: 
  807:     if ($selector eq 'loncapaCAcrl') {
  808:         my $tabledir = $perlvar{'lonCertificateDirectory'};
  809:         if (-d $tabledir) {
  810:             $tablefile =  $tabledir.'/'.$selector.'.pem';
  811:         }
  812:     } else {
  813:         my $tabledir = $perlvar{'lonTabDir'}.'/';
  814:         if (($selector eq "hosts") || ($selector eq "domain") || 
  815:             ($selector eq "dns_hosts") || ($selector eq "dns_domain")) {
  816: 	    $tablefile =  $tabledir.$selector.'.tab';
  817:         }
  818:     }
  819:     return $tablefile;
  820: }
  821: #
  822: #   PushFile:  Called to do an administrative push of a file.
  823: #              - Ensure the file being pushed is one we support.
  824: #              - Backup the old file to <filename.saved>
  825: #              - Separate the contents of the new file out from the
  826: #                rest of the request.
  827: #              - Write the new file.
  828: #  Parameter:
  829: #     Request - The entire user request.  This consists of a : separated
  830: #               string pushfile:tablename:contents.
  831: #     NOTE:  The contents may have :'s in it as well making things a bit
  832: #            more interesting... but not much.
  833: #  Returns:
  834: #     String to send to client ("ok" or "refused" if bad file).
  835: #
  836: sub PushFile {
  837:     my $request = shift;
  838:     my ($command, $filename, $contents) = split(":", $request, 3);
  839:     &Debug("PushFile");
  840:     
  841:     #  At this point in time, pushes for only the following tables and
  842:     #  CRL file are supported:
  843:     #   hosts.tab  ($filename eq host).
  844:     #   domain.tab ($filename eq domain).
  845:     #   dns_hosts.tab ($filename eq dns_host).
  846:     #   dns_domain.tab ($filename eq dns_domain).
  847:     #   loncapaCAcrl.pem ($filename eq loncapaCAcrl).
  848:     # Construct the destination filename or reject the request.
  849:     #
  850:     # lonManage is supposed to ensure this, however this session could be
  851:     # part of some elaborate spoof that managed somehow to authenticate.
  852:     #
  853: 
  854: 
  855:     my $tablefile = ConfigFileFromSelector($filename);
  856:     if(! (defined $tablefile)) {
  857: 	return "refused";
  858:     }
  859: 
  860:     #  If the file being pushed is the host file, we adjust the entry for ourself so that the
  861:     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
  862:     #  to conceive of conditions where we don't have a DNS entry locally.  This is possible in a 
  863:     #  network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
  864:     #  that possibilty.
  865: 
  866:     if($filename eq "host") {
  867: 	$contents = AdjustHostContents($contents);
  868:     } elsif (($filename eq 'dns_hosts') || ($filename eq 'dns_domain') ||
  869:              ($filename eq 'loncapaCAcrl')) {
  870:         if ($contents eq '') {
  871:             &logthis('<font color="red"> Pushfile: unable to install '
  872:                     .$tablefile." - no data received from push. </font>");
  873:             return 'error: push had no data';
  874:         }
  875:         if (&Apache::lonnet::get_host_ip($clientname)) {
  876:             my $clienthost = &Apache::lonnet::hostname($clientname);
  877:             if ($managers{$clientip} eq $clientname) {
  878:                 my $clientprotocol = $Apache::lonnet::protocol{$clientname};
  879:                 $clientprotocol = 'http' if ($clientprotocol ne 'https');
  880:                 my $url;
  881:                 if ($filename eq 'loncapaCAcrl') {
  882:                     $url = '/adm/dns/loncapaCRL';
  883:                 } else {
  884:                     $url = '/adm/'.$filename;
  885:                     $url =~ s{_}{/};
  886:                 }
  887:                 my $request=new HTTP::Request('GET',"$clientprotocol://$clienthost$url");
  888:                 my $response = LONCAPA::LWPReq::makerequest($clientname,$request,'',\%perlvar,60,0);
  889:                 if ($response->is_error()) {
  890:                     &logthis('<font color="red"> Pushfile: unable to install '
  891:                             .$tablefile." - error attempting to pull data. </font>");
  892:                     return 'error: pull failed';
  893:                 } else {
  894:                     my $result = $response->content;
  895:                     chomp($result);
  896:                     unless ($result eq $contents) {
  897:                         &logthis('<font color="red"> Pushfile: unable to install '
  898:                                 .$tablefile." - pushed data and pulled data differ. </font>");
  899:                         my $pushleng = length($contents);
  900:                         my $pullleng = length($result);
  901:                         if ($pushleng != $pullleng) {
  902:                             return "error: $pushleng vs $pullleng bytes";
  903:                         } else {
  904:                             return "error: mismatch push and pull";
  905:                         }
  906:                     }
  907:                 }
  908:             }
  909:         }
  910:     }
  911: 
  912:     #  Install the new file:
  913: 
  914:     &logthis("Installing new $tablefile contents:\n$contents");
  915:     if(!InstallFile($tablefile, $contents)) {
  916: 	&logthis('<font color="red"> Pushfile: unable to install '
  917: 	 .$tablefile." $! </font>");
  918: 	return "error:$!";
  919:     } else {
  920: 	&logthis('<font color="green"> Installed new '.$tablefile
  921: 		 ." - transaction by: $clientname ($clientip)</font>");
  922:         my $adminmail = $perlvar{'lonAdmEMail'};
  923:         my $admindom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
  924:         if ($admindom ne '') {
  925:             my %domconfig =
  926:                 &Apache::lonnet::get_dom('configuration',['contacts'],$admindom);
  927:             if (ref($domconfig{'contacts'}) eq 'HASH') {
  928:                 if ($domconfig{'contacts'}{'adminemail'} ne '') {
  929:                     $adminmail = $domconfig{'contacts'}{'adminemail'};
  930:                 }
  931:             }
  932:         }
  933:         if ($adminmail =~ /^[^\@]+\@[^\@]+$/) {
  934:             my $msg = new Mail::Send;
  935:             $msg->to($adminmail);
  936:             $msg->subject('LON-CAPA DNS update on '.$perlvar{'lonHostID'});
  937:             $msg->add('Content-type','text/plain; charset=UTF-8');
  938:             if (my $fh = $msg->open()) {
  939:                 print $fh 'Update to '.$tablefile.' from Cluster Manager '.
  940:                           "$clientname ($clientip)\n";
  941:                 $fh->close;
  942:             }
  943:         }
  944:     }
  945: 
  946:     #  Indicate success:
  947:  
  948:     return "ok";
  949: 
  950: }
  951: 
  952: #
  953: #  Called to re-init either lonc or lond.
  954: #
  955: #  Parameters:
  956: #    request   - The full request by the client.  This is of the form
  957: #                reinit:<process>  
  958: #                where <process> is allowed to be either of 
  959: #                lonc or lond
  960: #
  961: #  Returns:
  962: #     The string to be sent back to the client either:
  963: #   ok         - Everything worked just fine.
  964: #   error:why  - There was a failure and why describes the reason.
  965: #
  966: #
  967: sub ReinitProcess {
  968:     my $request = shift;
  969: 
  970: 
  971:     # separate the request (reinit) from the process identifier and
  972:     # validate it producing the name of the .pid file for the process.
  973:     #
  974:     #
  975:     my ($junk, $process) = split(":", $request);
  976:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
  977:     if($process eq 'lonc') {
  978: 	$processpidfile = $processpidfile."lonc.pid";
  979: 	if (!open(PIDFILE, "< $processpidfile")) {
  980: 	    return "error:Open failed for $processpidfile";
  981: 	}
  982: 	my $loncpid = <PIDFILE>;
  983: 	close(PIDFILE);
  984: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
  985: 		."</font>");
  986: 	kill("USR2", $loncpid);
  987:     } elsif ($process eq 'lond') {
  988: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
  989: 	&UpdateHosts;			# Lond is us!!
  990:     } else {
  991: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
  992: 		 ."</font>");
  993: 	return "error:Invalid process identifier $process";
  994:     }
  995:     return 'ok';
  996: }
  997: #   Validate a line in a configuration file edit script:
  998: #   Validation includes:
  999: #     - Ensuring the command is valid.
 1000: #     - Ensuring the command has sufficient parameters
 1001: #   Parameters:
 1002: #     scriptline - A line to validate (\n has been stripped for what it's worth).
 1003: #
 1004: #   Return:
 1005: #      0     - Invalid scriptline.
 1006: #      1     - Valid scriptline
 1007: #  NOTE:
 1008: #     Only the command syntax is checked, not the executability of the
 1009: #     command.
 1010: #
 1011: sub isValidEditCommand {
 1012:     my $scriptline = shift;
 1013: 
 1014:     #   Line elements are pipe separated:
 1015: 
 1016:     my ($command, $key, $newline)  = split(/\|/, $scriptline);
 1017:     &logthis('<font color="green"> isValideditCommand checking: '.
 1018: 	     "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
 1019:     
 1020:     if ($command eq "delete") {
 1021: 	#
 1022: 	#   key with no newline.
 1023: 	#
 1024: 	if( ($key eq "") || ($newline ne "")) {
 1025: 	    return 0;		# Must have key but no newline.
 1026: 	} else {
 1027: 	    return 1;		# Valid syntax.
 1028: 	}
 1029:     } elsif ($command eq "replace") {
 1030: 	#
 1031: 	#   key and newline:
 1032: 	#
 1033: 	if (($key eq "") || ($newline eq "")) {
 1034: 	    return 0;
 1035: 	} else {
 1036: 	    return 1;
 1037: 	}
 1038:     } elsif ($command eq "append") {
 1039: 	if (($key ne "") && ($newline eq "")) {
 1040: 	    return 1;
 1041: 	} else {
 1042: 	    return 0;
 1043: 	}
 1044:     } else {
 1045: 	return 0;		# Invalid command.
 1046:     }
 1047:     return 0;			# Should not get here!!!
 1048: }
 1049: #
 1050: #   ApplyEdit - Applies an edit command to a line in a configuration 
 1051: #               file.  It is the caller's responsiblity to validate the
 1052: #               edit line.
 1053: #   Parameters:
 1054: #      $directive - A single edit directive to apply.  
 1055: #                   Edit directives are of the form:
 1056: #                  append|newline      - Appends a new line to the file.
 1057: #                  replace|key|newline - Replaces the line with key value 'key'
 1058: #                  delete|key          - Deletes the line with key value 'key'.
 1059: #      $editor   - A config file editor object that contains the
 1060: #                  file being edited.
 1061: #
 1062: sub ApplyEdit {
 1063: 
 1064:     my ($directive, $editor) = @_;
 1065: 
 1066:     # Break the directive down into its command and its parameters
 1067:     # (at most two at this point.  The meaning of the parameters, if in fact
 1068:     #  they exist depends on the command).
 1069: 
 1070:     my ($command, $p1, $p2) = split(/\|/, $directive);
 1071: 
 1072:     if($command eq "append") {
 1073: 	$editor->Append($p1);	          # p1 - key p2 null.
 1074:     } elsif ($command eq "replace") {
 1075: 	$editor->ReplaceLine($p1, $p2);   # p1 - key p2 = newline.
 1076:     } elsif ($command eq "delete") {
 1077: 	$editor->DeleteLine($p1);         # p1 - key p2 null.
 1078:     } else {			          # Should not get here!!!
 1079: 	die "Invalid command given to ApplyEdit $command"
 1080:     }
 1081: }
 1082: #
 1083: # AdjustOurHost:
 1084: #           Adjusts a host file stored in a configuration file editor object
 1085: #           for the true IP address of this host. This is necessary for hosts
 1086: #           that live behind a firewall.
 1087: #           Those hosts have a publicly distributed IP of the firewall, but
 1088: #           internally must use their actual IP.  We assume that a given
 1089: #           host only has a single IP interface for now.
 1090: # Formal Parameters:
 1091: #     editor   - The configuration file editor to adjust.  This
 1092: #                editor is assumed to contain a hosts.tab file.
 1093: # Strategy:
 1094: #    - Figure out our hostname.
 1095: #    - Lookup the entry for this host.
 1096: #    - Modify the line to contain our IP
 1097: #    - Do a replace for this host.
 1098: sub AdjustOurHost {
 1099:     my $editor        = shift;
 1100: 
 1101:     # figure out who I am.
 1102: 
 1103:     my $myHostName    = $perlvar{'lonHostID'}; # LonCAPA hostname.
 1104: 
 1105:     #  Get my host file entry.
 1106: 
 1107:     my $ConfigLine    = $editor->Find($myHostName);
 1108:     if(! (defined $ConfigLine)) {
 1109: 	die "AdjustOurHost - no entry for me in hosts file $myHostName";
 1110:     }
 1111:     # figure out my IP:
 1112:     #   Use the config line to get my hostname.
 1113:     #   Use gethostbyname to translate that into an IP address.
 1114:     #
 1115:     my ($id,$domain,$role,$name,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
 1116:     #
 1117:     #  Reassemble the config line from the elements in the list.
 1118:     #  Note that if the loncnew items were not present before, they will
 1119:     #  be now even if they would be empty
 1120:     #
 1121:     my $newConfigLine = $id;
 1122:     foreach my $item ($domain, $role, $name, $maxcon, $idleto, $mincon) {
 1123: 	$newConfigLine .= ":".$item;
 1124:     }
 1125:     #  Replace the line:
 1126: 
 1127:     $editor->ReplaceLine($id, $newConfigLine);
 1128:     
 1129: }
 1130: #
 1131: #   ReplaceConfigFile:
 1132: #              Replaces a configuration file with the contents of a
 1133: #              configuration file editor object.
 1134: #              This is done by:
 1135: #              - Copying the target file to <filename>.old
 1136: #              - Writing the new file to <filename>.tmp
 1137: #              - Moving <filename.tmp>  -> <filename>
 1138: #              This laborious process ensures that the system is never without
 1139: #              a configuration file that's at least valid (even if the contents
 1140: #              may be dated).
 1141: #   Parameters:
 1142: #        filename   - Name of the file to modify... this is a full path.
 1143: #        editor     - Editor containing the file.
 1144: #
 1145: sub ReplaceConfigFile {
 1146:     
 1147:     my ($filename, $editor) = @_;
 1148: 
 1149:     CopyFile ($filename, $filename.".old");
 1150: 
 1151:     my $contents  = $editor->Get(); # Get the contents of the file.
 1152: 
 1153:     InstallFile($filename, $contents);
 1154: }
 1155: #   
 1156: #
 1157: #   Called to edit a configuration table  file
 1158: #   Parameters:
 1159: #      request           - The entire command/request sent by lonc or lonManage
 1160: #   Return:
 1161: #      The reply to send to the client.
 1162: #
 1163: sub EditFile {
 1164:     my $request = shift;
 1165: 
 1166:     #  Split the command into it's pieces:  edit:filetype:script
 1167: 
 1168:     my ($cmd, $filetype, $script) = split(/:/, $request,3);	# : in script
 1169: 
 1170:     #  Check the pre-coditions for success:
 1171: 
 1172:     if($cmd != "edit") {	# Something is amiss afoot alack.
 1173: 	return "error:edit request detected, but request != 'edit'\n";
 1174:     }
 1175:     if( ($filetype ne "hosts")  &&
 1176: 	($filetype ne "domain")) {
 1177: 	return "error:edit requested with invalid file specifier: $filetype \n";
 1178:     }
 1179: 
 1180:     #   Split the edit script and check it's validity.
 1181: 
 1182:     my @scriptlines = split(/\n/, $script);  # one line per element.
 1183:     my $linecount   = scalar(@scriptlines);
 1184:     for(my $i = 0; $i < $linecount; $i++) {
 1185: 	chomp($scriptlines[$i]);
 1186: 	if(!isValidEditCommand($scriptlines[$i])) {
 1187: 	    return "error:edit with bad script line: '$scriptlines[$i]' \n";
 1188: 	}
 1189:     }
 1190: 
 1191:     #   Execute the edit operation.
 1192:     #   - Create a config file editor for the appropriate file and 
 1193:     #   - execute each command in the script:
 1194:     #
 1195:     my $configfile = ConfigFileFromSelector($filetype);
 1196:     if (!(defined $configfile)) {
 1197: 	return "refused\n";
 1198:     }
 1199:     my $editor = ConfigFileEdit->new($configfile);
 1200: 
 1201:     for (my $i = 0; $i < $linecount; $i++) {
 1202: 	ApplyEdit($scriptlines[$i], $editor);
 1203:     }
 1204:     # If the file is the host file, ensure that our host is
 1205:     # adjusted to have our ip:
 1206:     #
 1207:     if($filetype eq "host") {
 1208: 	AdjustOurHost($editor);
 1209:     }
 1210:     #  Finally replace the current file with our file.
 1211:     #
 1212:     ReplaceConfigFile($configfile, $editor);
 1213: 
 1214:     return "ok\n";
 1215: }
 1216: 
 1217: #   read_profile
 1218: #
 1219: #   Returns a set of specific entries from a user's profile file.
 1220: #   this is a utility function that is used by both get_profile_entry and
 1221: #   get_profile_entry_encrypted.
 1222: #
 1223: # Parameters:
 1224: #    udom       - Domain in which the user exists.
 1225: #    uname      - User's account name (loncapa account)
 1226: #    namespace  - The profile namespace to open.
 1227: #    what       - A set of & separated queries.
 1228: # Returns:
 1229: #    If all ok: - The string that needs to be shipped back to the user.
 1230: #    If failure - A string that starts with error: followed by the failure
 1231: #                 reason.. note that this probabyl gets shipped back to the
 1232: #                 user as well.
 1233: #
 1234: sub read_profile {
 1235:     my ($udom, $uname, $namespace, $what) = @_;
 1236:     
 1237:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 1238: 				 &GDBM_READER());
 1239:     if ($hashref) {
 1240:         my @queries=split(/\&/,$what);
 1241:         if ($namespace eq 'roles') {
 1242:             @queries = map { &unescape($_); } @queries; 
 1243:         }
 1244:         my $qresult='';
 1245: 	
 1246: 	for (my $i=0;$i<=$#queries;$i++) {
 1247: 	    $qresult.="$hashref->{$queries[$i]}&";    # Presumably failure gives empty string.
 1248: 	}
 1249: 	$qresult=~s/\&$//;              # Remove trailing & from last lookup.
 1250: 	if (&untie_user_hash($hashref)) {
 1251: 	    return $qresult;
 1252: 	} else {
 1253: 	    return "error: ".($!+0)." untie (GDBM) Failed";
 1254: 	}
 1255:     } else {
 1256: 	if ($!+0 == 2) {
 1257: 	    return "error:No such file or GDBM reported bad block error";
 1258: 	} else {
 1259: 	    return "error: ".($!+0)." tie (GDBM) Failed";
 1260: 	}
 1261:     }
 1262: 
 1263: }
 1264: #--------------------- Request Handlers --------------------------------------------
 1265: #
 1266: #   By convention each request handler registers itself prior to the sub 
 1267: #   declaration:
 1268: #
 1269: 
 1270: #++
 1271: #
 1272: #  Handles ping requests.
 1273: #  Parameters:
 1274: #      $cmd    - the actual keyword that invoked us.
 1275: #      $tail   - the tail of the request that invoked us.
 1276: #      $replyfd- File descriptor connected to the client
 1277: #  Implicit Inputs:
 1278: #      $currenthostid - Global variable that carries the name of the host we are
 1279: #                       known as.
 1280: #  Returns:
 1281: #      1       - Ok to continue processing.
 1282: #      0       - Program should exit.
 1283: #  Side effects:
 1284: #      Reply information is sent to the client.
 1285: sub ping_handler {
 1286:     my ($cmd, $tail, $client) = @_;
 1287:     Debug("$cmd $tail $client .. $currenthostid:");
 1288:    
 1289:     Reply( $client,\$currenthostid,"$cmd:$tail");
 1290:    
 1291:     return 1;
 1292: }
 1293: &register_handler("ping", \&ping_handler, 0, 1, 1);       # Ping unencoded, client or manager.
 1294: 
 1295: #++
 1296: #
 1297: # Handles pong requests.  Pong replies with our current host id, and
 1298: #                         the results of a ping sent to us via our lonc.
 1299: #
 1300: # Parameters:
 1301: #      $cmd    - the actual keyword that invoked us.
 1302: #      $tail   - the tail of the request that invoked us.
 1303: #      $replyfd- File descriptor connected to the client
 1304: #  Implicit Inputs:
 1305: #      $currenthostid - Global variable that carries the name of the host we are
 1306: #                       connected to.
 1307: #  Returns:
 1308: #      1       - Ok to continue processing.
 1309: #      0       - Program should exit.
 1310: #  Side effects:
 1311: #      Reply information is sent to the client.
 1312: sub pong_handler {
 1313:     my ($cmd, $tail, $replyfd) = @_;
 1314: 
 1315:     my $reply=&Apache::lonnet::reply("ping",$clientname);
 1316:     &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail"); 
 1317:     return 1;
 1318: }
 1319: &register_handler("pong", \&pong_handler, 0, 1, 1);       # Pong unencoded, client or manager
 1320: 
 1321: #++
 1322: #      Called to establish an encrypted session key with the remote client.
 1323: #      Note that with secure lond, in most cases this function is never
 1324: #      invoked.  Instead, the secure session key is established either
 1325: #      via a local file that's locked down tight and only lives for a short
 1326: #      time, or via an ssl tunnel...and is generated from a bunch-o-random
 1327: #      bits from /dev/urandom, rather than the predictable pattern used by
 1328: #      by this sub.  This sub is only used in the old-style insecure
 1329: #      key negotiation.
 1330: # Parameters:
 1331: #      $cmd    - the actual keyword that invoked us.
 1332: #      $tail   - the tail of the request that invoked us.
 1333: #      $replyfd- File descriptor connected to the client
 1334: #  Implicit Inputs:
 1335: #      $currenthostid - Global variable that carries the name of the host
 1336: #                       known as.
 1337: #      $clientname    - Global variable that carries the name of the host we're connected to.
 1338: #  Returns:
 1339: #      1       - Ok to continue processing.
 1340: #      0       - Program should exit.
 1341: #  Implicit Outputs:
 1342: #      Reply information is sent to the client.
 1343: #      $cipher is set with a reference to a new IDEA encryption object.
 1344: #
 1345: sub establish_key_handler {
 1346:     my ($cmd, $tail, $replyfd) = @_;
 1347: 
 1348:     my $buildkey=time.$$.int(rand 100000);
 1349:     $buildkey=~tr/1-6/A-F/;
 1350:     $buildkey=int(rand 100000).$buildkey.int(rand 100000);
 1351:     my $key=$currenthostid.$clientname;
 1352:     $key=~tr/a-z/A-Z/;
 1353:     $key=~tr/G-P/0-9/;
 1354:     $key=~tr/Q-Z/0-9/;
 1355:     $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
 1356:     $key=substr($key,0,32);
 1357:     my $cipherkey=pack("H32",$key);
 1358:     $cipher=new IDEA $cipherkey;
 1359:     &Reply($replyfd, \$buildkey, "$cmd:$tail"); 
 1360:    
 1361:     return 1;
 1362: 
 1363: }
 1364: &register_handler("ekey", \&establish_key_handler, 0, 1,1);
 1365: 
 1366: #     Handler for the load command.  Returns the current system load average
 1367: #     to the requestor.
 1368: #
 1369: # Parameters:
 1370: #      $cmd    - the actual keyword that invoked us.
 1371: #      $tail   - the tail of the request that invoked us.
 1372: #      $replyfd- File descriptor connected to the client
 1373: #  Implicit Inputs:
 1374: #      $currenthostid - Global variable that carries the name of the host
 1375: #                       known as.
 1376: #      $clientname    - Global variable that carries the name of the host we're connected to.
 1377: #  Returns:
 1378: #      1       - Ok to continue processing.
 1379: #      0       - Program should exit.
 1380: #  Side effects:
 1381: #      Reply information is sent to the client.
 1382: sub load_handler {
 1383:     my ($cmd, $tail, $replyfd) = @_;
 1384: 
 1385: 
 1386: 
 1387:    # Get the load average from /proc/loadavg and calculate it as a percentage of
 1388:    # the allowed load limit as set by the perl global variable lonLoadLim
 1389: 
 1390:     my $loadavg;
 1391:     my $loadfile=IO::File->new('/proc/loadavg');
 1392:    
 1393:     $loadavg=<$loadfile>;
 1394:     $loadavg =~ s/\s.*//g;                      # Extract the first field only.
 1395:    
 1396:     my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
 1397: 
 1398:     &Reply( $replyfd, \$loadpercent, "$cmd:$tail");
 1399:    
 1400:     return 1;
 1401: }
 1402: &register_handler("load", \&load_handler, 0, 1, 0);
 1403: 
 1404: #
 1405: #   Process the userload request.  This sub returns to the client the current
 1406: #  user load average.  It can be invoked either by clients or managers.
 1407: #
 1408: # Parameters:
 1409: #      $cmd    - the actual keyword that invoked us.
 1410: #      $tail   - the tail of the request that invoked us.
 1411: #      $replyfd- File descriptor connected to the client
 1412: #  Implicit Inputs:
 1413: #      $currenthostid - Global variable that carries the name of the host
 1414: #                       known as.
 1415: #      $clientname    - Global variable that carries the name of the host we're connected to.
 1416: #  Returns:
 1417: #      1       - Ok to continue processing.
 1418: #      0       - Program should exit
 1419: # Implicit inputs:
 1420: #     whatever the userload() function requires.
 1421: #  Implicit outputs:
 1422: #     the reply is written to the client.
 1423: #
 1424: sub user_load_handler {
 1425:     my ($cmd, $tail, $replyfd) = @_;
 1426: 
 1427:     my $userloadpercent=&Apache::lonnet::userload();
 1428:     &Reply($replyfd, \$userloadpercent, "$cmd:$tail");
 1429:     
 1430:     return 1;
 1431: }
 1432: &register_handler("userload", \&user_load_handler, 0, 1, 0);
 1433: 
 1434: #   Process a request for the authorization type of a user:
 1435: #   (userauth).
 1436: #
 1437: # Parameters:
 1438: #      $cmd    - the actual keyword that invoked us.
 1439: #      $tail   - the tail of the request that invoked us.
 1440: #      $replyfd- File descriptor connected to the client
 1441: #  Returns:
 1442: #      1       - Ok to continue processing.
 1443: #      0       - Program should exit
 1444: # Implicit outputs:
 1445: #    The user authorization type is written to the client.
 1446: #
 1447: sub user_authorization_type {
 1448:     my ($cmd, $tail, $replyfd) = @_;
 1449:    
 1450:     my $userinput = "$cmd:$tail";
 1451:    
 1452:     #  Pull the domain and username out of the command tail.
 1453:     # and call get_auth_type to determine the authentication type.
 1454:    
 1455:     my ($udom,$uname)=split(/:/,$tail);
 1456:     my $result = &get_auth_type($udom, $uname);
 1457:     if($result eq "nouser") {
 1458: 	&Failure( $replyfd, "unknown_user\n", $userinput);
 1459:     } else {
 1460: 	#
 1461: 	# We only want to pass the second field from get_auth_type
 1462: 	# for ^krb.. otherwise we'll be handing out the encrypted
 1463: 	# password for internals e.g.
 1464: 	#
 1465: 	my ($type,$otherinfo) = split(/:/,$result);
 1466: 	if($type =~ /^krb/) {
 1467: 	    $type = $result;
 1468: 	} else {
 1469:             $type .= ':';
 1470:         }
 1471: 	&Reply( $replyfd, \$type, $userinput);
 1472:     }
 1473:   
 1474:     return 1;
 1475: }
 1476: &register_handler("currentauth", \&user_authorization_type, 1, 1, 0);
 1477: 
 1478: #   Process a request by a manager to push a hosts or domain table 
 1479: #   to us.  We pick apart the command and pass it on to the subs
 1480: #   that already exist to do this.
 1481: #
 1482: # Parameters:
 1483: #      $cmd    - the actual keyword that invoked us.
 1484: #      $tail   - the tail of the request that invoked us.
 1485: #      $client - File descriptor connected to the client
 1486: #  Returns:
 1487: #      1       - Ok to continue processing.
 1488: #      0       - Program should exit
 1489: # Implicit Output:
 1490: #    a reply is written to the client.
 1491: sub push_file_handler {
 1492:     my ($cmd, $tail, $client) = @_;
 1493:     &Debug("In push file handler");
 1494:     my $userinput = "$cmd:$tail";
 1495: 
 1496:     # At this time we only know that the IP of our partner is a valid manager
 1497:     # the code below is a hook to do further authentication (e.g. to resolve
 1498:     # spoofing).
 1499: 
 1500:     my $cert = &GetCertificate($userinput);
 1501:     if(&ValidManager($cert)) {
 1502: 	&Debug("Valid manager: $client");
 1503: 
 1504: 	# Now presumably we have the bona fides of both the peer host and the
 1505: 	# process making the request.
 1506:       
 1507: 	my $reply = &PushFile($userinput);
 1508: 	&Reply($client, \$reply, $userinput);
 1509: 
 1510:     } else {
 1511: 	&logthis("push_file_handler $client is not valid");
 1512: 	&Failure( $client, "refused\n", $userinput);
 1513:     } 
 1514:     return 1;
 1515: }
 1516: &register_handler("pushfile", \&push_file_handler, 1, 0, 1);
 1517: 
 1518: # The du_handler routine should be considered obsolete and is retained
 1519: # for communication with legacy servers.  Please see the du2_handler.
 1520: #
 1521: #   du  - list the disk usage of a directory recursively. 
 1522: #    
 1523: #   note: stolen code from the ls file handler
 1524: #   under construction by Rick Banghart 
 1525: #    .
 1526: # Parameters:
 1527: #    $cmd        - The command that dispatched us (du).
 1528: #    $ududir     - The directory path to list... I'm not sure what this
 1529: #                  is relative as things like ls:. return e.g.
 1530: #                  no_such_dir.
 1531: #    $client     - Socket open on the client.
 1532: # Returns:
 1533: #     1 - indicating that the daemon should not disconnect.
 1534: # Side Effects:
 1535: #   The reply is written to  $client.
 1536: #
 1537: sub du_handler {
 1538:     my ($cmd, $ududir, $client) = @_;
 1539:     ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
 1540:     my $userinput = "$cmd:$ududir";
 1541: 
 1542:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
 1543: 	&Failure($client,"refused\n","$cmd:$ududir");
 1544: 	return 1;
 1545:     }
 1546:     #  Since $ududir could have some nasties in it,
 1547:     #  we will require that ududir is a valid
 1548:     #  directory.  Just in case someone tries to
 1549:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
 1550:     #  etc.
 1551:     #
 1552:     if (-d $ududir) {
 1553: 	my $total_size=0;
 1554: 	my $code=sub { 
 1555: 	    if ($_=~/\.\d+\./) { return;} 
 1556: 	    if ($_=~/\.meta$/) { return;}
 1557: 	    if (-d $_)         { return;}
 1558: 	    $total_size+=(stat($_))[7];
 1559: 	};
 1560: 	chdir($ududir);
 1561: 	find($code,$ududir);
 1562: 	$total_size=int($total_size/1024);
 1563: 	&Reply($client,\$total_size,"$cmd:$ududir");
 1564:     } else {
 1565: 	&Failure($client, "bad_directory:$ududir\n","$cmd:$ududir"); 
 1566:     }
 1567:     return 1;
 1568: }
 1569: &register_handler("du", \&du_handler, 0, 1, 0);
 1570: 
 1571: # Please also see the du_handler, which is obsoleted by du2. 
 1572: # du2_handler differs from du_handler in that required path to directory
 1573: # provided by &propath() is prepended in the handler instead of on the 
 1574: # client side.
 1575: #
 1576: #   du2  - list the disk usage of a directory recursively.
 1577: #
 1578: # Parameters:
 1579: #    $cmd        - The command that dispatched us (du).
 1580: #    $tail       - The tail of the request that invoked us.
 1581: #                  $tail is a : separated list of the following:
 1582: #                   - $ududir - directory path to list (before prepending)
 1583: #                   - $getpropath = 1 if &propath() should prepend
 1584: #                   - $uname - username to use for &propath or user dir
 1585: #                   - $udom - domain to use for &propath or user dir
 1586: #                   All are escaped.
 1587: #    $client     - Socket open on the client.
 1588: # Returns:
 1589: #     1 - indicating that the daemon should not disconnect.
 1590: # Side Effects:
 1591: #   The reply is written to $client.
 1592: #
 1593: 
 1594: sub du2_handler {
 1595:     my ($cmd, $tail, $client) = @_;
 1596:     my ($ududir,$getpropath,$uname,$udom) = map { &unescape($_) } (split(/:/, $tail));
 1597:     my $userinput = "$cmd:$tail";
 1598:     if (($ududir=~/\.\./) || (($ududir!~m|^/home/httpd/|) && (!$getpropath))) {
 1599:         &Failure($client,"refused\n","$cmd:$tail");
 1600:         return 1;
 1601:     }
 1602:     if ($getpropath) {
 1603:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
 1604:             $ududir = &propath($udom,$uname).'/'.$ududir;
 1605:         } else {
 1606:             &Failure($client,"refused\n","$cmd:$tail");
 1607:             return 1;
 1608:         }
 1609:     }
 1610:     #  Since $ududir could have some nasties in it,
 1611:     #  we will require that ududir is a valid
 1612:     #  directory.  Just in case someone tries to
 1613:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
 1614:     #  etc.
 1615:     #
 1616:     if (-d $ududir) {
 1617:         my $total_size=0;
 1618:         my $code=sub {
 1619:             if ($_=~/\.\d+\./) { return;}
 1620:             if ($_=~/\.meta$/) { return;}
 1621:             if (-d $_)         { return;}
 1622:             $total_size+=(stat($_))[7];
 1623:         };
 1624:         chdir($ududir);
 1625:         find($code,$ududir);
 1626:         $total_size=int($total_size/1024);
 1627:         &Reply($client,\$total_size,"$cmd:$ududir");
 1628:     } else {
 1629:         &Failure($client, "bad_directory:$ududir\n","$cmd:$tail");
 1630:     }
 1631:     return 1;
 1632: }
 1633: &register_handler("du2", \&du2_handler, 0, 1, 0);
 1634: 
 1635: #
 1636: # The ls_handler routine should be considered obsolete and is retained
 1637: # for communication with legacy servers.  Please see the ls3_handler.
 1638: #
 1639: #   ls  - list the contents of a directory.  For each file in the
 1640: #    selected directory the filename followed by the full output of
 1641: #    the stat function is returned.  The returned info for each
 1642: #    file are separated by ':'.  The stat fields are separated by &'s.
 1643: #
 1644: #    If the requested path contains /../ or is:
 1645: #
 1646: #    1. for a directory, and the path does not begin with one of:
 1647: #        (a) /home/httpd/html/res/<domain>
 1648: #        (b) /home/httpd/html/userfiles/
 1649: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
 1650: #    or is:
 1651: #
 1652: #    2. for a file, and the path (after prepending) does not begin with one of:
 1653: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
 1654: #        (b) /home/httpd/html/res/<domain>/<username>/
 1655: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
 1656: #
 1657: #    the response will be "refused".
 1658: #
 1659: # Parameters:
 1660: #    $cmd        - The command that dispatched us (ls).
 1661: #    $ulsdir     - The directory path to list... I'm not sure what this
 1662: #                  is relative as things like ls:. return e.g.
 1663: #                  no_such_dir.
 1664: #    $client     - Socket open on the client.
 1665: # Returns:
 1666: #     1 - indicating that the daemon should not disconnect.
 1667: # Side Effects:
 1668: #   The reply is written to  $client.
 1669: #
 1670: sub ls_handler {
 1671:     # obsoleted by ls2_handler
 1672:     my ($cmd, $ulsdir, $client) = @_;
 1673: 
 1674:     my $userinput = "$cmd:$ulsdir";
 1675: 
 1676:     my $obs;
 1677:     my $rights;
 1678:     my $ulsout='';
 1679:     my $ulsfn;
 1680:     if ($ulsdir =~m{/\.\./}) {
 1681:         &Failure($client,"refused\n",$userinput);
 1682:         return 1;
 1683:     }
 1684:     if (-e $ulsdir) {
 1685: 	if(-d $ulsdir) {
 1686:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
 1687:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
 1688:                 &Failure($client,"refused\n",$userinput);
 1689:                 return 1;
 1690:             }
 1691: 	    if (opendir(LSDIR,$ulsdir)) {
 1692: 		while ($ulsfn=readdir(LSDIR)) {
 1693: 		    undef($obs);
 1694: 		    undef($rights); 
 1695: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1696: 		    #We do some obsolete checking here
 1697: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
 1698: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
 1699: 			my @obsolete=<FILE>;
 1700: 			foreach my $obsolete (@obsolete) {
 1701: 			    if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
 1702: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
 1703: 			}
 1704: 		    }
 1705: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
 1706: 		    if($obs eq '1') { $ulsout.="&1"; }
 1707: 		    else { $ulsout.="&0"; }
 1708: 		    if($rights eq '1') { $ulsout.="&1:"; }
 1709: 		    else { $ulsout.="&0:"; }
 1710: 		}
 1711: 		closedir(LSDIR);
 1712: 	    }
 1713: 	} else {
 1714:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
 1715:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
 1716:                 &Failure($client,"refused\n",$userinput);
 1717:                 return 1;
 1718:             }
 1719: 	    my @ulsstats=stat($ulsdir);
 1720: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1721: 	}
 1722:     } else {
 1723: 	$ulsout='no_such_dir';
 1724:     }
 1725:     if ($ulsout eq '') { $ulsout='empty'; }
 1726:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
 1727:     
 1728:     return 1;
 1729: 
 1730: }
 1731: &register_handler("ls", \&ls_handler, 0, 1, 0);
 1732: 
 1733: # The ls2_handler routine should be considered obsolete and is retained
 1734: # for communication with legacy servers.  Please see the ls3_handler.
 1735: # Please also see the ls_handler, which was itself obsoleted by ls2.
 1736: # ls2_handler differs from ls_handler in that it escapes its return 
 1737: # values before concatenating them together with ':'s.
 1738: #
 1739: #   ls2  - list the contents of a directory.  For each file in the
 1740: #    selected directory the filename followed by the full output of
 1741: #    the stat function is returned.  The returned info for each
 1742: #    file are separated by ':'.  The stat fields are separated by &'s.
 1743: #
 1744: #    If the requested path contains /../ or is:
 1745: #
 1746: #    1. for a directory, and the path does not begin with one of:
 1747: #        (a) /home/httpd/html/res/<domain>
 1748: #        (b) /home/httpd/html/userfiles/
 1749: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
 1750: #    or is:
 1751: #
 1752: #    2. for a file, and the path (after prepending) does not begin with one of:
 1753: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
 1754: #        (b) /home/httpd/html/res/<domain>/<username>/
 1755: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
 1756: #
 1757: #    the response will be "refused".
 1758: #
 1759: # Parameters:
 1760: #    $cmd        - The command that dispatched us (ls).
 1761: #    $ulsdir     - The directory path to list... I'm not sure what this
 1762: #                  is relative as things like ls:. return e.g.
 1763: #                  no_such_dir.
 1764: #    $client     - Socket open on the client.
 1765: # Returns:
 1766: #     1 - indicating that the daemon should not disconnect.
 1767: # Side Effects:
 1768: #   The reply is written to  $client.
 1769: #
 1770: sub ls2_handler {
 1771:     my ($cmd, $ulsdir, $client) = @_;
 1772: 
 1773:     my $userinput = "$cmd:$ulsdir";
 1774: 
 1775:     my $obs;
 1776:     my $rights;
 1777:     my $ulsout='';
 1778:     my $ulsfn;
 1779:     if ($ulsdir =~m{/\.\./}) {
 1780:         &Failure($client,"refused\n",$userinput);
 1781:         return 1;
 1782:     }
 1783:     if (-e $ulsdir) {
 1784:         if(-d $ulsdir) {
 1785:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
 1786:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
 1787:                 &Failure($client,"refused\n","$userinput");
 1788:                 return 1;
 1789:             }
 1790:             if (opendir(LSDIR,$ulsdir)) {
 1791:                 while ($ulsfn=readdir(LSDIR)) {
 1792:                     undef($obs);
 1793: 		    undef($rights); 
 1794:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1795:                     #We do some obsolete checking here
 1796:                     if(-e $ulsdir.'/'.$ulsfn.".meta") { 
 1797:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
 1798:                         my @obsolete=<FILE>;
 1799:                         foreach my $obsolete (@obsolete) {
 1800:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
 1801:                             if($obsolete =~ m|(<copyright>)(default)|) {
 1802:                                 $rights = 1;
 1803:                             }
 1804:                         }
 1805:                     }
 1806:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
 1807:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1808:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1809:                     $ulsout.= &escape($tmp).':';
 1810:                 }
 1811:                 closedir(LSDIR);
 1812:             }
 1813:         } else {
 1814:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
 1815:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
 1816:                 &Failure($client,"refused\n",$userinput);
 1817:                 return 1;
 1818:             }
 1819:             my @ulsstats=stat($ulsdir);
 1820:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1821:         }
 1822:     } else {
 1823:         $ulsout='no_such_dir';
 1824:    }
 1825:    if ($ulsout eq '') { $ulsout='empty'; }
 1826:    &Reply($client, \$ulsout, $userinput); # This supports debug logging.
 1827:    return 1;
 1828: }
 1829: &register_handler("ls2", \&ls2_handler, 0, 1, 0);
 1830: #
 1831: #   ls3  - list the contents of a directory.  For each file in the
 1832: #    selected directory the filename followed by the full output of
 1833: #    the stat function is returned.  The returned info for each
 1834: #    file are separated by ':'.  The stat fields are separated by &'s.
 1835: #
 1836: #    If the requested path (after prepending) contains /../ or is:
 1837: #
 1838: #    1. for a directory, and the path does not begin with one of:
 1839: #        (a) /home/httpd/html/res/<domain>
 1840: #        (b) /home/httpd/html/userfiles/
 1841: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
 1842: #        (d) /home/httpd/html/priv/<domain> and client is the homeserver
 1843: #
 1844: #    or is:
 1845: #
 1846: #    2. for a file, and the path (after prepending) does not begin with one of:
 1847: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
 1848: #        (b) /home/httpd/html/res/<domain>/<username>/
 1849: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
 1850: #        (d) /home/httpd/html/priv/<domain>/<username>/ and client is the homeserver
 1851: #
 1852: #    the response will be "refused".
 1853: #
 1854: # Parameters:
 1855: #    $cmd        - The command that dispatched us (ls).
 1856: #    $tail       - The tail of the request that invoked us.
 1857: #                  $tail is a : separated list of the following:
 1858: #                   - $ulsdir - directory path to list (before prepending)
 1859: #                   - $getpropath = 1 if &propath() should prepend
 1860: #                   - $getuserdir = 1 if path to user dir in lonUsers should
 1861: #                                     prepend
 1862: #                   - $alternate_root - path to prepend
 1863: #                   - $uname - username to use for &propath or user dir
 1864: #                   - $udom - domain to use for &propath or user dir
 1865: #            All of these except $getpropath and &getuserdir are escaped.    
 1866: #                  no_such_dir.
 1867: #    $client     - Socket open on the client.
 1868: # Returns:
 1869: #     1 - indicating that the daemon should not disconnect.
 1870: # Side Effects:
 1871: #   The reply is written to $client.
 1872: #
 1873: 
 1874: sub ls3_handler {
 1875:     my ($cmd, $tail, $client) = @_;
 1876:     my $userinput = "$cmd:$tail";
 1877:     my ($ulsdir,$getpropath,$getuserdir,$alternate_root,$uname,$udom) =
 1878:         split(/:/,$tail);
 1879:     if (defined($ulsdir)) {
 1880:         $ulsdir = &unescape($ulsdir);
 1881:     }
 1882:     if (defined($alternate_root)) {
 1883:         $alternate_root = &unescape($alternate_root);
 1884:     }
 1885:     if (defined($uname)) {
 1886:         $uname = &unescape($uname);
 1887:     }
 1888:     if (defined($udom)) {
 1889:         $udom = &unescape($udom);
 1890:     }
 1891: 
 1892:     my $dir_root = $perlvar{'lonDocRoot'};
 1893:     if (($getpropath) || ($getuserdir)) {
 1894:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
 1895:             $dir_root = &propath($udom,$uname);
 1896:             $dir_root =~ s/\/$//;
 1897:         } else {
 1898:             &Failure($client,"refused\n",$userinput);
 1899:             return 1;
 1900:         }
 1901:     } elsif ($alternate_root ne '') {
 1902:         $dir_root = $alternate_root;
 1903:     }
 1904:     if (($dir_root ne '') && ($dir_root ne '/')) {
 1905:         if ($ulsdir =~ /^\//) {
 1906:             $ulsdir = $dir_root.$ulsdir;
 1907:         } else {
 1908:             $ulsdir = $dir_root.'/'.$ulsdir;
 1909:         }
 1910:     }
 1911:     if ($ulsdir =~m{/\.\./}) {
 1912:         &Failure($client,"refused\n",$userinput);
 1913:         return 1;
 1914:     }
 1915:     my $islocal;
 1916:     my @machine_ids = &Apache::lonnet::current_machine_ids();
 1917:     if (grep(/^\Q$clientname\E$/,@machine_ids)) {
 1918:         $islocal = 1;
 1919:     }
 1920:     my $obs;
 1921:     my $rights;
 1922:     my $ulsout='';
 1923:     my $ulsfn;
 1924: 
 1925:     my ($crscheck,$toplevel,$currdom,$currnum,$skip);
 1926:     unless ($islocal) {
 1927:         my ($major,$minor) = split(/\./,$clientversion);
 1928:         if (($major < 2) || ($major == 2 && $minor < 12)) {
 1929:             $crscheck = 1;
 1930:         }
 1931:     }
 1932:     if (-e $ulsdir) {
 1933:         if(-d $ulsdir) {
 1934:             unless (($getpropath) || ($getuserdir) ||
 1935:                     ($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
 1936:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles}) ||
 1937:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain}) && ($islocal))) {
 1938:                 &Failure($client,"refused\n",$userinput);
 1939:                 return 1;
 1940:             }
 1941:             if (($crscheck) &&
 1942:                 ($ulsdir =~ m{^/home/httpd/html/res/($LONCAPA::match_domain)(/?$|/$LONCAPA::match_courseid)})) {
 1943:                 ($currdom,my $posscnum) = ($1,$2);
 1944:                 if (($posscnum eq '') || ($posscnum eq '/')) {
 1945:                     $toplevel = 1;
 1946:                 } else {
 1947:                     $posscnum =~ s{^/+}{};
 1948:                     if (&LONCAPA::Lond::is_course($currdom,$posscnum)) {
 1949:                         $skip = 1;
 1950:                     }
 1951:                 }
 1952:             }
 1953:             if ((!$skip) && (opendir(LSDIR,$ulsdir))) {
 1954:                 while ($ulsfn=readdir(LSDIR)) {
 1955:                     if (($crscheck) && ($toplevel) && ($currdom ne '') &&
 1956:                         ($ulsfn =~ /^$LONCAPA::match_courseid$/) && (-d "$ulsdir/$ulsfn")) {
 1957:                         if (&LONCAPA::Lond::is_course($currdom,$ulsfn)) {
 1958:                             next;
 1959:                         }
 1960:                     }
 1961:                     undef($obs);
 1962:                     undef($rights);
 1963:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1964:                     #We do some obsolete checking here
 1965:                     if(-e $ulsdir.'/'.$ulsfn.".meta") {
 1966:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
 1967:                         my @obsolete=<FILE>;
 1968:                         foreach my $obsolete (@obsolete) {
 1969:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
 1970:                             if($obsolete =~ m|(<copyright>)(default)|) {
 1971:                                 $rights = 1;
 1972:                             }
 1973:                         }
 1974:                     }
 1975:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
 1976:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1977:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1978:                     $ulsout.= &escape($tmp).':';
 1979:                 }
 1980:                 closedir(LSDIR);
 1981:             }
 1982:         } else {
 1983:             unless (($getpropath) || ($getuserdir) ||
 1984:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
 1985:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/}) ||
 1986:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain/$LONCAPA::match_name/}) && ($islocal))) {
 1987:                 &Failure($client,"refused\n",$userinput);
 1988:                 return 1;
 1989:             }
 1990:             my @ulsstats=stat($ulsdir);
 1991:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1992:         }
 1993:     } else {
 1994:         $ulsout='no_such_dir';
 1995:     }
 1996:     if ($ulsout eq '') { $ulsout='empty'; }
 1997:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
 1998:     return 1;
 1999: }
 2000: &register_handler("ls3", \&ls3_handler, 0, 1, 0);
 2001: 
 2002: sub read_lonnet_global {
 2003:     my ($cmd,$tail,$client) = @_;
 2004:     my $userinput = "$cmd:$tail";
 2005:     my $requested = &Apache::lonnet::thaw_unescape($tail);
 2006:     my $result;
 2007:     my %packagevars = (
 2008:                         spareid => \%Apache::lonnet::spareid,
 2009:                         perlvar => \%Apache::lonnet::perlvar,
 2010:                       );
 2011:     my %limit_to = (
 2012:                     perlvar => {
 2013:                                  lonOtherAuthen  => 1,
 2014:                                  lonBalancer     => 1,
 2015:                                  lonVersion      => 1,
 2016:                                  lonAdmEMail     => 1,
 2017:                                  lonSupportEMail => 1,  
 2018:                                  lonSysEMail     => 1,
 2019:                                  lonHostID       => 1,
 2020:                                  lonRole         => 1,
 2021:                                  lonDefDomain    => 1,
 2022:                                  lonLoadLim      => 1,
 2023:                                  lonUserLoadLim  => 1,
 2024:                                }
 2025:                   );
 2026:     if (ref($requested) eq 'HASH') {
 2027:         foreach my $what (keys(%{$requested})) {
 2028:             my $response;
 2029:             my $items = {};
 2030:             if (exists($packagevars{$what})) {
 2031:                 if (ref($limit_to{$what}) eq 'HASH') {
 2032:                     foreach my $varname (keys(%{$packagevars{$what}})) {
 2033:                         if ($limit_to{$what}{$varname}) {
 2034:                             $items->{$varname} = $packagevars{$what}{$varname};
 2035:                         }
 2036:                     }
 2037:                 } else {
 2038:                     $items = $packagevars{$what};
 2039:                 }
 2040:                 if ($what eq 'perlvar') {
 2041:                     if (!exists($packagevars{$what}{'lonBalancer'})) {
 2042:                         if ($dist =~ /^(centos|rhes|fedora|scientific|oracle|rocky|alma)/) {
 2043:                             my $othervarref=LONCAPA::Configuration::read_conf('httpd.conf');
 2044:                             if (ref($othervarref) eq 'HASH') {
 2045:                                 $items->{'lonBalancer'} = $othervarref->{'lonBalancer'};
 2046:                             }
 2047:                         }
 2048:                     }
 2049:                 }
 2050:                 $response = &Apache::lonnet::freeze_escape($items);
 2051:             }
 2052:             $result .= &escape($what).'='.$response.'&';
 2053:         }
 2054:     }
 2055:     $result =~ s/\&$//;
 2056:     &Reply($client,\$result,$userinput);
 2057:     return 1;
 2058: }
 2059: &register_handler("readlonnetglobal", \&read_lonnet_global, 0, 1, 0);
 2060: 
 2061: sub server_devalidatecache_handler {
 2062:     my ($cmd,$tail,$client) = @_;
 2063:     my $userinput = "$cmd:$tail";
 2064:     my $items = &unescape($tail);
 2065:     my @cached = split(/\&/,$items);
 2066:     foreach my $key (@cached) {
 2067:         if ($key =~ /:/) {
 2068:             my ($name,$id) = map { &unescape($_); } split(/:/,$key);
 2069:             &Apache::lonnet::devalidate_cache_new($name,$id);
 2070:         }
 2071:     }
 2072:     my $result = 'ok';
 2073:     &Reply($client,\$result,$userinput);
 2074:     return 1;
 2075: }
 2076: &register_handler("devalidatecache", \&server_devalidatecache_handler, 0, 1, 0);
 2077: 
 2078: sub server_timezone_handler {
 2079:     my ($cmd,$tail,$client) = @_;
 2080:     my $userinput = "$cmd:$tail";
 2081:     my $timezone;
 2082:     my $clockfile = '/etc/sysconfig/clock'; # Fedora/CentOS/SuSE
 2083:     my $tzfile = '/etc/timezone'; # Debian/Ubuntu
 2084:     if (-e $clockfile) {
 2085:         if (open(my $fh,"<$clockfile")) {
 2086:             while (<$fh>) {
 2087:                 next if (/^[\#\s]/);
 2088:                 if (/^(?:TIME)?ZONE\s*=\s*['"]?\s*([\w\/]+)/) {
 2089:                     $timezone = $1;
 2090:                     last;
 2091:                 }
 2092:             }
 2093:             close($fh);
 2094:         }
 2095:     } elsif (-e $tzfile) {
 2096:         if (open(my $fh,"<$tzfile")) {
 2097:             $timezone = <$fh>;
 2098:             close($fh);
 2099:             chomp($timezone);
 2100:             if ($timezone =~ m{^Etc/(\w+)$}) {
 2101:                 $timezone = $1;
 2102:             }
 2103:         }
 2104:     }
 2105:     &Reply($client,\$timezone,$userinput); # This supports debug logging.
 2106:     return 1;
 2107: }
 2108: &register_handler("servertimezone", \&server_timezone_handler, 0, 1, 0);
 2109: 
 2110: sub server_loncaparev_handler {
 2111:     my ($cmd,$tail,$client) = @_;
 2112:     my $userinput = "$cmd:$tail";
 2113:     &Reply($client,\$perlvar{'lonVersion'},$userinput);
 2114:     return 1;
 2115: }
 2116: &register_handler("serverloncaparev", \&server_loncaparev_handler, 0, 1, 0);
 2117: 
 2118: sub server_homeID_handler {
 2119:     my ($cmd,$tail,$client) = @_;
 2120:     my $userinput = "$cmd:$tail";
 2121:     &Reply($client,\$perlvar{'lonHostID'},$userinput);
 2122:     return 1;
 2123: }
 2124: &register_handler("serverhomeID", \&server_homeID_handler, 0, 1, 0);
 2125: 
 2126: sub server_distarch_handler {
 2127:     my ($cmd,$tail,$client) = @_;
 2128:     my $userinput = "$cmd:$tail";
 2129:     my $reply = &distro_and_arch();
 2130:     &Reply($client,\$reply,$userinput);
 2131:     return 1;
 2132: }
 2133: &register_handler("serverdistarch", \&server_distarch_handler, 0, 1, 0);
 2134: 
 2135: sub server_certs_handler {
 2136:     my ($cmd,$tail,$client) = @_;
 2137:     my $userinput = "$cmd:$tail";
 2138:     my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
 2139:     my $result = &LONCAPA::Lond::server_certs(\%perlvar,$perlvar{'lonHostID'},$hostname);
 2140:     &Reply($client,\$result,$userinput);
 2141:     return;
 2142: }
 2143: &register_handler("servercerts", \&server_certs_handler, 0, 1, 0);
 2144: 
 2145: #   Process a reinit request.  Reinit requests that either
 2146: #   lonc or lond be reinitialized so that an updated 
 2147: #   host.tab or domain.tab can be processed.
 2148: #
 2149: # Parameters:
 2150: #      $cmd    - the actual keyword that invoked us.
 2151: #      $tail   - the tail of the request that invoked us.
 2152: #      $client - File descriptor connected to the client
 2153: #  Returns:
 2154: #      1       - Ok to continue processing.
 2155: #      0       - Program should exit
 2156: #  Implicit output:
 2157: #     a reply is sent to the client.
 2158: #
 2159: sub reinit_process_handler {
 2160:     my ($cmd, $tail, $client) = @_;
 2161:    
 2162:     my $userinput = "$cmd:$tail";
 2163:    
 2164:     my $cert = &GetCertificate($userinput);
 2165:     if(&ValidManager($cert)) {
 2166: 	chomp($userinput);
 2167: 	my $reply = &ReinitProcess($userinput);
 2168: 	&Reply( $client,  \$reply, $userinput);
 2169:     } else {
 2170: 	&Failure( $client, "refused\n", $userinput);
 2171:     }
 2172:     return 1;
 2173: }
 2174: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
 2175: 
 2176: #  Process the editing script for a table edit operation.
 2177: #  the editing operation must be encrypted and requested by
 2178: #  a manager host.
 2179: #
 2180: # Parameters:
 2181: #      $cmd    - the actual keyword that invoked us.
 2182: #      $tail   - the tail of the request that invoked us.
 2183: #      $client - File descriptor connected to the client
 2184: #  Returns:
 2185: #      1       - Ok to continue processing.
 2186: #      0       - Program should exit
 2187: #  Implicit output:
 2188: #     a reply is sent to the client.
 2189: #
 2190: sub edit_table_handler {
 2191:     my ($command, $tail, $client) = @_;
 2192:    
 2193:     my $userinput = "$command:$tail";
 2194: 
 2195:     my $cert = &GetCertificate($userinput);
 2196:     if(&ValidManager($cert)) {
 2197: 	my($filetype, $script) = split(/:/, $tail);
 2198: 	if (($filetype eq "hosts") || 
 2199: 	    ($filetype eq "domain")) {
 2200: 	    if($script ne "") {
 2201: 		&Reply($client,              # BUGBUG - EditFile
 2202: 		      &EditFile($userinput), #   could fail.
 2203: 		      $userinput);
 2204: 	    } else {
 2205: 		&Failure($client,"refused\n",$userinput);
 2206: 	    }
 2207: 	} else {
 2208: 	    &Failure($client,"refused\n",$userinput);
 2209: 	}
 2210:     } else {
 2211: 	&Failure($client,"refused\n",$userinput);
 2212:     }
 2213:     return 1;
 2214: }
 2215: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
 2216: 
 2217: #
 2218: #   Authenticate a user against the LonCAPA authentication
 2219: #   database.  Note that there are several authentication
 2220: #   possibilities:
 2221: #   - unix     - The user can be authenticated against the unix
 2222: #                password file.
 2223: #   - internal - The user can be authenticated against a purely 
 2224: #                internal per user password file.
 2225: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
 2226: #                ticket granting authority.
 2227: #   - user     - The person tailoring LonCAPA can supply a user authentication
 2228: #                mechanism that is per system.
 2229: #
 2230: # Parameters:
 2231: #    $cmd      - The command that got us here.
 2232: #    $tail     - Tail of the command (remaining parameters).
 2233: #    $client   - File descriptor connected to client.
 2234: # Returns
 2235: #     0        - Requested to exit, caller should shut down.
 2236: #     1        - Continue processing.
 2237: # Implicit inputs:
 2238: #    The authentication systems describe above have their own forms of implicit
 2239: #    input into the authentication process that are described above.
 2240: #
 2241: sub authenticate_handler {
 2242:     my ($cmd, $tail, $client) = @_;
 2243: 
 2244:     
 2245:     #  Regenerate the full input line 
 2246:     
 2247:     my $userinput  = $cmd.":".$tail;
 2248:     
 2249:     #  udom    - User's domain.
 2250:     #  uname   - Username.
 2251:     #  upass   - User's password.
 2252:     #  checkdefauth - Pass to validate_user() to try authentication
 2253:     #                 with default auth type(s) if no user account.
 2254:     #  clientcancheckhost - Passed by clients with functionality in lonauth.pm
 2255:     #                       to check if session can be hosted.
 2256:     
 2257:     my ($udom, $uname, $upass, $checkdefauth, $clientcancheckhost)=split(/:/,$tail);
 2258:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass,  checkdefauth = $checkdefauth");
 2259:     chomp($upass);
 2260:     $upass=&unescape($upass);
 2261: 
 2262:     my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
 2263:     if($pwdcorrect) {
 2264:         my $canhost = 1;
 2265:         unless ($clientcancheckhost) {
 2266:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 2267:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 2268:             my @intdoms;
 2269:             my $internet_names = &Apache::lonnet::get_internet_names($clientname);
 2270:             if (ref($internet_names) eq 'ARRAY') {
 2271:                 @intdoms = @{$internet_names};
 2272:             }
 2273:             unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
 2274:                 my ($remote,$hosted);
 2275:                 my $remotesession = &get_usersession_config($udom,'remotesession');
 2276:                 if (ref($remotesession) eq 'HASH') {
 2277:                     $remote = $remotesession->{'remote'};
 2278:                 }
 2279:                 my $hostedsession = &get_usersession_config($clienthomedom,'hostedsession');
 2280:                 if (ref($hostedsession) eq 'HASH') {
 2281:                     $hosted = $hostedsession->{'hosted'};
 2282:                 }
 2283:                 $canhost = &Apache::lonnet::can_host_session($udom,$clientname,
 2284:                                                              $clientversion,
 2285:                                                              $remote,$hosted);
 2286:             }
 2287:         }
 2288:         if ($canhost) {               
 2289:             &Reply( $client, "authorized\n", $userinput);
 2290:         } else {
 2291:             &Reply( $client, "not_allowed_to_host\n", $userinput);
 2292:         }
 2293: 	#
 2294: 	#  Bad credentials: Failed to authorize
 2295: 	#
 2296:     } else {
 2297: 	&Failure( $client, "non_authorized\n", $userinput);
 2298:     }
 2299: 
 2300:     return 1;
 2301: }
 2302: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
 2303: 
 2304: #
 2305: #   Change a user's password.  Note that this function is complicated by
 2306: #   the fact that a user may be authenticated in more than one way:
 2307: #   At present, we are not able to change the password for all types of
 2308: #   authentication methods.  Only for:
 2309: #      unix    - unix password or shadow passoword style authentication.
 2310: #      local   - Locally written authentication mechanism.
 2311: #   For now, kerb4 and kerb5 password changes are not supported and result
 2312: #   in an error.
 2313: # FUTURE WORK:
 2314: #    Support kerberos passwd changes?
 2315: # Parameters:
 2316: #    $cmd      - The command that got us here.
 2317: #    $tail     - Tail of the command (remaining parameters).
 2318: #    $client   - File descriptor connected to client.
 2319: # Returns
 2320: #     0        - Requested to exit, caller should shut down.
 2321: #     1        - Continue processing.
 2322: # Implicit inputs:
 2323: #    The authentication systems describe above have their own forms of implicit
 2324: #    input into the authentication process that are described above.
 2325: sub change_password_handler {
 2326:     my ($cmd, $tail, $client) = @_;
 2327: 
 2328:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
 2329: 
 2330:     #
 2331:     #  udom  - user's domain.
 2332:     #  uname - Username.
 2333:     #  upass - Current password.
 2334:     #  npass - New password.
 2335:     #  context - Context in which this was called 
 2336:     #            (preferences or reset_by_email).
 2337:     #  lonhost - HostID of server where request originated 
 2338:    
 2339:     my ($udom,$uname,$upass,$npass,$context,$lonhost)=split(/:/,$tail);
 2340: 
 2341:     $upass=&unescape($upass);
 2342:     $npass=&unescape($npass);
 2343:     &Debug("Trying to change password for $uname");
 2344: 
 2345:     # First require that the user can be authenticated with their
 2346:     # old password unless context was 'reset_by_email':
 2347:     
 2348:     my ($validated,$failure);
 2349:     if ($context eq 'reset_by_email') {
 2350:         if ($lonhost eq '') {
 2351:             $failure = 'invalid_client';
 2352:         } else {
 2353:             $validated = 1;
 2354:         }
 2355:     } else {
 2356:         $validated = &validate_user($udom, $uname, $upass);
 2357:     }
 2358:     if($validated) {
 2359: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
 2360: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
 2361:         my $notunique;
 2362: 	if ($howpwd eq 'internal') {
 2363: 	    &Debug("internal auth");
 2364:             my $ncpass = &hash_passwd($udom,$npass);
 2365:             my (undef,$method,@rest) = split(/!/,$contentpwd);
 2366:             if ($method eq 'bcrypt') {
 2367:                 my %passwdconf = &Apache::lonnet::get_passwdconf($udom);
 2368:                 if (($passwdconf{'numsaved'}) && ($passwdconf{'numsaved'} =~ /^\d+$/)) {
 2369:                     my @oldpasswds;
 2370:                     my $userpath = &propath($udom,$uname);
 2371:                     my $fullpath = $userpath.'/oldpasswds';
 2372:                     if (-d $userpath) {
 2373:                         my @oldfiles;
 2374:                         if (-e $fullpath) {
 2375:                             if (opendir(my $dir,$fullpath)) {
 2376:                                 (@oldfiles) = grep(/^\d+$/,readdir($dir));
 2377:                                 closedir($dir);
 2378:                             }
 2379:                             if (@oldfiles) {
 2380:                                 @oldfiles = sort { $b <=> $a } (@oldfiles);
 2381:                                 my $numremoved = 0;
 2382:                                 for (my $i=0; $i<@oldfiles; $i++) {
 2383:                                     if ($i>=$passwdconf{'numsaved'}) {
 2384:                                         if (-f "$fullpath/$oldfiles[$i]") {
 2385:                                             if (unlink("$fullpath/$oldfiles[$i]")) {
 2386:                                                 $numremoved ++;
 2387:                                             }
 2388:                                         }
 2389:                                     } elsif (open(my $fh,'<',"$fullpath/$oldfiles[$i]")) {
 2390:                                         while (my $line = <$fh>) {
 2391:                                             push(@oldpasswds,$line);
 2392:                                         }
 2393:                                         close($fh);
 2394:                                     }
 2395:                                 }
 2396:                                 if ($numremoved) {
 2397:                                     &logthis("unlinked $numremoved old password files for $uname:$udom");
 2398:                                 }
 2399:                             }
 2400:                         }
 2401:                         push(@oldpasswds,$contentpwd);
 2402:                         foreach my $item (@oldpasswds) {
 2403:                             my (undef,$method,@rest) = split(/!/,$item);
 2404:                             if ($method eq 'bcrypt') {
 2405:                                 my $result = &hash_passwd($udom,$npass,@rest);
 2406:                                 if ($result eq $item) {
 2407:                                     $notunique = 1;
 2408:                                     last;
 2409:                                 }
 2410:                             }
 2411:                         }
 2412:                         unless ($notunique) {
 2413:                             unless (-e $fullpath) {
 2414:                                 if (&mkpath("$fullpath/")) {
 2415:                                     chmod(0700,$fullpath);
 2416:                                 }
 2417:                             }
 2418:                             if (-d $fullpath) {
 2419:                                 my $now = time;
 2420:                                 if (open(my $fh,'>',"$fullpath/$now")) {
 2421:                                     print $fh $contentpwd;
 2422:                                     close($fh);
 2423:                                     chmod(0400,"$fullpath/$now");
 2424:                                 }
 2425:                             }
 2426:                         }
 2427:                     }
 2428:                 }
 2429:             }
 2430:             if ($notunique) {
 2431:                 my $msg="Result of password change for $uname:$udom - password matches one used before";
 2432:                 if ($lonhost) {
 2433:                     $msg .= " - request originated from: $lonhost";
 2434:                 }
 2435:                 &logthis($msg);
 2436:                 &Reply($client, "prioruse\n", $userinput);
 2437: 	    } elsif (&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
 2438: 		my $msg="Result of password change for $uname: pwchange_success";
 2439:                 if ($lonhost) {
 2440:                     $msg .= " - request originated from: $lonhost";
 2441:                 }
 2442:                 &logthis($msg);
 2443:                 &update_passwd_history($uname,$udom,$howpwd,$context);
 2444: 		&Reply($client, "ok\n", $userinput);
 2445: 	    } else {
 2446: 		&logthis("Unable to open $uname passwd "               
 2447: 			 ."to change password");
 2448: 		&Failure( $client, "non_authorized\n",$userinput);
 2449: 	    }
 2450: 	} elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
 2451: 	    my $result = &change_unix_password($uname, $npass);
 2452:             if ($result eq 'ok') {
 2453:                 &update_passwd_history($uname,$udom,$howpwd,$context);
 2454:             }
 2455: 	    &logthis("Result of password change for $uname: ".
 2456: 		     $result);
 2457: 	    &Reply($client, \$result, $userinput);
 2458: 	} else {
 2459: 	    # this just means that the current password mode is not
 2460: 	    # one we know how to change (e.g the kerberos auth modes or
 2461: 	    # locally written auth handler).
 2462: 	    #
 2463: 	    &Failure( $client, "auth_mode_error\n", $userinput);
 2464: 	}  
 2465:     } else {
 2466: 	if ($failure eq '') {
 2467: 	    $failure = 'non_authorized';
 2468: 	}
 2469: 	&Failure( $client, "$failure\n", $userinput);
 2470:     }
 2471: 
 2472:     return 1;
 2473: }
 2474: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
 2475: 
 2476: sub hash_passwd {
 2477:     my ($domain,$plainpass,@rest) = @_;
 2478:     my ($salt,$cost);
 2479:     if (@rest) {
 2480:         $cost = $rest[0];
 2481:         # salt is first 22 characters, base-64 encoded by bcrypt
 2482:         my $plainsalt = substr($rest[1],0,22);
 2483:         $salt = Crypt::Eksblowfish::Bcrypt::de_base64($plainsalt);
 2484:     } else {
 2485:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2486:         my $defaultcost = $domdefaults{'intauth_cost'};
 2487:         if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
 2488:             $cost = 10;
 2489:         } else {
 2490:             $cost = $defaultcost;
 2491:         }
 2492:         # Generate random 16-octet base64 salt
 2493:         $salt = "";
 2494:         $salt .= pack("C", int rand(256)) for 1..16;
 2495:     }
 2496:     my $hash = &Crypt::Eksblowfish::Bcrypt::bcrypt_hash({
 2497:         key_nul => 1,
 2498:         cost    => $cost,
 2499:         salt    => $salt,
 2500:     }, Digest::SHA::sha512(Encode::encode('UTF-8',$plainpass)));
 2501: 
 2502:     my $result = join("!", "", "bcrypt", sprintf("%02d",$cost),
 2503:                 &Crypt::Eksblowfish::Bcrypt::en_base64($salt).
 2504:                 &Crypt::Eksblowfish::Bcrypt::en_base64($hash));
 2505:     return $result;
 2506: }
 2507: 
 2508: #
 2509: #   Create a new user.  User in this case means a lon-capa user.
 2510: #   The user must either already exist in some authentication realm
 2511: #   like kerberos or the /etc/passwd.  If not, a user completely local to
 2512: #   this loncapa system is created.
 2513: #
 2514: # Parameters:
 2515: #    $cmd      - The command that got us here.
 2516: #    $tail     - Tail of the command (remaining parameters).
 2517: #    $client   - File descriptor connected to client.
 2518: # Returns
 2519: #     0        - Requested to exit, caller should shut down.
 2520: #     1        - Continue processing.
 2521: # Implicit inputs:
 2522: #    The authentication systems describe above have their own forms of implicit
 2523: #    input into the authentication process that are described above.
 2524: sub add_user_handler {
 2525: 
 2526:     my ($cmd, $tail, $client) = @_;
 2527: 
 2528: 
 2529:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
 2530:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
 2531: 
 2532:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
 2533: 
 2534: 
 2535:     if($udom eq $currentdomainid) { # Reject new users for other domains...
 2536: 	
 2537: 	my $oldumask=umask(0077);
 2538: 	chomp($npass);
 2539: 	$npass=&unescape($npass);
 2540: 	my $passfilename  = &password_path($udom, $uname);
 2541: 	&Debug("Password file created will be:".$passfilename);
 2542: 	if (-e $passfilename) {
 2543: 	    &Failure( $client, "already_exists\n", $userinput);
 2544: 	} else {
 2545: 	    my $fperror='';
 2546: 	    if (!&mkpath($passfilename)) {
 2547: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
 2548: 		    ."makeuser";
 2549: 	    }
 2550: 	    unless ($fperror) {
 2551: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
 2552:                                              $passfilename,'makeuser');
 2553: 		&Reply($client,\$result, $userinput);     #BUGBUG - could be fail
 2554: 	    } else {
 2555: 		&Failure($client, \$fperror, $userinput);
 2556: 	    }
 2557: 	}
 2558: 	umask($oldumask);
 2559:     }  else {
 2560: 	&Failure($client, "not_right_domain\n",
 2561: 		$userinput);	# Even if we are multihomed.
 2562:     
 2563:     }
 2564:     return 1;
 2565: 
 2566: }
 2567: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
 2568: 
 2569: #
 2570: #   Change the authentication method of a user.  Note that this may
 2571: #   also implicitly change the user's password if, for example, the user is
 2572: #   joining an existing authentication realm.  Known authentication realms at
 2573: #   this time are:
 2574: #    internal   - Purely internal password file (only loncapa knows this user)
 2575: #    local      - Institutionally written authentication module.
 2576: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
 2577: #    kerb4      - kerberos version 4
 2578: #    kerb5      - kerberos version 5
 2579: #
 2580: # Parameters:
 2581: #    $cmd      - The command that got us here.
 2582: #    $tail     - Tail of the command (remaining parameters).
 2583: #    $client   - File descriptor connected to client.
 2584: # Returns
 2585: #     0        - Requested to exit, caller should shut down.
 2586: #     1        - Continue processing.
 2587: # Implicit inputs:
 2588: #    The authentication systems describe above have their own forms of implicit
 2589: #    input into the authentication process that are described above.
 2590: # NOTE:
 2591: #   This is also used to change the authentication credential values (e.g. passwd).
 2592: #   
 2593: #
 2594: sub change_authentication_handler {
 2595: 
 2596:     my ($cmd, $tail, $client) = @_;
 2597:    
 2598:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
 2599: 
 2600:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
 2601:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
 2602:     if ($udom ne $currentdomainid) {
 2603: 	&Failure( $client, "not_right_domain\n", $client);
 2604:     } else {
 2605: 	
 2606: 	chomp($npass);
 2607: 	
 2608: 	$npass=&unescape($npass);
 2609: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
 2610: 	my $passfilename = &password_path($udom, $uname);
 2611: 	if ($passfilename) {	# Not allowed to create a new user!!
 2612: 	    # If just changing the unix passwd. need to arrange to run
 2613: 	    # passwd since otherwise make_passwd_file will fail as 
 2614: 	    # creation of unix authenticated users is no longer supported
 2615:             # except from the command line, when running make_domain_coordinator.pl
 2616: 
 2617: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
 2618: 		my $result = &change_unix_password($uname, $npass);
 2619: 		&logthis("Result of password change for $uname: ".$result);
 2620: 		if ($result eq "ok") {
 2621:                     &update_passwd_history($uname,$udom,$umode,'changeuserauth'); 
 2622: 		    &Reply($client, \$result);
 2623: 		} else {
 2624: 		    &Failure($client, \$result);
 2625: 		}
 2626: 	    } else {
 2627: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
 2628:                                              $passfilename,'changeuserauth');
 2629: 		#
 2630: 		#  If the current auth mode is internal, and the old auth mode was
 2631: 		#  unix, or krb*,  and the user is an author for this domain,
 2632: 		#  re-run manage_permissions for that role in order to be able
 2633: 		#  to take ownership of the construction space back to www:www
 2634: 		#
 2635: 
 2636: 
 2637: 		&Reply($client, \$result, $userinput);
 2638: 	    }
 2639: 	       
 2640: 
 2641: 	} else {	       
 2642: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
 2643: 	}
 2644:     }
 2645:     return 1;
 2646: }
 2647: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
 2648: 
 2649: sub update_passwd_history {
 2650:     my ($uname,$udom,$umode,$context) = @_;
 2651:     my $proname=&propath($udom,$uname);
 2652:     my $now = time;
 2653:     if (open(my $fh,">>$proname/passwd.log")) {
 2654:         print $fh "$now:$umode:$context\n";
 2655:         close($fh);
 2656:     }
 2657:     return;
 2658: }
 2659: 
 2660: sub inst_unamemap_check {
 2661:     my ($cmd, $tail, $client)   = @_;
 2662:     my $userinput               = "$cmd:$tail";
 2663:     my %rulecheck;
 2664:     my $outcome;
 2665:     my ($udom,$uname,@rules) = split(/:/,$tail);
 2666:     $udom = &unescape($udom);
 2667:     $uname = &unescape($uname);
 2668:     @rules = map {&unescape($_);} (@rules);
 2669:     eval {
 2670:         local($SIG{__DIE__})='DEFAULT';
 2671:         $outcome = &localenroll::unamemap_check($udom,$uname,\@rules,\%rulecheck);
 2672:     };
 2673:     if (!$@) {
 2674:         if ($outcome eq 'ok') {
 2675:             my $result='';
 2676:             foreach my $key (keys(%rulecheck)) {
 2677:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
 2678:             }
 2679:             &Reply($client,\$result,$userinput);
 2680:         } else {
 2681:             &Reply($client,"error\n", $userinput);
 2682:         }
 2683:     } else {
 2684:         &Failure($client,"unknown_cmd\n",$userinput);
 2685:     }
 2686: }
 2687: &register_handler("instunamemapcheck",\&inst_unamemap_check,0,1,0);
 2688: 
 2689: 
 2690: #
 2691: #   Determines if this is the home server for a user.  The home server
 2692: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
 2693: #   to do is determine if this file exists.
 2694: #
 2695: # Parameters:
 2696: #    $cmd      - The command that got us here.
 2697: #    $tail     - Tail of the command (remaining parameters).
 2698: #    $client   - File descriptor connected to client.
 2699: # Returns
 2700: #     0        - Requested to exit, caller should shut down.
 2701: #     1        - Continue processing.
 2702: # Implicit inputs:
 2703: #    The authentication systems describe above have their own forms of implicit
 2704: #    input into the authentication process that are described above.
 2705: #
 2706: sub is_home_handler {
 2707:     my ($cmd, $tail, $client) = @_;
 2708:    
 2709:     my $userinput  = "$cmd:$tail";
 2710:    
 2711:     my ($udom,$uname)=split(/:/,$tail);
 2712:     chomp($uname);
 2713:     my $passfile = &password_filename($udom, $uname);
 2714:     if($passfile) {
 2715: 	&Reply( $client, "found\n", $userinput);
 2716:     } else {
 2717: 	&Failure($client, "not_found\n", $userinput);
 2718:     }
 2719:     return 1;
 2720: }
 2721: &register_handler("home", \&is_home_handler, 0,1,0);
 2722: 
 2723: #
 2724: #   Process an update request for a resource.
 2725: #   A resource has been modified that we hold a subscription to.
 2726: #   If the resource is not local, then we must update, or at least invalidate our
 2727: #   cached copy of the resource. 
 2728: # Parameters:
 2729: #    $cmd      - The command that got us here.
 2730: #    $tail     - Tail of the command (remaining parameters).
 2731: #    $client   - File descriptor connected to client.
 2732: # Returns
 2733: #     0        - Requested to exit, caller should shut down.
 2734: #     1        - Continue processing.
 2735: # Implicit inputs:
 2736: #    The authentication systems describe above have their own forms of implicit
 2737: #    input into the authentication process that are described above.
 2738: #
 2739: sub update_resource_handler {
 2740: 
 2741:     my ($cmd, $tail, $client) = @_;
 2742:    
 2743:     my $userinput = "$cmd:$tail";
 2744:    
 2745:     my $fname= $tail;		# This allows interactive testing
 2746: 
 2747: 
 2748:     my $ownership=ishome($fname);
 2749:     if ($ownership eq 'not_owner') {
 2750: 	if (-e $fname) {
 2751:             # Delete preview file, if exists
 2752:             unlink("$fname.tmp");
 2753:             # Get usage stats
 2754: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
 2755: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
 2756: 	    my $now=time;
 2757: 	    my $since=$now-$atime;
 2758:             # If the file has not been used within lonExpire seconds,
 2759:             # unsubscribe from it and delete local copy
 2760: 	    if ($since>$perlvar{'lonExpire'}) {
 2761: 		my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
 2762: 		&devalidate_meta_cache($fname);
 2763: 		unlink("$fname");
 2764: 		unlink("$fname.meta");
 2765: 	    } else {
 2766:             # Yes, this is in active use. Get a fresh copy. Since it might be in
 2767:             # very active use and huge (like a movie), copy it to "in.transfer" filename first.
 2768: 		my $transname="$fname.in.transfer";
 2769: 		my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
 2770: 		my $response;
 2771: # FIXME: cannot replicate files that take more than two minutes to transfer -- needs checking now 1200s timeout used
 2772: # for LWP request.
 2773: 		my $request=new HTTP::Request('GET',"$remoteurl");
 2774:                 $response=&LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,0,1);
 2775: 		if ($response->is_error()) {
 2776:                     my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
 2777:                     &devalidate_meta_cache($fname);
 2778:                     if (-e $transname) {
 2779:                         unlink($transname);
 2780:                     }
 2781:                     unlink($fname);
 2782: 		    my $message=$response->status_line;
 2783: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
 2784: 		} else {
 2785: 		    if ($remoteurl!~/\.meta$/) {
 2786: 			my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2787:                         my $mresponse = &LONCAPA::LWPReq::makerequest($clientname,$mrequest,$fname.'.meta',\%perlvar,120,0,1);
 2788: 			if ($mresponse->is_error()) {
 2789: 			    unlink($fname.'.meta');
 2790: 			}
 2791: 		    }
 2792:                     # we successfully transfered, copy file over to real name
 2793: 		    rename($transname,$fname);
 2794: 		    &devalidate_meta_cache($fname);
 2795: 		}
 2796: 	    }
 2797: 	    &Reply( $client, "ok\n", $userinput);
 2798: 	} else {
 2799: 	    &Failure($client, "not_found\n", $userinput);
 2800: 	}
 2801:     } else {
 2802: 	&Failure($client, "rejected\n", $userinput);
 2803:     }
 2804:     return 1;
 2805: }
 2806: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
 2807: 
 2808: sub devalidate_meta_cache {
 2809:     my ($url) = @_;
 2810:     use Cache::Memcached;
 2811:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
 2812:     $url = &Apache::lonnet::declutter($url);
 2813:     $url =~ s-\.meta$--;
 2814:     my $id = &escape('meta:'.$url);
 2815:     $memcache->delete($id);
 2816: }
 2817: 
 2818: #
 2819: #   Fetch a user file from a remote server to the user's home directory
 2820: #   userfiles subdir.
 2821: # Parameters:
 2822: #    $cmd      - The command that got us here.
 2823: #    $tail     - Tail of the command (remaining parameters).
 2824: #    $client   - File descriptor connected to client.
 2825: # Returns
 2826: #     0        - Requested to exit, caller should shut down.
 2827: #     1        - Continue processing.
 2828: #
 2829: sub fetch_user_file_handler {
 2830: 
 2831:     my ($cmd, $tail, $client) = @_;
 2832: 
 2833:     my $userinput = "$cmd:$tail";
 2834:     my $fname           = $tail;
 2835:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
 2836:     my $udir=&propath($udom,$uname).'/userfiles';
 2837:     unless (-e $udir) {
 2838: 	mkdir($udir,0770); 
 2839:     }
 2840:     Debug("fetch user file for $fname");
 2841:     if (-e $udir) {
 2842: 	$ufile=~s/^[\.\~]+//;
 2843: 
 2844: 	# IF necessary, create the path right down to the file.
 2845: 	# Note that any regular files in the way of this path are
 2846: 	# wiped out to deal with some earlier folly of mine.
 2847: 
 2848: 	if (!&mkpath($udir.'/'.$ufile)) {
 2849: 	    &Failure($client, "unable_to_create\n", $userinput);	    
 2850: 	}
 2851: 
 2852: 	my $destname=$udir.'/'.$ufile;
 2853: 	my $transname=$udir.'/'.$ufile.'.in.transit';
 2854:         my $clientprotocol=$Apache::lonnet::protocol{$clientname};
 2855:         $clientprotocol = 'http' if ($clientprotocol ne 'https');
 2856: 	my $clienthost = &Apache::lonnet::hostname($clientname);
 2857: 	my $remoteurl=$clientprotocol.'://'.$clienthost.'/userfiles/'.$fname;
 2858: 	my $response;
 2859: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
 2860: 	my $request=new HTTP::Request('GET',"$remoteurl");
 2861:         my $verifycert = 1;
 2862:         my @machine_ids = &Apache::lonnet::current_machine_ids();
 2863:         if (grep(/^\Q$clientname\E$/,@machine_ids)) {
 2864:             $verifycert = 0;
 2865:         }
 2866:         $response = &LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,$verifycert);
 2867: 	if ($response->is_error()) {
 2868: 	    unlink($transname);
 2869: 	    my $message=$response->status_line;
 2870: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
 2871: 	    &Failure($client, "failed\n", $userinput);
 2872: 	} else {
 2873: 	    Debug("Renaming $transname to $destname");
 2874: 	    if (!rename($transname,$destname)) {
 2875: 		&logthis("Unable to move $transname to $destname");
 2876: 		unlink($transname);
 2877: 		&Failure($client, "failed\n", $userinput);
 2878: 	    } else {
 2879:                 if ($fname =~ /^default.+\.(page|sequence)$/) {
 2880:                     my ($major,$minor) = split(/\./,$clientversion);
 2881:                     if (($major < 2) || ($major == 2 && $minor < 11)) {
 2882:                         my $now = time;
 2883:                         &Apache::lonnet::do_cache_new('crschange',$udom.'_'.$uname,$now,600);
 2884:                         my $key = &escape('internal.contentchange');
 2885:                         my $what = "$key=$now";
 2886:                         my $hashref = &tie_user_hash($udom,$uname,'environment',
 2887:                                                      &GDBM_WRCREAT(),"P",$what);
 2888:                         if ($hashref) {
 2889:                             $hashref->{$key}=$now;
 2890:                             if (!&untie_user_hash($hashref)) {
 2891:                                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
 2892:                                          "when updating internal.contentchange");
 2893:                             }
 2894:                         }
 2895:                     }
 2896:                 }
 2897: 		&Reply($client, "ok\n", $userinput);
 2898: 	    }
 2899: 	}   
 2900:     } else {
 2901: 	&Failure($client, "not_home\n", $userinput);
 2902:     }
 2903:     return 1;
 2904: }
 2905: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
 2906: 
 2907: #
 2908: #   Remove a file from a user's home directory userfiles subdirectory.
 2909: # Parameters:
 2910: #    cmd   - the Lond request keyword that got us here.
 2911: #    tail  - the part of the command past the keyword.
 2912: #    client- File descriptor connected with the client.
 2913: #
 2914: # Returns:
 2915: #    1    - Continue processing.
 2916: sub remove_user_file_handler {
 2917:     my ($cmd, $tail, $client) = @_;
 2918: 
 2919:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
 2920: 
 2921:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
 2922:     if ($ufile =~m|/\.\./|) {
 2923: 	# any files paths with /../ in them refuse 
 2924: 	# to deal with
 2925: 	&Failure($client, "refused\n", "$cmd:$tail");
 2926:     } else {
 2927: 	my $udir = &propath($udom,$uname);
 2928: 	if (-e $udir) {
 2929: 	    my $file=$udir.'/userfiles/'.$ufile;
 2930: 	    if (-e $file) {
 2931: 		#
 2932: 		#   If the file is a regular file unlink is fine...
 2933: 		#   However it's possible the client wants a dir 
 2934: 		#   removed, in which case rmdir is more appropriate.
 2935: 		#   Note: rmdir will only remove an empty directory.
 2936: 		#
 2937: 	        if (-f $file){
 2938: 		    unlink($file);
 2939:                     # for html files remove the associated .bak file 
 2940:                     # which may have been created by the editor.
 2941:                     if ($ufile =~ m{^((docs|supplemental)/(?:\d+|default)/\d+(?:|/.+)/)[^/]+\.x?html?$}i) {
 2942:                         my $path = $1;
 2943:                         if (-e $file.'.bak') {
 2944:                             unlink($file.'.bak');
 2945:                         }
 2946:                     }
 2947: 		} elsif(-d $file) {
 2948: 		    rmdir($file);
 2949: 		}
 2950: 		if (-e $file) {
 2951: 		    #  File is still there after we deleted it ?!?
 2952: 
 2953: 		    &Failure($client, "failed\n", "$cmd:$tail");
 2954: 		} else {
 2955: 		    &Reply($client, "ok\n", "$cmd:$tail");
 2956: 		}
 2957: 	    } else {
 2958: 		&Failure($client, "not_found\n", "$cmd:$tail");
 2959: 	    }
 2960: 	} else {
 2961: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 2962: 	}
 2963:     }
 2964:     return 1;
 2965: }
 2966: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
 2967: 
 2968: #
 2969: #   make a directory in a user's home directory userfiles subdirectory.
 2970: # Parameters:
 2971: #    cmd   - the Lond request keyword that got us here.
 2972: #    tail  - the part of the command past the keyword.
 2973: #    client- File descriptor connected with the client.
 2974: #
 2975: # Returns:
 2976: #    1    - Continue processing.
 2977: sub mkdir_user_file_handler {
 2978:     my ($cmd, $tail, $client) = @_;
 2979: 
 2980:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
 2981:     $dir=&unescape($dir);
 2982:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
 2983:     if ($ufile =~m|/\.\./|) {
 2984: 	# any files paths with /../ in them refuse 
 2985: 	# to deal with
 2986: 	&Failure($client, "refused\n", "$cmd:$tail");
 2987:     } else {
 2988: 	my $udir = &propath($udom,$uname);
 2989: 	if (-e $udir) {
 2990: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
 2991: 	    if (!&mkpath($newdir)) {
 2992: 		&Failure($client, "failed\n", "$cmd:$tail");
 2993: 	    }
 2994: 	    &Reply($client, "ok\n", "$cmd:$tail");
 2995: 	} else {
 2996: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 2997: 	}
 2998:     }
 2999:     return 1;
 3000: }
 3001: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
 3002: 
 3003: #
 3004: #   rename a file in a user's home directory userfiles subdirectory.
 3005: # Parameters:
 3006: #    cmd   - the Lond request keyword that got us here.
 3007: #    tail  - the part of the command past the keyword.
 3008: #    client- File descriptor connected with the client.
 3009: #
 3010: # Returns:
 3011: #    1    - Continue processing.
 3012: sub rename_user_file_handler {
 3013:     my ($cmd, $tail, $client) = @_;
 3014: 
 3015:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
 3016:     $old=&unescape($old);
 3017:     $new=&unescape($new);
 3018:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
 3019: 	# any files paths with /../ in them refuse to deal with
 3020: 	&Failure($client, "refused\n", "$cmd:$tail");
 3021:     } else {
 3022: 	my $udir = &propath($udom,$uname);
 3023: 	if (-e $udir) {
 3024: 	    my $oldfile=$udir.'/userfiles/'.$old;
 3025: 	    my $newfile=$udir.'/userfiles/'.$new;
 3026: 	    if (-e $newfile) {
 3027: 		&Failure($client, "exists\n", "$cmd:$tail");
 3028: 	    } elsif (! -e $oldfile) {
 3029: 		&Failure($client, "not_found\n", "$cmd:$tail");
 3030: 	    } else {
 3031: 		if (!rename($oldfile,$newfile)) {
 3032: 		    &Failure($client, "failed\n", "$cmd:$tail");
 3033: 		} else {
 3034: 		    &Reply($client, "ok\n", "$cmd:$tail");
 3035: 		}
 3036: 	    }
 3037: 	} else {
 3038: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 3039: 	}
 3040:     }
 3041:     return 1;
 3042: }
 3043: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
 3044: 
 3045: #
 3046: #  Checks if the specified user has an active session on the server
 3047: #  return ok if so, not_found if not
 3048: #
 3049: # Parameters:
 3050: #   cmd      - The request keyword that dispatched to tus.
 3051: #   tail     - The tail of the request (colon separated parameters).
 3052: #   client   - Filehandle open on the client.
 3053: # Return:
 3054: #    1.
 3055: sub user_has_session_handler {
 3056:     my ($cmd, $tail, $client) = @_;
 3057: 
 3058:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
 3059:     
 3060:     opendir(DIR,$perlvar{'lonIDsDir'});
 3061:     my $filename;
 3062:     while ($filename=readdir(DIR)) {
 3063: 	last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
 3064:     }
 3065:     if ($filename) {
 3066: 	&Reply($client, "ok\n", "$cmd:$tail");
 3067:     } else {
 3068: 	&Failure($client, "not_found\n", "$cmd:$tail");
 3069:     }
 3070:     return 1;
 3071: 
 3072: }
 3073: &register_handler("userhassession", \&user_has_session_handler, 0,1,0);
 3074: 
 3075: sub del_usersession_handler {
 3076:     my ($cmd, $tail, $client) = @_;
 3077: 
 3078:     my $result;
 3079:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
 3080:     if (($udom =~ /^$LONCAPA::match_domain$/) && ($uname =~ /^$LONCAPA::match_username$/)) {
 3081:         my $lonidsdir = $perlvar{'lonIDsDir'};
 3082:         if (-d $lonidsdir) {
 3083:             if (opendir(DIR,$lonidsdir)) {
 3084:                 my $filename;
 3085:                 while ($filename=readdir(DIR)) {
 3086:                     if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/) {
 3087:                         if (tie(my %oldenv,'GDBM_File',"$lonidsdir/$filename",
 3088:                                 &GDBM_READER(),0640)) {
 3089:                             my $linkedfile;
 3090:                             if (exists($oldenv{'user.linkedenv'})) {
 3091:                                 $linkedfile = $oldenv{'user.linkedenv'};
 3092:                             }
 3093:                             untie(%oldenv);
 3094:                             $result = unlink("$lonidsdir/$filename");
 3095:                             if ($result) {
 3096:                                 if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
 3097:                                     if (-l "$lonidsdir/$linkedfile.id") {
 3098:                                         unlink("$lonidsdir/$linkedfile.id");
 3099:                                     }
 3100:                                 }
 3101:                             }
 3102:                         } else {
 3103:                             $result = unlink("$lonidsdir/$filename");
 3104:                         }
 3105:                         last;
 3106:                     }
 3107:                 }
 3108:             }
 3109:         }
 3110:         if ($result == 1) {
 3111:             &Reply($client, "$result\n", "$cmd:$tail");
 3112:         } else {
 3113:             &Reply($client, "not_found\n", "$cmd:$tail");
 3114:         }
 3115:     } else {
 3116:         &Failure($client, "invalid_user\n", "$cmd:$tail");
 3117:     }
 3118:     return 1;
 3119: }
 3120: 
 3121: &register_handler("delusersession", \&del_usersession_handler, 0,1,0);
 3122: 
 3123: #
 3124: #  Authenticate access to a user file by checking that the token the user's 
 3125: #  passed also exists in their session file
 3126: #
 3127: # Parameters:
 3128: #   cmd      - The request keyword that dispatched to tus.
 3129: #   tail     - The tail of the request (colon separated parameters).
 3130: #   client   - Filehandle open on the client.
 3131: # Return:
 3132: #    1.
 3133: sub token_auth_user_file_handler {
 3134:     my ($cmd, $tail, $client) = @_;
 3135: 
 3136:     my ($fname, $session) = split(/:/, $tail);
 3137:     
 3138:     chomp($session);
 3139:     my $reply="non_auth";
 3140:     my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
 3141:     if (open(ENVIN,"$file")) {
 3142: 	flock(ENVIN,LOCK_SH);
 3143: 	tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
 3144: 	if (exists($disk_env{"userfile.$fname"})) {
 3145: 	    $reply="ok";
 3146: 	} else {
 3147: 	    foreach my $envname (keys(%disk_env)) {
 3148: 		if ($envname=~ m|^userfile\.\Q$fname\E|) {
 3149: 		    $reply="ok";
 3150: 		    last;
 3151: 		}
 3152: 	    }
 3153: 	}
 3154: 	untie(%disk_env);
 3155: 	close(ENVIN);
 3156: 	&Reply($client, \$reply, "$cmd:$tail");
 3157:     } else {
 3158: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
 3159:     }
 3160:     return 1;
 3161: 
 3162: }
 3163: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
 3164: 
 3165: #
 3166: #   Unsubscribe from a resource.
 3167: #
 3168: # Parameters:
 3169: #    $cmd      - The command that got us here.
 3170: #    $tail     - Tail of the command (remaining parameters).
 3171: #    $client   - File descriptor connected to client.
 3172: # Returns
 3173: #     0        - Requested to exit, caller should shut down.
 3174: #     1        - Continue processing.
 3175: #
 3176: sub unsubscribe_handler {
 3177:     my ($cmd, $tail, $client) = @_;
 3178: 
 3179:     my $userinput= "$cmd:$tail";
 3180:     
 3181:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
 3182: 
 3183:     &Debug("Unsubscribing $fname");
 3184:     if (-e $fname) {
 3185: 	&Debug("Exists");
 3186: 	&Reply($client, &unsub($fname,$clientip), $userinput);
 3187:     } else {
 3188: 	&Failure($client, "not_found\n", $userinput);
 3189:     }
 3190:     return 1;
 3191: }
 3192: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
 3193: 
 3194: #   Subscribe to a resource
 3195: #
 3196: # Parameters:
 3197: #    $cmd      - The command that got us here.
 3198: #    $tail     - Tail of the command (remaining parameters).
 3199: #    $client   - File descriptor connected to client.
 3200: # Returns
 3201: #     0        - Requested to exit, caller should shut down.
 3202: #     1        - Continue processing.
 3203: #
 3204: sub subscribe_handler {
 3205:     my ($cmd, $tail, $client)= @_;
 3206: 
 3207:     my $userinput  = "$cmd:$tail";
 3208: 
 3209:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
 3210: 
 3211:     return 1;
 3212: }
 3213: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
 3214: 
 3215: #
 3216: #   Determine the latest version of a resource (it looks for the highest
 3217: #   past version and then returns that +1)
 3218: #
 3219: # Parameters:
 3220: #    $cmd      - The command that got us here.
 3221: #    $tail     - Tail of the command (remaining parameters).
 3222: #                 (Should consist of an absolute path to a file)
 3223: #    $client   - File descriptor connected to client.
 3224: # Returns
 3225: #     0        - Requested to exit, caller should shut down.
 3226: #     1        - Continue processing.
 3227: #
 3228: sub current_version_handler {
 3229:     my ($cmd, $tail, $client) = @_;
 3230: 
 3231:     my $userinput= "$cmd:$tail";
 3232:    
 3233:     my $fname   = $tail;
 3234:     &Reply( $client, &currentversion($fname)."\n", $userinput);
 3235:     return 1;
 3236: 
 3237: }
 3238: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
 3239: 
 3240: #  Make an entry in a user's activity log.
 3241: #
 3242: # Parameters:
 3243: #    $cmd      - The command that got us here.
 3244: #    $tail     - Tail of the command (remaining parameters).
 3245: #    $client   - File descriptor connected to client.
 3246: # Returns
 3247: #     0        - Requested to exit, caller should shut down.
 3248: #     1        - Continue processing.
 3249: #
 3250: sub activity_log_handler {
 3251:     my ($cmd, $tail, $client) = @_;
 3252: 
 3253: 
 3254:     my $userinput= "$cmd:$tail";
 3255: 
 3256:     my ($udom,$uname,$what)=split(/:/,$tail);
 3257:     chomp($what);
 3258:     my $proname=&propath($udom,$uname);
 3259:     my $now=time;
 3260:     my $hfh;
 3261:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
 3262: 	print $hfh "$now:$clientname:$what\n";
 3263: 	&Reply( $client, "ok\n", $userinput); 
 3264:     } else {
 3265: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
 3266: 		 ."while attempting log\n", 
 3267: 		 $userinput);
 3268:     }
 3269: 
 3270:     return 1;
 3271: }
 3272: &register_handler("log", \&activity_log_handler, 0, 1, 0);
 3273: 
 3274: #
 3275: #   Put a namespace entry in a user profile hash.
 3276: #   My druthers would be for this to be an encrypted interaction too.
 3277: #   anything that might be an inadvertent covert channel about either
 3278: #   user authentication or user personal information....
 3279: #
 3280: # Parameters:
 3281: #    $cmd      - The command that got us here.
 3282: #    $tail     - Tail of the command (remaining parameters).
 3283: #    $client   - File descriptor connected to client.
 3284: # Returns
 3285: #     0        - Requested to exit, caller should shut down.
 3286: #     1        - Continue processing.
 3287: #
 3288: sub put_user_profile_entry {
 3289:     my ($cmd, $tail, $client)  = @_;
 3290: 
 3291:     my $userinput = "$cmd:$tail";
 3292:     
 3293:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
 3294:     if ($namespace ne 'roles') {
 3295: 	chomp($what);
 3296: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3297: 				  &GDBM_WRCREAT(),"P",$what);
 3298: 	if($hashref) {
 3299: 	    my @pairs=split(/\&/,$what);
 3300: 	    foreach my $pair (@pairs) {
 3301: 		my ($key,$value)=split(/=/,$pair);
 3302: 		$hashref->{$key}=$value;
 3303: 	    }
 3304: 	    if (&untie_user_hash($hashref)) {
 3305: 		&Reply( $client, "ok\n", $userinput);
 3306: 	    } else {
 3307: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 3308: 			"while attempting put\n", 
 3309: 			$userinput);
 3310: 	    }
 3311: 	} else {
 3312: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3313: 		     "while attempting put\n", $userinput);
 3314: 	}
 3315:     } else {
 3316:         &Failure( $client, "refused\n", $userinput);
 3317:     }
 3318:     
 3319:     return 1;
 3320: }
 3321: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
 3322: 
 3323: #   Put a piece of new data in hash, returns error if entry already exists
 3324: # Parameters:
 3325: #    $cmd      - The command that got us here.
 3326: #    $tail     - Tail of the command (remaining parameters).
 3327: #    $client   - File descriptor connected to client.
 3328: # Returns
 3329: #     0        - Requested to exit, caller should shut down.
 3330: #     1        - Continue processing.
 3331: #
 3332: sub newput_user_profile_entry {
 3333:     my ($cmd, $tail, $client)  = @_;
 3334: 
 3335:     my $userinput = "$cmd:$tail";
 3336: 
 3337:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
 3338:     if ($namespace eq 'roles') {
 3339:         &Failure( $client, "refused\n", $userinput);
 3340: 	return 1;
 3341:     }
 3342: 
 3343:     chomp($what);
 3344: 
 3345:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3346: 				 &GDBM_WRCREAT(),"N",$what);
 3347:     if(!$hashref) {
 3348: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3349: 		  "while attempting put\n", $userinput);
 3350: 	return 1;
 3351:     }
 3352: 
 3353:     my @pairs=split(/\&/,$what);
 3354:     foreach my $pair (@pairs) {
 3355: 	my ($key,$value)=split(/=/,$pair);
 3356: 	if (exists($hashref->{$key})) {
 3357:             if (!&untie_user_hash($hashref)) {
 3358:                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
 3359:                          "while attempting newput - early out as key exists");
 3360:             }
 3361:             &Failure($client, "key_exists: ".$key."\n",$userinput);
 3362:             return 1;
 3363: 	}
 3364:     }
 3365: 
 3366:     foreach my $pair (@pairs) {
 3367: 	my ($key,$value)=split(/=/,$pair);
 3368: 	$hashref->{$key}=$value;
 3369:     }
 3370: 
 3371:     if (&untie_user_hash($hashref)) {
 3372: 	&Reply( $client, "ok\n", $userinput);
 3373:     } else {
 3374: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 3375: 		 "while attempting put\n", 
 3376: 		 $userinput);
 3377:     }
 3378:     return 1;
 3379: }
 3380: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
 3381: 
 3382: # 
 3383: #   Increment a profile entry in the user history file.
 3384: #   The history contains keyword value pairs.  In this case,
 3385: #   The value itself is a pair of numbers.  The first, the current value
 3386: #   the second an increment that this function applies to the current
 3387: #   value.
 3388: #
 3389: # Parameters:
 3390: #    $cmd      - The command that got us here.
 3391: #    $tail     - Tail of the command (remaining parameters).
 3392: #    $client   - File descriptor connected to client.
 3393: # Returns
 3394: #     0        - Requested to exit, caller should shut down.
 3395: #     1        - Continue processing.
 3396: #
 3397: sub increment_user_value_handler {
 3398:     my ($cmd, $tail, $client) = @_;
 3399:     
 3400:     my $userinput   = "$cmd:$tail";
 3401:     
 3402:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
 3403:     if ($namespace ne 'roles') {
 3404:         chomp($what);
 3405: 	my $hashref = &tie_user_hash($udom, $uname,
 3406: 				     $namespace, &GDBM_WRCREAT(),
 3407: 				     "P",$what);
 3408: 	if ($hashref) {
 3409: 	    my @pairs=split(/\&/,$what);
 3410: 	    foreach my $pair (@pairs) {
 3411: 		my ($key,$value)=split(/=/,$pair);
 3412:                 $value = &unescape($value);
 3413: 		# We could check that we have a number...
 3414: 		if (! defined($value) || $value eq '') {
 3415: 		    $value = 1;
 3416: 		}
 3417: 		$hashref->{$key}+=$value;
 3418:                 if ($namespace eq 'nohist_resourcetracker') {
 3419:                     if ($hashref->{$key} < 0) {
 3420:                         $hashref->{$key} = 0;
 3421:                     }
 3422:                 }
 3423: 	    }
 3424: 	    if (&untie_user_hash($hashref)) {
 3425: 		&Reply( $client, "ok\n", $userinput);
 3426: 	    } else {
 3427: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 3428: 			 "while attempting inc\n", $userinput);
 3429: 	    }
 3430: 	} else {
 3431: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3432: 		     "while attempting inc\n", $userinput);
 3433: 	}
 3434:     } else {
 3435: 	&Failure($client, "refused\n", $userinput);
 3436:     }
 3437:     
 3438:     return 1;
 3439: }
 3440: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
 3441: 
 3442: #
 3443: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
 3444: #   Each 'role' a user has implies a set of permissions.  Adding a new role
 3445: #   for a person grants the permissions packaged with that role
 3446: #   to that user when the role is selected.
 3447: #
 3448: # Parameters:
 3449: #    $cmd       - The command string (rolesput).
 3450: #    $tail      - The remainder of the request line.  For rolesput this
 3451: #                 consists of a colon separated list that contains:
 3452: #                 The domain and user that is granting the role (logged).
 3453: #                 The domain and user that is getting the role.
 3454: #                 The roles being granted as a set of & separated pairs.
 3455: #                 each pair a key value pair.
 3456: #    $client    - File descriptor connected to the client.
 3457: # Returns:
 3458: #     0         - If the daemon should exit
 3459: #     1         - To continue processing.
 3460: #
 3461: #
 3462: sub roles_put_handler {
 3463:     my ($cmd, $tail, $client) = @_;
 3464: 
 3465:     my $userinput  = "$cmd:$tail";
 3466: 
 3467:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
 3468:     
 3469: 
 3470:     my $namespace='roles';
 3471:     chomp($what);
 3472:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3473: 				 &GDBM_WRCREAT(), "P",
 3474: 				 "$exedom:$exeuser:$what");
 3475:     #
 3476:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
 3477:     #  handle is open for the minimal amount of time.  Since the flush
 3478:     #  is done on close this improves the chances the log will be an un-
 3479:     #  corrupted ordered thing.
 3480:     if ($hashref) {
 3481: 	my $pass_entry = &get_auth_type($udom, $uname);
 3482: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
 3483: 	$auth_type = $auth_type.":";
 3484: 	my @pairs=split(/\&/,$what);
 3485: 	foreach my $pair (@pairs) {
 3486: 	    my ($key,$value)=split(/=/,$pair);
 3487: 	    &manage_permissions($key, $udom, $uname,
 3488: 			       $auth_type);
 3489: 	    $hashref->{$key}=$value;
 3490: 	}
 3491: 	if (&untie_user_hash($hashref)) {
 3492: 	    &Reply($client, "ok\n", $userinput);
 3493: 	} else {
 3494: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 3495: 		     "while attempting rolesput\n", $userinput);
 3496: 	}
 3497:     } else {
 3498: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3499: 		 "while attempting rolesput\n", $userinput);
 3500:     }
 3501:     return 1;
 3502: }
 3503: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
 3504: 
 3505: #
 3506: #   Deletes (removes) a role for a user.   This is equivalent to removing
 3507: #  a permissions package associated with the role from the user's profile.
 3508: #
 3509: # Parameters:
 3510: #     $cmd                 - The command (rolesdel)
 3511: #     $tail                - The remainder of the request line. This consists
 3512: #                             of:
 3513: #                             The domain and user requesting the change (logged)
 3514: #                             The domain and user being changed.
 3515: #                             The roles being revoked.  These are shipped to us
 3516: #                             as a bunch of & separated role name keywords.
 3517: #     $client              - The file handle open on the client.
 3518: # Returns:
 3519: #     1                    - Continue processing
 3520: #     0                    - Exit.
 3521: #
 3522: sub roles_delete_handler {
 3523:     my ($cmd, $tail, $client)  = @_;
 3524: 
 3525:     my $userinput    = "$cmd:$tail";
 3526:    
 3527:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
 3528:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
 3529: 	   "what = ".$what);
 3530:     my $namespace='roles';
 3531:     chomp($what);
 3532:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3533: 				 &GDBM_WRCREAT(), "D",
 3534: 				 "$exedom:$exeuser:$what");
 3535:     
 3536:     if ($hashref) {
 3537: 	my @rolekeys=split(/\&/,$what);
 3538: 	
 3539: 	foreach my $key (@rolekeys) {
 3540: 	    delete $hashref->{$key};
 3541: 	}
 3542: 	if (&untie_user_hash($hashref)) {
 3543: 	    &Reply($client, "ok\n", $userinput);
 3544: 	} else {
 3545: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 3546: 		     "while attempting rolesdel\n", $userinput);
 3547: 	}
 3548:     } else {
 3549:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3550: 		 "while attempting rolesdel\n", $userinput);
 3551:     }
 3552:     
 3553:     return 1;
 3554: }
 3555: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
 3556: 
 3557: # Unencrypted get from a user's profile database.  See 
 3558: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
 3559: # This function retrieves a keyed item from a specific named database in the
 3560: # user's directory.
 3561: #
 3562: # Parameters:
 3563: #   $cmd             - Command request keyword (get).
 3564: #   $tail            - Tail of the command.  This is a colon separated list
 3565: #                      consisting of the domain and username that uniquely
 3566: #                      identifies the profile,
 3567: #                      The 'namespace' which selects the gdbm file to 
 3568: #                      do the lookup in, 
 3569: #                      & separated list of keys to lookup.  Note that
 3570: #                      the values are returned as an & separated list too.
 3571: #   $client          - File descriptor open on the client.
 3572: # Returns:
 3573: #   1       - Continue processing.
 3574: #   0       - Exit.
 3575: #
 3576: sub get_profile_entry {
 3577:     my ($cmd, $tail, $client) = @_;
 3578: 
 3579:     my $userinput= "$cmd:$tail";
 3580:    
 3581:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 3582:     chomp($what);
 3583: 
 3584: 
 3585:     my $replystring = read_profile($udom, $uname, $namespace, $what);
 3586:     my ($first) = split(/:/,$replystring);
 3587:     if($first ne "error") {
 3588: 	&Reply($client, \$replystring, $userinput);
 3589:     } else {
 3590: 	&Failure($client, $replystring." while attempting get\n", $userinput);
 3591:     }
 3592:     return 1;
 3593: 
 3594: 
 3595: }
 3596: &register_handler("get", \&get_profile_entry, 0,1,0);
 3597: 
 3598: #
 3599: #  Process the encrypted get request.  Note that the request is sent
 3600: #  in clear, but the reply is encrypted.  This is a small covert channel:
 3601: #  information about the sensitive keys is given to the snooper.  Just not
 3602: #  information about the values of the sensitive key.  Hmm if I wanted to
 3603: #  know these I'd snoop for the egets. Get the profile item names from them
 3604: #  and then issue a get for them since there's no enforcement of the
 3605: #  requirement of an encrypted get for particular profile items.  If I
 3606: #  were re-doing this, I'd force the request to be encrypted as well as the
 3607: #  reply.  I'd also just enforce encrypted transactions for all gets since
 3608: #  that would prevent any covert channel snooping.
 3609: #
 3610: #  Parameters:
 3611: #     $cmd               - Command keyword of request (eget).
 3612: #     $tail              - Tail of the command.  See GetProfileEntry
 3613: #                          for more information about this.
 3614: #     $client            - File open on the client.
 3615: #  Returns:
 3616: #     1      - Continue processing
 3617: #     0      - server should exit.
 3618: sub get_profile_entry_encrypted {
 3619:     my ($cmd, $tail, $client) = @_;
 3620: 
 3621:     my $userinput = "$cmd:$tail";
 3622:    
 3623:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 3624:     chomp($what);
 3625:     my $qresult = read_profile($udom, $uname, $namespace, $what);
 3626:     my ($first) = split(/:/, $qresult);
 3627:     if($first ne "error") {
 3628: 	
 3629: 	if ($cipher) {
 3630: 	    my $cmdlength=length($qresult);
 3631: 	    $qresult.="         ";
 3632: 	    my $encqresult='';
 3633: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 3634: 		$encqresult.= unpack("H16", 
 3635: 				     $cipher->encrypt(substr($qresult,
 3636: 							     $encidx,
 3637: 							     8)));
 3638: 	    }
 3639: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
 3640: 	} else {
 3641: 		&Failure( $client, "error:no_key\n", $userinput);
 3642: 	    }
 3643:     } else {
 3644: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
 3645: 
 3646:     }
 3647:     
 3648:     return 1;
 3649: }
 3650: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
 3651: 
 3652: #
 3653: #   Deletes a key in a user profile database.
 3654: #   
 3655: #   Parameters:
 3656: #       $cmd                  - Command keyword (del).
 3657: #       $tail                 - Command tail.  IN this case a colon
 3658: #                               separated list containing:
 3659: #                               The domain and user that identifies uniquely
 3660: #                               the identity of the user.
 3661: #                               The profile namespace (name of the profile
 3662: #                               database file).
 3663: #                               & separated list of keywords to delete.
 3664: #       $client              - File open on client socket.
 3665: # Returns:
 3666: #     1   - Continue processing
 3667: #     0   - Exit server.
 3668: #
 3669: #
 3670: sub delete_profile_entry {
 3671:     my ($cmd, $tail, $client) = @_;
 3672: 
 3673:     my $userinput = "cmd:$tail";
 3674: 
 3675:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 3676:     chomp($what);
 3677:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3678: 				 &GDBM_WRCREAT(),
 3679: 				 "D",$what);
 3680:     if ($hashref) {
 3681:         my @keys=split(/\&/,$what);
 3682: 	foreach my $key (@keys) {
 3683: 	    delete($hashref->{$key});
 3684: 	}
 3685: 	if (&untie_user_hash($hashref)) {
 3686: 	    &Reply($client, "ok\n", $userinput);
 3687: 	} else {
 3688: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3689: 		    "while attempting del\n", $userinput);
 3690: 	}
 3691:     } else {
 3692: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3693: 		 "while attempting del\n", $userinput);
 3694:     }
 3695:     return 1;
 3696: }
 3697: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
 3698: 
 3699: #
 3700: #  List the set of keys that are defined in a profile database file.
 3701: #  A successful reply from this will contain an & separated list of
 3702: #  the keys. 
 3703: # Parameters:
 3704: #     $cmd              - Command request (keys).
 3705: #     $tail             - Remainder of the request, a colon separated
 3706: #                         list containing domain/user that identifies the
 3707: #                         user being queried, and the database namespace
 3708: #                         (database filename essentially).
 3709: #     $client           - File open on the client.
 3710: #  Returns:
 3711: #    1    - Continue processing.
 3712: #    0    - Exit the server.
 3713: #
 3714: sub get_profile_keys {
 3715:     my ($cmd, $tail, $client) = @_;
 3716: 
 3717:     my $userinput = "$cmd:$tail";
 3718: 
 3719:     my ($udom,$uname,$namespace)=split(/:/,$tail);
 3720:     my $qresult='';
 3721:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3722: 				  &GDBM_READER());
 3723:     if ($hashref) {
 3724: 	foreach my $key (keys %$hashref) {
 3725: 	    $qresult.="$key&";
 3726: 	}
 3727: 	if (&untie_user_hash($hashref)) {
 3728: 	    $qresult=~s/\&$//;
 3729: 	    &Reply($client, \$qresult, $userinput);
 3730: 	} else {
 3731: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3732: 		    "while attempting keys\n", $userinput);
 3733: 	}
 3734:     } else {
 3735: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3736: 		 "while attempting keys\n", $userinput);
 3737:     }
 3738:    
 3739:     return 1;
 3740: }
 3741: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
 3742: 
 3743: #
 3744: #   Dump the contents of a user profile database.
 3745: #   Note that this constitutes a very large covert channel too since
 3746: #   the dump will return sensitive information that is not encrypted.
 3747: #   The naive security assumption is that the session negotiation ensures
 3748: #   our client is trusted and I don't believe that's assured at present.
 3749: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
 3750: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
 3751: # 
 3752: #  Parameters:
 3753: #     $cmd           - The command request keyword (currentdump).
 3754: #     $tail          - Remainder of the request, consisting of a colon
 3755: #                      separated list that has the domain/username and
 3756: #                      the namespace to dump (database file).
 3757: #     $client        - file open on the remote client.
 3758: # Returns:
 3759: #     1    - Continue processing.
 3760: #     0    - Exit the server.
 3761: #
 3762: sub dump_profile_database {
 3763:     my ($cmd, $tail, $client) = @_;
 3764: 
 3765:     my $res = LONCAPA::Lond::dump_profile_database($tail);
 3766: 
 3767:     if ($res =~ /^error:/) {
 3768:         Failure($client, \$res, "$cmd:$tail");
 3769:     } else {
 3770:         Reply($client, \$res, "$cmd:$tail");
 3771:     }
 3772: 
 3773:     return 1;  
 3774: 
 3775:     #TODO remove 
 3776:     my $userinput = "$cmd:$tail";
 3777:    
 3778:     my ($udom,$uname,$namespace) = split(/:/,$tail);
 3779:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3780: 				 &GDBM_READER());
 3781:     if ($hashref) {
 3782: 	# Structure of %data:
 3783: 	# $data{$symb}->{$parameter}=$value;
 3784: 	# $data{$symb}->{'v.'.$parameter}=$version;
 3785: 	# since $parameter will be unescaped, we do not
 3786:  	# have to worry about silly parameter names...
 3787: 	
 3788:         my $qresult='';
 3789: 	my %data = ();                     # A hash of anonymous hashes..
 3790: 	while (my ($key,$value) = each(%$hashref)) {
 3791: 	    my ($v,$symb,$param) = split(/:/,$key);
 3792: 	    next if ($v eq 'version' || $symb eq 'keys');
 3793: 	    next if (exists($data{$symb}) && 
 3794: 		     exists($data{$symb}->{$param}) &&
 3795: 		     $data{$symb}->{'v.'.$param} > $v);
 3796: 	    $data{$symb}->{$param}=$value;
 3797: 	    $data{$symb}->{'v.'.$param}=$v;
 3798: 	}
 3799: 	if (&untie_user_hash($hashref)) {
 3800: 	    while (my ($symb,$param_hash) = each(%data)) {
 3801: 		while(my ($param,$value) = each (%$param_hash)){
 3802: 		    next if ($param =~ /^v\./);       # Ignore versions...
 3803: 		    #
 3804: 		    #   Just dump the symb=value pairs separated by &
 3805: 		    #
 3806: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
 3807: 		}
 3808: 	    }
 3809: 	    chop($qresult);
 3810: 	    &Reply($client , \$qresult, $userinput);
 3811: 	} else {
 3812: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 3813: 		     "while attempting currentdump\n", $userinput);
 3814: 	}
 3815:     } else {
 3816: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3817: 		"while attempting currentdump\n", $userinput);
 3818:     }
 3819: 
 3820:     return 1;
 3821: }
 3822: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
 3823: 
 3824: #
 3825: #   Dump a profile database with an optional regular expression
 3826: #   to match against the keys.  In this dump, no effort is made
 3827: #   to separate symb from version information. Presumably the
 3828: #   databases that are dumped by this command are of a different
 3829: #   structure.  Need to look at this and improve the documentation of
 3830: #   both this and the currentdump handler.
 3831: # Parameters:
 3832: #    $cmd                     - The command keyword.
 3833: #    $tail                    - All of the characters after the $cmd:
 3834: #                               These are expected to be a colon
 3835: #                               separated list containing:
 3836: #                               domain/user - identifying the user.
 3837: #                               namespace   - identifying the database.
 3838: #                               regexp      - optional regular expression
 3839: #                                             that is matched against
 3840: #                                             database keywords to do
 3841: #                                             selective dumps.
 3842: #                               range       - optional range of entries
 3843: #                                             e.g., 10-20 would return the
 3844: #                                             10th to 19th items, etc.  
 3845: #   $client                   - Channel open on the client.
 3846: # Returns:
 3847: #    1    - Continue processing.
 3848: # Side effects:
 3849: #    response is written to $client.
 3850: #
 3851: sub dump_with_regexp {
 3852:     my ($cmd, $tail, $client) = @_;
 3853: 
 3854:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
 3855:     
 3856:     if ($res =~ /^error:/) {
 3857:         Failure($client, \$res, "$cmd:$tail");
 3858:     } else {
 3859:         Reply($client, \$res, "$cmd:$tail");
 3860:     }
 3861: 
 3862:     return 1;
 3863: }
 3864: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
 3865: 
 3866: #
 3867: #  Process the encrypted dump request. Original call should
 3868: #  be from lonnet::dump() with seventh arg ($encrypt) set to
 3869: #  1, to ensure that both request and response are encrypted.
 3870: #
 3871: #  Parameters:
 3872: #     $cmd               - Command keyword of request (edump).
 3873: #     $tail              - Tail of the command.
 3874: #                          See &dump_with_regexp for more
 3875: #                          information about this.
 3876: #     $client            - File open on the client.
 3877: #  Returns:
 3878: #     1      - Continue processing
 3879: #     0      - server should exit.
 3880: #
 3881: 
 3882: sub encrypted_dump_with_regexp {
 3883:     my ($cmd, $tail, $client) = @_;
 3884:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
 3885: 
 3886:     if ($res =~ /^error:/) {
 3887:         Failure($client, \$res, "$cmd:$tail");
 3888:     } else {
 3889:         if ($cipher) {
 3890:             my $cmdlength=length($res);
 3891:             $res.="         ";
 3892:             my $encres='';
 3893:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 3894:                 $encres.= unpack("H16",
 3895:                                  $cipher->encrypt(substr($res,
 3896:                                                          $encidx,
 3897:                                                          8)));
 3898:             }
 3899:             &Reply( $client,"enc:$cmdlength:$encres\n","$cmd:$tail");
 3900:         } else {
 3901:             &Failure( $client, "error:no_key\n","$cmd:$tail");
 3902:         }
 3903:     }
 3904: }
 3905: &register_handler("edump", \&encrypted_dump_with_regexp, 0, 1, 0);
 3906: 
 3907: #  Store a set of key=value pairs associated with a versioned name.
 3908: #
 3909: #  Parameters:
 3910: #    $cmd                - Request command keyword.
 3911: #    $tail               - Tail of the request.  This is a colon
 3912: #                          separated list containing:
 3913: #                          domain/user - User and authentication domain.
 3914: #                          namespace   - Name of the database being modified
 3915: #                          rid         - Resource keyword to modify.
 3916: #                          what        - new value associated with rid.
 3917: #                          laststore   - (optional) version=timestamp
 3918: #                                        for most recent transaction for rid
 3919: #                                        in namespace, when cstore was called
 3920: #
 3921: #    $client             - Socket open on the client.
 3922: #
 3923: #
 3924: #  Returns:
 3925: #      1 (keep on processing).
 3926: #  Side-Effects:
 3927: #    Writes to the client
 3928: #    Successful storage will cause either 'ok', or, if $laststore was included
 3929: #    in the tail of the request, and the version number for the last transaction
 3930: #    is larger than the version in $laststore, delay:$numtrans , where $numtrans
 3931: #    is the number of store evevnts recorded for rid in namespace since
 3932: #    lonnet::store() was called by the client.
 3933: #
 3934: sub store_handler {
 3935:     my ($cmd, $tail, $client) = @_;
 3936:  
 3937:     my $userinput = "$cmd:$tail";
 3938:     chomp($tail);
 3939:     my ($udom,$uname,$namespace,$rid,$what,$laststore) =split(/:/,$tail);
 3940:     if ($namespace ne 'roles') {
 3941: 
 3942: 	my @pairs=split(/\&/,$what);
 3943: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
 3944: 				       &GDBM_WRCREAT(), "S",
 3945: 				       "$rid:$what");
 3946: 	if ($hashref) {
 3947: 	    my $now = time;
 3948:             my $numtrans;
 3949:             if ($laststore) {
 3950:                 my ($previousversion,$previoustime) = split(/\=/,$laststore);
 3951:                 my ($lastversion,$lasttime) = (0,0);
 3952:                 $lastversion = $hashref->{"version:$rid"};
 3953:                 if ($lastversion) {
 3954:                     $lasttime = $hashref->{"$lastversion:$rid:timestamp"};
 3955:                 }
 3956:                 if (($previousversion) && ($previousversion !~ /\D/)) {
 3957:                     if (($lastversion > $previousversion) && ($lasttime >= $previoustime)) {
 3958:                         $numtrans = $lastversion - $previousversion;
 3959:                     }
 3960:                 } elsif ($lastversion) {
 3961:                     $numtrans = $lastversion;
 3962:                 }
 3963:                 if ($numtrans) {
 3964:                     $numtrans =~ s/D//g;
 3965:                 }
 3966:             }
 3967: 	    $hashref->{"version:$rid"}++;
 3968: 	    my $version=$hashref->{"version:$rid"};
 3969: 	    my $allkeys=''; 
 3970: 	    foreach my $pair (@pairs) {
 3971: 		my ($key,$value)=split(/=/,$pair);
 3972: 		$allkeys.=$key.':';
 3973: 		$hashref->{"$version:$rid:$key"}=$value;
 3974: 	    }
 3975: 	    $hashref->{"$version:$rid:timestamp"}=$now;
 3976: 	    $allkeys.='timestamp';
 3977: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
 3978: 	    if (&untie_user_hash($hashref)) {
 3979:                 my $msg = 'ok';
 3980:                 if ($numtrans) {
 3981:                     $msg = 'delay:'.$numtrans;
 3982:                 }
 3983: 		&Reply($client, "$msg\n", $userinput);
 3984: 	    } else {
 3985: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3986: 			"while attempting store\n", $userinput);
 3987: 	    }
 3988: 	} else {
 3989: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3990: 		     "while attempting store\n", $userinput);
 3991: 	}
 3992:     } else {
 3993: 	&Failure($client, "refused\n", $userinput);
 3994:     }
 3995: 
 3996:     return 1;
 3997: }
 3998: &register_handler("store", \&store_handler, 0, 1, 0);
 3999: 
 4000: #  Modify a set of key=value pairs associated with a versioned name.
 4001: #
 4002: #  Parameters:
 4003: #    $cmd                - Request command keyword.
 4004: #    $tail               - Tail of the request.  This is a colon
 4005: #                          separated list containing:
 4006: #                          domain/user - User and authentication domain.
 4007: #                          namespace   - Name of the database being modified
 4008: #                          rid         - Resource keyword to modify.
 4009: #                          v           - Version item to modify
 4010: #                          what        - new value associated with rid.
 4011: #
 4012: #    $client             - Socket open on the client.
 4013: #
 4014: #
 4015: #  Returns:
 4016: #      1 (keep on processing).
 4017: #  Side-Effects:
 4018: #    Writes to the client
 4019: sub putstore_handler {
 4020:     my ($cmd, $tail, $client) = @_;
 4021:  
 4022:     my $userinput = "$cmd:$tail";
 4023: 
 4024:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
 4025:     if ($namespace ne 'roles') {
 4026: 
 4027: 	chomp($what);
 4028: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
 4029: 				       &GDBM_WRCREAT(), "M",
 4030: 				       "$rid:$v:$what");
 4031: 	if ($hashref) {
 4032: 	    my $now = time;
 4033: 	    my %data = &hash_extract($what);
 4034: 	    my @allkeys;
 4035: 	    while (my($key,$value) = each(%data)) {
 4036: 		push(@allkeys,$key);
 4037: 		$hashref->{"$v:$rid:$key"} = $value;
 4038: 	    }
 4039: 	    my $allkeys = join(':',@allkeys);
 4040: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
 4041: 
 4042: 	    if (&untie_user_hash($hashref)) {
 4043: 		&Reply($client, "ok\n", $userinput);
 4044: 	    } else {
 4045: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4046: 			"while attempting store\n", $userinput);
 4047: 	    }
 4048: 	} else {
 4049: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 4050: 		     "while attempting store\n", $userinput);
 4051: 	}
 4052:     } else {
 4053: 	&Failure($client, "refused\n", $userinput);
 4054:     }
 4055: 
 4056:     return 1;
 4057: }
 4058: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
 4059: 
 4060: sub hash_extract {
 4061:     my ($str)=@_;
 4062:     my %hash;
 4063:     foreach my $pair (split(/\&/,$str)) {
 4064: 	my ($key,$value)=split(/=/,$pair);
 4065: 	$hash{$key}=$value;
 4066:     }
 4067:     return (%hash);
 4068: }
 4069: sub hash_to_str {
 4070:     my ($hash_ref)=@_;
 4071:     my $str;
 4072:     foreach my $key (keys(%$hash_ref)) {
 4073: 	$str.=$key.'='.$hash_ref->{$key}.'&';
 4074:     }
 4075:     $str=~s/\&$//;
 4076:     return $str;
 4077: }
 4078: 
 4079: #
 4080: #  Dump out all versions of a resource that has key=value pairs associated
 4081: # with it for each version.  These resources are built up via the store
 4082: # command.
 4083: #
 4084: #  Parameters:
 4085: #     $cmd               - Command keyword.
 4086: #     $tail              - Remainder of the request which consists of:
 4087: #                          domain/user   - User and auth. domain.
 4088: #                          namespace     - name of resource database.
 4089: #                          rid           - Resource id.
 4090: #    $client             - socket open on the client.
 4091: #
 4092: # Returns:
 4093: #      1  indicating the caller should not yet exit.
 4094: # Side-effects:
 4095: #   Writes a reply to the client.
 4096: #   The reply is a string of the following shape:
 4097: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
 4098: #    Where the 1 above represents version 1.
 4099: #    this continues for all pairs of keys in all versions.
 4100: #
 4101: #
 4102: #    
 4103: #
 4104: sub restore_handler {
 4105:     my ($cmd, $tail, $client) = @_;
 4106: 
 4107:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
 4108:     my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
 4109:     $namespace=~s/\//\_/g;
 4110:     $namespace = &LONCAPA::clean_username($namespace);
 4111: 
 4112:     chomp($rid);
 4113:     my $qresult='';
 4114:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
 4115:     if ($hashref) {
 4116: 	my $version=$hashref->{"version:$rid"};
 4117: 	$qresult.="version=$version&";
 4118: 	my $scope;
 4119: 	for ($scope=1;$scope<=$version;$scope++) {
 4120: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
 4121: 	    my @keys=split(/:/,$vkeys);
 4122: 	    my $key;
 4123: 	    $qresult.="$scope:keys=$vkeys&";
 4124: 	    foreach $key (@keys) {
 4125: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
 4126: 	    }                                  
 4127: 	}
 4128: 	if (&untie_user_hash($hashref)) {
 4129: 	    $qresult=~s/\&$//;
 4130: 	    &Reply( $client, \$qresult, $userinput);
 4131: 	} else {
 4132: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4133: 		    "while attempting restore\n", $userinput);
 4134: 	}
 4135:     } else {
 4136: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 4137: 		"while attempting restore\n", $userinput);
 4138:     }
 4139:   
 4140:     return 1;
 4141: 
 4142: 
 4143: }
 4144: &register_handler("restore", \&restore_handler, 0,1,0);
 4145: 
 4146: #
 4147: #   Add a chat message to a synchronous discussion board.
 4148: #
 4149: # Parameters:
 4150: #    $cmd                - Request keyword.
 4151: #    $tail               - Tail of the command. A colon separated list
 4152: #                          containing:
 4153: #                          cdom    - Domain on which the chat board lives
 4154: #                          cnum    - Course containing the chat board.
 4155: #                          newpost - Body of the posting.
 4156: #                          group   - Optional group, if chat board is only 
 4157: #                                    accessible in a group within the course 
 4158: #   $client              - Socket open on the client.
 4159: # Returns:
 4160: #   1    - Indicating caller should keep on processing.
 4161: #
 4162: # Side-effects:
 4163: #   writes a reply to the client.
 4164: #
 4165: #
 4166: sub send_chat_handler {
 4167:     my ($cmd, $tail, $client) = @_;
 4168: 
 4169:     
 4170:     my $userinput = "$cmd:$tail";
 4171: 
 4172:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
 4173:     &chat_add($cdom,$cnum,$newpost,$group);
 4174:     &Reply($client, "ok\n", $userinput);
 4175: 
 4176:     return 1;
 4177: }
 4178: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
 4179: 
 4180: #
 4181: #   Retrieve the set of chat messages from a discussion board.
 4182: #
 4183: #  Parameters:
 4184: #    $cmd             - Command keyword that initiated the request.
 4185: #    $tail            - Remainder of the request after the command
 4186: #                       keyword.  In this case a colon separated list of
 4187: #                       chat domain    - Which discussion board.
 4188: #                       chat id        - Discussion thread(?)
 4189: #                       domain/user    - Authentication domain and username
 4190: #                                        of the requesting person.
 4191: #                       group          - Optional course group containing
 4192: #                                        the board.      
 4193: #   $client           - Socket open on the client program.
 4194: # Returns:
 4195: #    1     - continue processing
 4196: # Side effects:
 4197: #    Response is written to the client.
 4198: #
 4199: sub retrieve_chat_handler {
 4200:     my ($cmd, $tail, $client) = @_;
 4201: 
 4202: 
 4203:     my $userinput = "$cmd:$tail";
 4204: 
 4205:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
 4206:     my $reply='';
 4207:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
 4208: 	$reply.=&escape($_).':';
 4209:     }
 4210:     $reply=~s/\:$//;
 4211:     &Reply($client, \$reply, $userinput);
 4212: 
 4213: 
 4214:     return 1;
 4215: }
 4216: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
 4217: 
 4218: #
 4219: #  Initiate a query of an sql database.  SQL query repsonses get put in
 4220: #  a file for later retrieval.  This prevents sql query results from
 4221: #  bottlenecking the system.  Note that with loncnew, perhaps this is
 4222: #  less of an issue since multiple outstanding requests can be concurrently
 4223: #  serviced.
 4224: #
 4225: #  Parameters:
 4226: #     $cmd       - Command keyword that initiated the request.
 4227: #     $tail      - Remainder of the command after the keyword.
 4228: #                  For this function, this consists of a query and
 4229: #                  3 arguments that are self-documentingly labelled
 4230: #                  in the original arg1, arg2, arg3.
 4231: #     $client    - Socket open on the client.
 4232: # Return:
 4233: #    1   - Indicating processing should continue.
 4234: # Side-effects:
 4235: #    a reply is written to $client.
 4236: #
 4237: sub send_query_handler {
 4238:     my ($cmd, $tail, $client) = @_;
 4239: 
 4240:     my $userinput = "$cmd:$tail";
 4241: 
 4242:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
 4243:     $query=~s/\n*$//g;
 4244:     if (($query eq 'usersearch') || ($query eq 'instdirsearch')) {
 4245:         my $usersearchconf = &get_usersearch_config($currentdomainid,'directorysrch');
 4246:         my $earlyout;
 4247:         if (ref($usersearchconf) eq 'HASH') {
 4248:             if ($currentdomainid eq $clienthomedom) {
 4249:                 if ($query eq 'usersearch') {
 4250:                     if ($usersearchconf->{'lcavailable'} eq '0') {
 4251:                         $earlyout = 1;
 4252:                     }
 4253:                 } else {
 4254:                     if ($usersearchconf->{'available'} eq '0') {
 4255:                         $earlyout = 1;
 4256:                     }
 4257:                 }
 4258:             } else {
 4259:                 if ($query eq 'usersearch') {
 4260:                     if ($usersearchconf->{'lclocalonly'}) {
 4261:                         $earlyout = 1;
 4262:                     }
 4263:                 } else {
 4264:                     if ($usersearchconf->{'localonly'}) {
 4265:                         $earlyout = 1;
 4266:                     }
 4267:                 }
 4268:             }
 4269:         }
 4270:         if ($earlyout) {
 4271:             &Reply($client, "query_not_authorized\n");
 4272:             return 1;
 4273:         }
 4274:     }
 4275:     &Reply($client, "". &sql_reply("$clientname\&$query".
 4276: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
 4277: 	  $userinput);
 4278:     
 4279:     return 1;
 4280: }
 4281: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
 4282: 
 4283: #
 4284: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
 4285: #   The query is submitted via a "querysend" transaction.
 4286: #   There it is passed on to the lonsql daemon, queued and issued to
 4287: #   mysql.
 4288: #     This transaction is invoked when the sql transaction is complete
 4289: #   it stores the query results in flie and indicates query completion.
 4290: #   presumably local software then fetches this response... I'm guessing
 4291: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
 4292: #   lonsql on completion of the query interacts with the lond of our
 4293: #   client to do a query reply storing two files:
 4294: #    - id     - The results of the query.
 4295: #    - id.end - Indicating the transaction completed. 
 4296: #    NOTE: id is a unique id assigned to the query and querysend time.
 4297: # Parameters:
 4298: #    $cmd        - Command keyword that initiated this request.
 4299: #    $tail       - Remainder of the tail.  In this case that's a colon
 4300: #                  separated list containing the query Id and the 
 4301: #                  results of the query.
 4302: #    $client     - Socket open on the client.
 4303: # Return:
 4304: #    1           - Indicating that we should continue processing.
 4305: # Side effects:
 4306: #    ok written to the client.
 4307: #
 4308: sub reply_query_handler {
 4309:     my ($cmd, $tail, $client) = @_;
 4310: 
 4311: 
 4312:     my $userinput = "$cmd:$tail";
 4313: 
 4314:     my ($id,$reply)=split(/:/,$tail); 
 4315:     my $store;
 4316:     my $execdir=$perlvar{'lonDaemons'};
 4317:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
 4318: 	$reply=~s/\&/\n/g;
 4319: 	print $store $reply;
 4320: 	close $store;
 4321: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
 4322: 	print $store2 "done\n";
 4323: 	close $store2;
 4324: 	&Reply($client, "ok\n", $userinput);
 4325:     } else {
 4326: 	&Failure($client, "error: ".($!+0)
 4327: 		." IO::File->new Failed ".
 4328: 		"while attempting queryreply\n", $userinput);
 4329:     }
 4330:  
 4331: 
 4332:     return 1;
 4333: }
 4334: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
 4335: 
 4336: #
 4337: #  Process the courseidput request.  Not quite sure what this means
 4338: #  at the system level sense.  It appears a gdbm file in the 
 4339: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
 4340: #  a set of entries made in that database.
 4341: #
 4342: # Parameters:
 4343: #   $cmd      - The command keyword that initiated this request.
 4344: #   $tail     - Tail of the command.  In this case consists of a colon
 4345: #               separated list contaning the domain to apply this to and
 4346: #               an ampersand separated list of keyword=value pairs.
 4347: #               Each value is a colon separated list that includes:  
 4348: #               description, institutional code and course owner.
 4349: #               For backward compatibility with versions included
 4350: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
 4351: #               code and/or course owner are preserved from the existing 
 4352: #               record when writing a new record in response to 1.1 or 
 4353: #               1.2 implementations of lonnet::flushcourselogs().   
 4354: #                      
 4355: #   $client   - Socket open on the client.
 4356: # Returns:
 4357: #   1    - indicating that processing should continue
 4358: #
 4359: # Side effects:
 4360: #   reply is written to the client.
 4361: #
 4362: sub put_course_id_handler {
 4363:     my ($cmd, $tail, $client) = @_;
 4364: 
 4365: 
 4366:     my $userinput = "$cmd:$tail";
 4367: 
 4368:     my ($udom, $what) = split(/:/, $tail,2);
 4369:     chomp($what);
 4370:     my $now=time;
 4371:     my @pairs=split(/\&/,$what);
 4372: 
 4373:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 4374:     if ($hashref) {
 4375: 	foreach my $pair (@pairs) {
 4376:             my ($key,$courseinfo) = split(/=/,$pair,2);
 4377:             $courseinfo =~ s/=/:/g;
 4378:             if (defined($hashref->{$key})) {
 4379:                 my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
 4380:                 if (ref($value) eq 'HASH') {
 4381:                     my @items = ('description','inst_code','owner','type');
 4382:                     my @new_items = split(/:/,$courseinfo,-1);
 4383:                     my %storehash; 
 4384:                     for (my $i=0; $i<@new_items; $i++) {
 4385:                         $storehash{$items[$i]} = &unescape($new_items[$i]);
 4386:                     }
 4387:                     $hashref->{$key} = 
 4388:                         &Apache::lonnet::freeze_escape(\%storehash);
 4389:                     my $unesc_key = &unescape($key);
 4390:                     $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
 4391:                     next;
 4392:                 }
 4393:             }
 4394:             my @current_items = split(/:/,$hashref->{$key},-1);
 4395:             shift(@current_items); # remove description
 4396:             pop(@current_items);   # remove last access
 4397:             my $numcurrent = scalar(@current_items);
 4398:             if ($numcurrent > 3) {
 4399:                 $numcurrent = 3;
 4400:             }
 4401:             my @new_items = split(/:/,$courseinfo,-1);
 4402:             my $numnew = scalar(@new_items);
 4403:             if ($numcurrent > 0) {
 4404:                 if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2 
 4405:                     for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
 4406:                         $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
 4407:                     }
 4408:                 }
 4409:             }
 4410:             $hashref->{$key}=$courseinfo.':'.$now;
 4411: 	}
 4412: 	if (&untie_domain_hash($hashref)) {
 4413: 	    &Reply( $client, "ok\n", $userinput);
 4414: 	} else {
 4415: 	    &Failure($client, "error: ".($!+0)
 4416: 		     ." untie(GDBM) Failed ".
 4417: 		     "while attempting courseidput\n", $userinput);
 4418: 	}
 4419:     } else {
 4420: 	&Failure($client, "error: ".($!+0)
 4421: 		 ." tie(GDBM) Failed ".
 4422: 		 "while attempting courseidput\n", $userinput);
 4423:     }
 4424: 
 4425:     return 1;
 4426: }
 4427: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
 4428: 
 4429: sub put_course_id_hash_handler {
 4430:     my ($cmd, $tail, $client) = @_;
 4431:     my $userinput = "$cmd:$tail";
 4432:     my ($udom,$mode,$what) = split(/:/, $tail,3);
 4433:     chomp($what);
 4434:     my $now=time;
 4435:     my @pairs=split(/\&/,$what);
 4436:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 4437:     if ($hashref) {
 4438:         foreach my $pair (@pairs) {
 4439:             my ($key,$value)=split(/=/,$pair);
 4440:             my $unesc_key = &unescape($key);
 4441:             if ($mode ne 'timeonly') {
 4442:                 if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
 4443:                     my $curritems = &Apache::lonnet::thaw_unescape($key); 
 4444:                     if (ref($curritems) ne 'HASH') {
 4445:                         my @current_items = split(/:/,$hashref->{$key},-1);
 4446:                         my $lasttime = pop(@current_items);
 4447:                         $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
 4448:                     } else {
 4449:                         $hashref->{&escape('lasttime:'.$unesc_key)} = '';
 4450:                     }
 4451:                 } 
 4452:                 $hashref->{$key} = $value;
 4453:             }
 4454:             if ($mode ne 'notime') {
 4455:                 $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
 4456:             }
 4457:         }
 4458:         if (&untie_domain_hash($hashref)) {
 4459:             &Reply($client, "ok\n", $userinput);
 4460:         } else {
 4461:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4462:                      "while attempting courseidputhash\n", $userinput);
 4463:         }
 4464:     } else {
 4465:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 4466:                   "while attempting courseidputhash\n", $userinput);
 4467:     }
 4468:     return 1;
 4469: }
 4470: &register_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
 4471: 
 4472: #  Retrieves the value of a course id resource keyword pattern
 4473: #  defined since a starting date.  Both the starting date and the
 4474: #  keyword pattern are optional.  If the starting date is not supplied it
 4475: #  is treated as the beginning of time.  If the pattern is not found,
 4476: #  it is treatred as "." matching everything.
 4477: #
 4478: #  Parameters:
 4479: #     $cmd     - Command keyword that resulted in us being dispatched.
 4480: #     $tail    - The remainder of the command that, in this case, consists
 4481: #                of a colon separated list of:
 4482: #                 domain   - The domain in which the course database is 
 4483: #                            defined.
 4484: #                 since    - Optional parameter describing the minimum
 4485: #                            time of definition(?) of the resources that
 4486: #                            will match the dump.
 4487: #                 description - regular expression that is used to filter
 4488: #                            the dump.  Only keywords matching this regexp
 4489: #                            will be used.
 4490: #                 institutional code - optional supplied code to filter 
 4491: #                            the dump. Only courses with an institutional code 
 4492: #                            that match the supplied code will be returned.
 4493: #                 owner    - optional supplied username and domain of owner to
 4494: #                            filter the dump.  Only courses for which the course
 4495: #                            owner matches the supplied username and/or domain
 4496: #                            will be returned. Pre-2.2.0 legacy entries from 
 4497: #                            nohist_courseiddump will only contain usernames.
 4498: #                 type     - optional parameter for selection 
 4499: #                 regexp_ok - if 1 or -1 allow the supplied institutional code
 4500: #                            filter to behave as a regular expression:
 4501: #	                      1 will not exclude the course if the instcode matches the RE 
 4502: #                            -1 will exclude the course if the instcode matches the RE
 4503: #                 rtn_as_hash - whether to return the information available for
 4504: #                            each matched item as a frozen hash of all 
 4505: #                            key, value pairs in the item's hash, or as a 
 4506: #                            colon-separated list of (in order) description,
 4507: #                            institutional code, and course owner.
 4508: #                 selfenrollonly - filter by courses allowing self-enrollment  
 4509: #                                  now or in the future (selfenrollonly = 1).
 4510: #                 catfilter - filter by course category, assigned to a course 
 4511: #                             using manually defined categories (i.e., not
 4512: #                             self-cataloging based on on institutional code).   
 4513: #                 showhidden - include course in results even if course  
 4514: #                              was set to be excluded from course catalog (DC only).
 4515: #                 caller -  if set to 'coursecatalog', courses set to be hidden
 4516: #                           from course catalog will be excluded from results (unless
 4517: #                           overridden by "showhidden".
 4518: #                 cloner - escaped username:domain of course cloner (if picking course to
 4519: #                          clone).
 4520: #                 cc_clone_list - escaped comma separated list of courses for which 
 4521: #                                 course cloner has active CC role (and so can clone
 4522: #                                 automatically).
 4523: #                 cloneonly - filter by courses for which cloner has rights to clone.
 4524: #                 createdbefore - include courses for which creation date preceeded this date.
 4525: #                 createdafter - include courses for which creation date followed this date.
 4526: #                 creationcontext - include courses created in specified context 
 4527: #
 4528: #                 domcloner - flag to indicate if user can create CCs in course's domain.
 4529: #                             If so, ability to clone course is automatic.
 4530: #                 hasuniquecode - filter by courses for which a six character unique code has 
 4531: #                                 been set.
 4532: #
 4533: #     $client  - The socket open on the client.
 4534: # Returns:
 4535: #    1     - Continue processing.
 4536: # Side Effects:
 4537: #   a reply is written to $client.
 4538: sub dump_course_id_handler {
 4539:     my ($cmd, $tail, $client) = @_;
 4540: 
 4541:     my $res = LONCAPA::Lond::dump_course_id_handler($tail);
 4542:     if ($res =~ /^error:/) {
 4543:         Failure($client, \$res, "$cmd:$tail");
 4544:     } else {
 4545:         Reply($client, \$res, "$cmd:$tail");
 4546:     }
 4547: 
 4548:     return 1;  
 4549: 
 4550:     #TODO remove
 4551:     my $userinput = "$cmd:$tail";
 4552: 
 4553:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
 4554:         $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
 4555:         $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
 4556:         $creationcontext,$domcloner,$hasuniquecode) =split(/:/,$tail);
 4557:     my $now = time;
 4558:     my ($cloneruname,$clonerudom,%cc_clone);
 4559:     if (defined($description)) {
 4560: 	$description=&unescape($description);
 4561:     } else {
 4562: 	$description='.';
 4563:     }
 4564:     if (defined($instcodefilter)) {
 4565:         $instcodefilter=&unescape($instcodefilter);
 4566:     } else {
 4567:         $instcodefilter='.';
 4568:     }
 4569:     my ($ownerunamefilter,$ownerdomfilter);
 4570:     if (defined($ownerfilter)) {
 4571:         $ownerfilter=&unescape($ownerfilter);
 4572:         if ($ownerfilter ne '.' && defined($ownerfilter)) {
 4573:             if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
 4574:                  $ownerunamefilter = $1;
 4575:                  $ownerdomfilter = $2;
 4576:             } else {
 4577:                 $ownerunamefilter = $ownerfilter;
 4578:                 $ownerdomfilter = '';
 4579:             }
 4580:         }
 4581:     } else {
 4582:         $ownerfilter='.';
 4583:     }
 4584: 
 4585:     if (defined($coursefilter)) {
 4586:         $coursefilter=&unescape($coursefilter);
 4587:     } else {
 4588:         $coursefilter='.';
 4589:     }
 4590:     if (defined($typefilter)) {
 4591:         $typefilter=&unescape($typefilter);
 4592:     } else {
 4593:         $typefilter='.';
 4594:     }
 4595:     if (defined($regexp_ok)) {
 4596:         $regexp_ok=&unescape($regexp_ok);
 4597:     }
 4598:     if (defined($catfilter)) {
 4599:         $catfilter=&unescape($catfilter);
 4600:     }
 4601:     if (defined($cloner)) {
 4602:         $cloner = &unescape($cloner);
 4603:         ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/); 
 4604:     }
 4605:     if (defined($cc_clone_list)) {
 4606:         $cc_clone_list = &unescape($cc_clone_list);
 4607:         my @cc_cloners = split('&',$cc_clone_list);
 4608:         foreach my $cid (@cc_cloners) {
 4609:             my ($clonedom,$clonenum) = split(':',$cid);
 4610:             next if ($clonedom ne $udom); 
 4611:             $cc_clone{$clonedom.'_'.$clonenum} = 1;
 4612:         } 
 4613:     }
 4614:     if ($createdbefore ne '') {
 4615:         $createdbefore = &unescape($createdbefore);
 4616:     } else {
 4617:        $createdbefore = 0;
 4618:     }
 4619:     if ($createdafter ne '') {
 4620:         $createdafter = &unescape($createdafter);
 4621:     } else {
 4622:         $createdafter = 0;
 4623:     }
 4624:     if ($creationcontext ne '') {
 4625:         $creationcontext = &unescape($creationcontext);
 4626:     } else {
 4627:         $creationcontext = '.';
 4628:     }
 4629:     unless ($hasuniquecode) {
 4630:         $hasuniquecode = '.';
 4631:     }
 4632:     my $unpack = 1;
 4633:     if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' && 
 4634:         $typefilter eq '.') {
 4635:         $unpack = 0;
 4636:     }
 4637:     if (!defined($since)) { $since=0; }
 4638:     my $qresult='';
 4639:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 4640:     if ($hashref) {
 4641: 	while (my ($key,$value) = each(%$hashref)) {
 4642:             my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
 4643:                 %unesc_val,$selfenroll_end,$selfenroll_types,$created,
 4644:                 $context);
 4645:             $unesc_key = &unescape($key);
 4646:             if ($unesc_key =~ /^lasttime:/) {
 4647:                 next;
 4648:             } else {
 4649:                 $lasttime_key = &escape('lasttime:'.$unesc_key);
 4650:             }
 4651:             if ($hashref->{$lasttime_key} ne '') {
 4652:                 $lasttime = $hashref->{$lasttime_key};
 4653:                 next if ($lasttime<$since);
 4654:             }
 4655:             my ($canclone,$valchange);
 4656:             my $items = &Apache::lonnet::thaw_unescape($value);
 4657:             if (ref($items) eq 'HASH') {
 4658:                 if ($hashref->{$lasttime_key} eq '') {
 4659:                     next if ($since > 1);
 4660:                 }
 4661:                 $is_hash =  1;
 4662:                 if ($domcloner) {
 4663:                     $canclone = 1;
 4664:                 } elsif (defined($clonerudom)) {
 4665:                     if ($items->{'cloners'}) {
 4666:                         my @cloneable = split(',',$items->{'cloners'});
 4667:                         if (@cloneable) {
 4668:                             if (grep(/^\*$/,@cloneable))  {
 4669:                                 $canclone = 1;
 4670:                             } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
 4671:                                 $canclone = 1;
 4672:                             } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
 4673:                                 $canclone = 1;
 4674:                             }
 4675:                         }
 4676:                         unless ($canclone) {
 4677:                             if ($cloneruname ne '' && $clonerudom ne '') {
 4678:                                 if ($cc_clone{$unesc_key}) {
 4679:                                     $canclone = 1;
 4680:                                     $items->{'cloners'} .= ','.$cloneruname.':'.
 4681:                                                            $clonerudom;
 4682:                                     $valchange = 1;
 4683:                                 }
 4684:                             }
 4685:                         }
 4686:                     } elsif (defined($cloneruname)) {
 4687:                         if ($cc_clone{$unesc_key}) {
 4688:                             $canclone = 1;
 4689:                             $items->{'cloners'} = $cloneruname.':'.$clonerudom;
 4690:                             $valchange = 1;
 4691:                         }
 4692:                         unless ($canclone) {
 4693:                             if ($items->{'owner'} =~ /:/) {
 4694:                                 if ($items->{'owner'} eq $cloner) {
 4695:                                     $canclone = 1;
 4696:                                 }
 4697:                             } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
 4698:                                 $canclone = 1;
 4699:                             }
 4700:                             if ($canclone) {
 4701:                                 $items->{'cloners'} = $cloneruname.':'.$clonerudom;
 4702:                                 $valchange = 1;
 4703:                             }
 4704:                         }
 4705:                     }
 4706:                 }
 4707:                 if ($unpack || !$rtn_as_hash) {
 4708:                     $unesc_val{'descr'} = $items->{'description'};
 4709:                     $unesc_val{'inst_code'} = $items->{'inst_code'};
 4710:                     $unesc_val{'owner'} = $items->{'owner'};
 4711:                     $unesc_val{'type'} = $items->{'type'};
 4712:                     $unesc_val{'cloners'} = $items->{'cloners'};
 4713:                     $unesc_val{'created'} = $items->{'created'};
 4714:                     $unesc_val{'context'} = $items->{'context'};
 4715:                 }
 4716:                 $selfenroll_types = $items->{'selfenroll_types'};
 4717:                 $selfenroll_end = $items->{'selfenroll_end_date'};
 4718:                 $created = $items->{'created'};
 4719:                 $context = $items->{'context'};
 4720:                 if ($hasuniquecode ne '.') {
 4721:                     next unless ($items->{'uniquecode'});
 4722:                 }
 4723:                 if ($selfenrollonly) {
 4724:                     next if (!$selfenroll_types);
 4725:                     if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
 4726:                         next;
 4727:                     }
 4728:                 }
 4729:                 if ($creationcontext ne '.') {
 4730:                     next if (($context ne '') && ($context ne $creationcontext));  
 4731:                 }
 4732:                 if ($createdbefore > 0) {
 4733:                     next if (($created eq '') || ($created > $createdbefore));   
 4734:                 }
 4735:                 if ($createdafter > 0) {
 4736:                     next if (($created eq '') || ($created <= $createdafter)); 
 4737:                 }
 4738:                 if ($catfilter ne '') {
 4739:                     next if ($items->{'categories'} eq '');
 4740:                     my @categories = split('&',$items->{'categories'}); 
 4741:                     next if (@categories == 0);
 4742:                     my @subcats = split('&',$catfilter);
 4743:                     my $matchcat = 0;
 4744:                     foreach my $cat (@categories) {
 4745:                         if (grep(/^\Q$cat\E$/,@subcats)) {
 4746:                             $matchcat = 1;
 4747:                             last;
 4748:                         }
 4749:                     }
 4750:                     next if (!$matchcat);
 4751:                 }
 4752:                 if ($caller eq 'coursecatalog') {
 4753:                     if ($items->{'hidefromcat'} eq 'yes') {
 4754:                         next if !$showhidden;
 4755:                     }
 4756:                 }
 4757:             } else {
 4758:                 next if ($catfilter ne '');
 4759:                 next if ($selfenrollonly);
 4760:                 next if ($createdbefore || $createdafter);
 4761:                 next if ($creationcontext ne '.');
 4762:                 if ((defined($clonerudom)) && (defined($cloneruname)))  {
 4763:                     if ($cc_clone{$unesc_key}) {
 4764:                         $canclone = 1;
 4765:                         $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
 4766:                     }
 4767:                 }
 4768:                 $is_hash =  0;
 4769:                 my @courseitems = split(/:/,$value);
 4770:                 $lasttime = pop(@courseitems);
 4771:                 if ($hashref->{$lasttime_key} eq '') {
 4772:                     next if ($lasttime<$since);
 4773:                 }
 4774: 	        ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
 4775:             }
 4776:             if ($cloneonly) {
 4777:                next unless ($canclone);
 4778:             }
 4779:             my $match = 1;
 4780: 	    if ($description ne '.') {
 4781:                 if (!$is_hash) {
 4782:                     $unesc_val{'descr'} = &unescape($val{'descr'});
 4783:                 }
 4784:                 if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
 4785:                     $match = 0;
 4786:                 }
 4787:             }
 4788:             if ($instcodefilter ne '.') {
 4789:                 if (!$is_hash) {
 4790:                     $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
 4791:                 }
 4792:                 if ($regexp_ok == 1) {
 4793:                     if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
 4794:                         $match = 0;
 4795:                     }
 4796:                 } elsif ($regexp_ok == -1) {
 4797:                     if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
 4798:                         $match = 0;
 4799:                     }
 4800:                 } else {
 4801:                     if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
 4802:                         $match = 0;
 4803:                     }
 4804:                 }
 4805: 	    }
 4806:             if ($ownerfilter ne '.') {
 4807:                 if (!$is_hash) {
 4808:                     $unesc_val{'owner'} = &unescape($val{'owner'});
 4809:                 }
 4810:                 if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
 4811:                     if ($unesc_val{'owner'} =~ /:/) {
 4812:                         if (eval{$unesc_val{'owner'} !~ 
 4813:                              /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
 4814:                             $match = 0;
 4815:                         } 
 4816:                     } else {
 4817:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
 4818:                             $match = 0;
 4819:                         }
 4820:                     }
 4821:                 } elsif ($ownerunamefilter ne '') {
 4822:                     if ($unesc_val{'owner'} =~ /:/) {
 4823:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
 4824:                              $match = 0;
 4825:                         }
 4826:                     } else {
 4827:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
 4828:                             $match = 0;
 4829:                         }
 4830:                     }
 4831:                 } elsif ($ownerdomfilter ne '') {
 4832:                     if ($unesc_val{'owner'} =~ /:/) {
 4833:                         if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
 4834:                              $match = 0;
 4835:                         }
 4836:                     } else {
 4837:                         if ($ownerdomfilter ne $udom) {
 4838:                             $match = 0;
 4839:                         }
 4840:                     }
 4841:                 }
 4842:             }
 4843:             if ($coursefilter ne '.') {
 4844:                 if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
 4845:                     $match = 0;
 4846:                 }
 4847:             }
 4848:             if ($typefilter ne '.') {
 4849:                 if (!$is_hash) {
 4850:                     $unesc_val{'type'} = &unescape($val{'type'});
 4851:                 }
 4852:                 if ($unesc_val{'type'} eq '') {
 4853:                     if ($typefilter ne 'Course') {
 4854:                         $match = 0;
 4855:                     }
 4856:                 } else {
 4857:                     if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
 4858:                         $match = 0;
 4859:                     }
 4860:                 }
 4861:             }
 4862:             if ($match == 1) {
 4863:                 if ($rtn_as_hash) {
 4864:                     if ($is_hash) {
 4865:                         if ($valchange) {
 4866:                             my $newvalue = &Apache::lonnet::freeze_escape($items);
 4867:                             $qresult.=$key.'='.$newvalue.'&';
 4868:                         } else {
 4869:                             $qresult.=$key.'='.$value.'&';
 4870:                         }
 4871:                     } else {
 4872:                         my %rtnhash = ( 'description' => &unescape($val{'descr'}),
 4873:                                         'inst_code' => &unescape($val{'inst_code'}),
 4874:                                         'owner'     => &unescape($val{'owner'}),
 4875:                                         'type'      => &unescape($val{'type'}),
 4876:                                         'cloners'   => &unescape($val{'cloners'}),
 4877:                                       );
 4878:                         my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
 4879:                         $qresult.=$key.'='.$items.'&';
 4880:                     }
 4881:                 } else {
 4882:                     if ($is_hash) {
 4883:                         $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
 4884:                                     &escape($unesc_val{'inst_code'}).':'.
 4885:                                     &escape($unesc_val{'owner'}).'&';
 4886:                     } else {
 4887:                         $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
 4888:                                     ':'.$val{'owner'}.'&';
 4889:                     }
 4890:                 }
 4891:             }
 4892: 	}
 4893: 	if (&untie_domain_hash($hashref)) {
 4894: 	    chop($qresult);
 4895: 	    &Reply($client, \$qresult, $userinput);
 4896: 	} else {
 4897: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4898: 		    "while attempting courseiddump\n", $userinput);
 4899: 	}
 4900:     } else {
 4901: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 4902: 		"while attempting courseiddump\n", $userinput);
 4903:     }
 4904:     return 1;
 4905: }
 4906: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
 4907: 
 4908: sub course_lastaccess_handler {
 4909:     my ($cmd, $tail, $client) = @_;
 4910:     my $userinput = "$cmd:$tail";
 4911:     my ($cdom,$cnum) = split(':',$tail); 
 4912:     my (%lastaccess,$qresult);
 4913:     my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
 4914:     if ($hashref) {
 4915:         while (my ($key,$value) = each(%$hashref)) {
 4916:             my ($unesc_key,$lasttime);
 4917:             $unesc_key = &unescape($key);
 4918:             if ($cnum) {
 4919:                 next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
 4920:             }
 4921:             if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
 4922:                 $lastaccess{$1} = $value;
 4923:             } else {
 4924:                 my $items = &Apache::lonnet::thaw_unescape($value);
 4925:                 if (ref($items) eq 'HASH') {
 4926:                     unless ($lastaccess{$unesc_key}) {
 4927:                         $lastaccess{$unesc_key} = '';
 4928:                     }
 4929:                 } else {
 4930:                     my @courseitems = split(':',$value);
 4931:                     $lastaccess{$unesc_key} = pop(@courseitems);
 4932:                 }
 4933:             }
 4934:         }
 4935:         foreach my $cid (sort(keys(%lastaccess))) {
 4936:             $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&'; 
 4937:         }
 4938:         if (&untie_domain_hash($hashref)) {
 4939:             if ($qresult) {
 4940:                 chop($qresult);
 4941:             }
 4942:             &Reply($client, \$qresult, $userinput);
 4943:         } else {
 4944:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4945:                     "while attempting lastacourseaccess\n", $userinput);
 4946:         }
 4947:     } else {
 4948:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 4949:                 "while attempting lastcourseaccess\n", $userinput);
 4950:     }
 4951:     return 1;
 4952: }
 4953: &register_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
 4954: 
 4955: sub course_sessions_handler {
 4956:     my ($cmd, $tail, $client) = @_;
 4957:     my $userinput = "$cmd:$tail";
 4958:     my ($cdom,$cnum,$lastactivity) = split(':',$tail);
 4959:     my $dbsuffix = '_'.$cdom.'_'.$cnum.'.db';
 4960:     my (%sessions,$qresult);
 4961:     my $now=time;
 4962:     if (opendir(DIR,$perlvar{'lonIDsDir'})) {
 4963:         my $filename;
 4964:         while ($filename=readdir(DIR)) {
 4965:             next if ($filename=~/^\./);
 4966:             next if ($filename=~/^publicuser_/);
 4967:             next if ($filename=~/^[a-f0-9]+_(linked|lti_\d+)\.id$/);
 4968:             if ($filename =~ /^($LONCAPA::match_username)_\d+_($LONCAPA::match_domain)_/) {
 4969:                 my ($uname,$udom) = ($1,$2);
 4970:                 next unless (-e "$perlvar{'lonDaemons'}/tmp/$uname$dbsuffix");
 4971:                 my $mtime = (stat("$perlvar{'lonIDsDir'}/$filename"))[9];
 4972:                 if ($lastactivity < 0) {
 4973:                     next if ($mtime-$now > $lastactivity);
 4974:                 } else {
 4975:                     next if ($now-$mtime > $lastactivity);
 4976:                 }
 4977:                 $sessions{$uname.':'.$udom} = $mtime;
 4978:             }
 4979:         }
 4980:         closedir(DIR); 
 4981:     }
 4982:     foreach my $user (keys(%sessions)) {
 4983:         $qresult.=&escape($user).'='.$sessions{$user}.'&';
 4984:     }
 4985:     if ($qresult) {
 4986:         chop($qresult);
 4987:     }
 4988:     &Reply($client, \$qresult, $userinput);
 4989:     return 1;
 4990: }
 4991: &register_handler("coursesessions",\&course_sessions_handler, 0, 1, 0);
 4992: 
 4993: #
 4994: # Puts an unencrypted entry in a namespace db file at the domain level 
 4995: #
 4996: # Parameters:
 4997: #    $cmd      - The command that got us here.
 4998: #    $tail     - Tail of the command (remaining parameters).
 4999: #    $client   - File descriptor connected to client.
 5000: # Returns
 5001: #     0        - Requested to exit, caller should shut down.
 5002: #     1        - Continue processing.
 5003: #  Side effects:
 5004: #     reply is written to $client.
 5005: #
 5006: sub put_domain_handler {
 5007:     my ($cmd,$tail,$client) = @_;
 5008: 
 5009:     my $userinput = "$cmd:$tail";
 5010: 
 5011:     my ($udom,$namespace,$what) =split(/:/,$tail,3);
 5012:     chomp($what);
 5013:     my @pairs=split(/\&/,$what);
 5014:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
 5015:                                    "P", $what);
 5016:     if ($hashref) {
 5017:         foreach my $pair (@pairs) {
 5018:             my ($key,$value)=split(/=/,$pair);
 5019:             $hashref->{$key}=$value;
 5020:         }
 5021:         if (&untie_domain_hash($hashref)) {
 5022:             &Reply($client, "ok\n", $userinput);
 5023:         } else {
 5024:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5025:                      "while attempting putdom\n", $userinput);
 5026:         }
 5027:     } else {
 5028:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 5029:                   "while attempting putdom\n", $userinput);
 5030:     }
 5031: 
 5032:     return 1;
 5033: }
 5034: &register_handler("putdom", \&put_domain_handler, 0, 1, 0);
 5035: 
 5036: # Updates one or more entries in clickers.db file at the domain level
 5037: #
 5038: # Parameters:
 5039: #    $cmd      - The command that got us here.
 5040: #    $tail     - Tail of the command (remaining parameters).
 5041: #                In this case a colon separated list containing:
 5042: #                (a) the domain for which we are updating the entries,
 5043: #                (b) the action required -- add or del -- and
 5044: #                (c) a &-separated list of entries to add or delete.
 5045: #    $client   - File descriptor connected to client.
 5046: # Returns
 5047: #     1        - Continue processing.
 5048: #     0        - Requested to exit, caller should shut down.
 5049: #  Side effects:
 5050: #     reply is written to $client.
 5051: #
 5052: 
 5053: 
 5054: sub update_clickers {
 5055:     my ($cmd, $tail, $client)  = @_;
 5056: 
 5057:     my $userinput = "$cmd:$tail";
 5058:     my ($udom,$action,$what) =split(/:/,$tail,3);
 5059:     chomp($what);
 5060: 
 5061:     my $hashref = &tie_domain_hash($udom, "clickers", &GDBM_WRCREAT(),
 5062:                                  "U","$action:$what");
 5063: 
 5064:     if (!$hashref) {
 5065:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 5066:                   "while attempting updateclickers\n", $userinput);
 5067:         return 1;
 5068:     }
 5069: 
 5070:     my @pairs=split(/\&/,$what);
 5071:     foreach my $pair (@pairs) {
 5072:         my ($key,$value)=split(/=/,$pair);
 5073:         if ($action eq 'add') {
 5074:             if (exists($hashref->{$key})) {
 5075:                 my @newvals = split(/,/,&unescape($value));
 5076:                 my @currvals = split(/,/,&unescape($hashref->{$key}));
 5077:                 my @merged = sort(keys(%{{map { $_ => 1 } (@newvals,@currvals)}}));
 5078:                 $hashref->{$key}=&escape(join(',',@merged));
 5079:             } else {
 5080:                 $hashref->{$key}=$value;
 5081:             }
 5082:         } elsif ($action eq 'del') {
 5083:             if (exists($hashref->{$key})) {
 5084:                 my %current;
 5085:                 map { $current{$_} = 1; } split(/,/,&unescape($hashref->{$key}));
 5086:                 map { delete($current{$_}); } split(/,/,&unescape($value));
 5087:                 if (keys(%current)) {
 5088:                     $hashref->{$key}=&escape(join(',',sort(keys(%current))));
 5089:                 } else {
 5090:                     delete($hashref->{$key});
 5091:                 }
 5092:             }
 5093:         }
 5094:     }
 5095:     if (&untie_user_hash($hashref)) {
 5096:         &Reply( $client, "ok\n", $userinput);
 5097:     } else {
 5098:         &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 5099:                  "while attempting put\n",
 5100:                  $userinput);
 5101:     }
 5102:     return 1;
 5103: }
 5104: &register_handler("updateclickers", \&update_clickers, 0, 1, 0);
 5105: 
 5106: 
 5107: # Deletes one or more entries in a namespace db file at the domain level
 5108: #
 5109: # Parameters:
 5110: #    $cmd      - The command that got us here.
 5111: #    $tail     - Tail of the command (remaining parameters).
 5112: #                In this case a colon separated list containing:
 5113: #                (a) the domain for which we are deleting the entries,
 5114: #                (b) &-separated list of keys to delete.  
 5115: #    $client   - File descriptor connected to client.
 5116: # Returns
 5117: #     1        - Continue processing.
 5118: #     0        - Requested to exit, caller should shut down.
 5119: #  Side effects:
 5120: #     reply is written to $client.
 5121: #
 5122: 
 5123: sub del_domain_handler {
 5124:     my ($cmd,$tail,$client) = @_;
 5125: 
 5126:     my $userinput = "$cmd:$tail";
 5127: 
 5128:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
 5129:     chomp($what);
 5130:     my $hashref = &tie_domain_hash($udom,$namespace,&GDBM_WRCREAT(),
 5131:                                    "D", $what);
 5132:     if ($hashref) {
 5133:         my @keys=split(/\&/,$what);
 5134:         foreach my $key (@keys) {
 5135:             delete($hashref->{$key});
 5136:         }
 5137:         if (&untie_user_hash($hashref)) {
 5138:             &Reply($client, "ok\n", $userinput);
 5139:         } else {
 5140:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5141:                     "while attempting deldom\n", $userinput);
 5142:         }
 5143:     } else {
 5144:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 5145:                  "while attempting deldom\n", $userinput);
 5146:     }
 5147:     return 1;
 5148: }
 5149: &register_handler("deldom", \&del_domain_handler, 0, 1, 0);
 5150: 
 5151: 
 5152: # Unencrypted get from the namespace database file at the domain level.
 5153: # This function retrieves a keyed item from a specific named database in the
 5154: # domain directory.
 5155: #
 5156: # Parameters:
 5157: #   $cmd             - Command request keyword (getdom).
 5158: #   $tail            - Tail of the command.  This is a colon separated list
 5159: #                      consisting of the domain and the 'namespace' 
 5160: #                      which selects the gdbm file to do the lookup in,
 5161: #                      & separated list of keys to lookup.  Note that
 5162: #                      the values are returned as an & separated list too.
 5163: #   $client          - File descriptor open on the client.
 5164: # Returns:
 5165: #   1       - Continue processing.
 5166: #   0       - Exit.
 5167: #  Side effects:
 5168: #     reply is written to $client.
 5169: #
 5170: 
 5171: sub get_domain_handler {
 5172:     my ($cmd, $tail, $client) = @_;
 5173: 
 5174:     my $userinput = "$cmd:$tail";
 5175: 
 5176:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
 5177:     if (($namespace =~ /^enc/) || ($namespace eq 'private')) {
 5178:         &Failure( $client, "refused\n", $userinput);
 5179:     } else {
 5180:         my $res = LONCAPA::Lond::get_dom($userinput);
 5181:         if ($res =~ /^error:/) {
 5182:             &Failure($client, \$res, $userinput);
 5183:         } else {
 5184:             &Reply($client, \$res, $userinput);
 5185:         }
 5186:     }
 5187: 
 5188:     return 1;
 5189: }
 5190: &register_handler("getdom", \&get_domain_handler, 0, 1, 0);
 5191: 
 5192: #
 5193: # Encrypted get from the namespace database file at the domain level.
 5194: # This function retrieves a keyed item from a specific named database in the
 5195: # domain directory.
 5196: #
 5197: # Parameters:
 5198: #   $cmd             - Command request keyword (egetdom).
 5199: #   $tail            - Tail of the command.  This is a colon separated list
 5200: #                      consisting of the domain and the 'namespace'
 5201: #                      which selects the gdbm file to do the lookup in,
 5202: #                      & separated list of keys to lookup.  Note that
 5203: #                      the values are returned as an & separated list too.
 5204: #   $client          - File descriptor open on the client.
 5205: # Returns:
 5206: #   1       - Continue processing.
 5207: #   0       - Exit.
 5208: #  Side effects:
 5209: #     reply is encrypted before being written to $client.
 5210: #
 5211: sub encrypted_get_domain_handler {
 5212:     my ($cmd, $tail, $client) = @_;
 5213: 
 5214:     my $userinput = "$cmd:$tail";
 5215: 
 5216:     my ($udom,$namespace,$what) = split(/:/,$tail,3);
 5217:     if ($namespace eq 'private') {
 5218:         &Failure( $client, "refused\n", $userinput);
 5219:     } else {
 5220:         my $res = LONCAPA::Lond::get_dom($userinput);
 5221:         if ($res =~ /^error:/) {
 5222:             &Failure($client, \$res, $userinput);
 5223:         } else {
 5224:             if ($cipher) {
 5225:                 my $cmdlength=length($res);
 5226:                 $res.="         ";
 5227:                 my $encres='';
 5228:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 5229:                     $encres.= unpack("H16",
 5230:                                      $cipher->encrypt(substr($res,
 5231:                                                              $encidx,
 5232:                                                              8)));
 5233:                 }
 5234:                 &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
 5235:             } else {
 5236:                 &Failure( $client, "error:no_key\n",$userinput);
 5237:             }
 5238:         }
 5239:     }
 5240:     return 1;
 5241: }
 5242: &register_handler("egetdom", \&encrypted_get_domain_handler, 1, 1, 0);
 5243: 
 5244: #
 5245: # Encrypted get from the namespace database file at the domain level.
 5246: # This function retrieves a keyed item from a specific named database in the
 5247: # domain directory.
 5248: #
 5249: # Parameters:
 5250: #   $cmd             - Command request keyword (lti).
 5251: #   $tail            - Tail of the command.  This is a colon-separated list
 5252: #                      consisting of the domain, coursenum, if for LTI-
 5253: #                      enabled deep-linking to course content using
 5254: #                      link protection configured within a course,
 5255: #                      context (=deeplink) if for LTI-enabled deep-linking
 5256: #                      to course content using LTI Provider settings
 5257: #                      configured within a course's domain, the (escaped)
 5258: #                      launch URL, the (escaped) method (typically POST),
 5259: #                      and a frozen hash of the LTI launch parameters
 5260: #                      from the LTI payload.
 5261: #   $client          - File descriptor open on the client.
 5262: # Returns:
 5263: #   1       - Continue processing.
 5264: #   0       - Exit.
 5265: #  Side effects:
 5266: #     The reply will contain an LTI itemID, if the signed LTI payload
 5267: #     could be verified using the consumer key and the shared secret 
 5268: #     available for that key (for the itemID) for either the course or domain, 
 5269: #     depending on values for cnum and context. The reply is encrypted before 
 5270: #     being written to $client.
 5271: #
 5272: sub lti_handler {
 5273:     my ($cmd, $tail, $client) = @_;
 5274: 
 5275:     my $userinput = "$cmd:$tail";
 5276: 
 5277:     my ($cdom,$cnum,$context,$escurl,$escmethod,$items) = split(/:/,$tail);
 5278:     my $url = &unescape($escurl);
 5279:     my $method = &unescape($escmethod);
 5280:     my $params = &Apache::lonnet::thaw_unescape($items);
 5281:     my $res;
 5282:     if ($cnum ne '') {
 5283:         $res = &LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
 5284:     } else {
 5285:         $res = &LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
 5286:     }
 5287:     if ($res =~ /^error:/) {
 5288:         &Failure($client, \$res, $userinput);
 5289:     } else {
 5290:         if ($cipher) {
 5291:             my $cmdlength=length($res);
 5292:             $res.="         ";
 5293:             my $encres='';
 5294:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 5295:                 $encres.= unpack("H16",
 5296:                                  $cipher->encrypt(substr($res,
 5297:                                                          $encidx,
 5298:                                                          8)));
 5299:             }
 5300:             &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
 5301:         } else {
 5302:             &Failure( $client, "error:no_key\n",$userinput);
 5303:         }
 5304:     }
 5305:     return 1;
 5306: }
 5307: &register_handler("lti", \&lti_handler, 1, 1, 0);
 5308: 
 5309: #
 5310: #  Puts an id to a domains id database. 
 5311: #
 5312: #  Parameters:
 5313: #   $cmd     - The command that triggered us.
 5314: #   $tail    - Remainder of the request other than the command. This is a 
 5315: #              colon separated list containing:
 5316: #              $domain  - The domain for which we are writing the id.
 5317: #              $pairs  - The id info to write... this is and & separated list
 5318: #                        of keyword=value.
 5319: #   $client  - Socket open on the client.
 5320: #  Returns:
 5321: #    1   - Continue processing.
 5322: #  Side effects:
 5323: #     reply is written to $client.
 5324: #
 5325: sub put_id_handler {
 5326:     my ($cmd,$tail,$client) = @_;
 5327: 
 5328: 
 5329:     my $userinput = "$cmd:$tail";
 5330: 
 5331:     my ($udom,$what)=split(/:/,$tail);
 5332:     chomp($what);
 5333:     my @pairs=split(/\&/,$what);
 5334:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
 5335: 				   "P", $what);
 5336:     if ($hashref) {
 5337: 	foreach my $pair (@pairs) {
 5338: 	    my ($key,$value)=split(/=/,$pair);
 5339: 	    $hashref->{$key}=$value;
 5340: 	}
 5341: 	if (&untie_domain_hash($hashref)) {
 5342: 	    &Reply($client, "ok\n", $userinput);
 5343: 	} else {
 5344: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5345: 		     "while attempting idput\n", $userinput);
 5346: 	}
 5347:     } else {
 5348: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 5349: 		  "while attempting idput\n", $userinput);
 5350:     }
 5351: 
 5352:     return 1;
 5353: }
 5354: &register_handler("idput", \&put_id_handler, 0, 1, 0);
 5355: 
 5356: #
 5357: #  Retrieves a set of id values from the id database.
 5358: #  Returns an & separated list of results, one for each requested id to the
 5359: #  client.
 5360: #
 5361: # Parameters:
 5362: #   $cmd       - Command keyword that caused us to be dispatched.
 5363: #   $tail      - Tail of the command.  Consists of a colon separated:
 5364: #               domain - the domain whose id table we dump
 5365: #               ids      Consists of an & separated list of
 5366: #                        id keywords whose values will be fetched.
 5367: #                        nonexisting keywords will have an empty value.
 5368: #   $client    - Socket open on the client.
 5369: #
 5370: # Returns:
 5371: #    1 - indicating processing should continue.
 5372: # Side effects:
 5373: #   An & separated list of results is written to $client.
 5374: #
 5375: sub get_id_handler {
 5376:     my ($cmd, $tail, $client) = @_;
 5377: 
 5378:     
 5379:     my $userinput = "$client:$tail";
 5380:     
 5381:     my ($udom,$what)=split(/:/,$tail);
 5382:     chomp($what);
 5383:     my @queries=split(/\&/,$what);
 5384:     my $qresult='';
 5385:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
 5386:     if ($hashref) {
 5387: 	for (my $i=0;$i<=$#queries;$i++) {
 5388: 	    $qresult.="$hashref->{$queries[$i]}&";
 5389: 	}
 5390: 	if (&untie_domain_hash($hashref)) {
 5391: 	    $qresult=~s/\&$//;
 5392: 	    &Reply($client, \$qresult, $userinput);
 5393: 	} else {
 5394: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 5395: 		      "while attempting idget\n",$userinput);
 5396: 	}
 5397:     } else {
 5398: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 5399: 		 "while attempting idget\n",$userinput);
 5400:     }
 5401:     
 5402:     return 1;
 5403: }
 5404: &register_handler("idget", \&get_id_handler, 0, 1, 0);
 5405: 
 5406: #   Deletes one or more ids in a domain's id database.
 5407: #
 5408: #   Parameters:
 5409: #       $cmd                  - Command keyword (iddel).
 5410: #       $tail                 - Command tail.  In this case a colon
 5411: #                               separated list containing:
 5412: #                               The domain for which we are deleting the id(s).
 5413: #                               &-separated list of id(s) to delete.
 5414: #       $client               - File open on client socket.
 5415: # Returns:
 5416: #     1   - Continue processing
 5417: #     0   - Exit server.
 5418: #     
 5419: #
 5420: 
 5421: sub del_id_handler {
 5422:     my ($cmd,$tail,$client) = @_;
 5423: 
 5424:     my $userinput = "$cmd:$tail";
 5425: 
 5426:     my ($udom,$what)=split(/:/,$tail);
 5427:     chomp($what);
 5428:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
 5429:                                    "D", $what);
 5430:     if ($hashref) {
 5431:         my @keys=split(/\&/,$what);
 5432:         foreach my $key (@keys) {
 5433:             delete($hashref->{$key});
 5434:         }
 5435:         if (&untie_user_hash($hashref)) {
 5436:             &Reply($client, "ok\n", $userinput);
 5437:         } else {
 5438:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5439:                     "while attempting iddel\n", $userinput);
 5440:         }
 5441:     } else {
 5442:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 5443:                  "while attempting iddel\n", $userinput);
 5444:     }
 5445:     return 1;
 5446: }
 5447: &register_handler("iddel", \&del_id_handler, 0, 1, 0);
 5448: 
 5449: #
 5450: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
 5451: #
 5452: # Parameters
 5453: #   $cmd       - Command keyword that caused us to be dispatched.
 5454: #   $tail      - Tail of the command.  Consists of a colon separated:
 5455: #               domain - the domain whose dcmail we are recording
 5456: #               email    Consists of key=value pair 
 5457: #                        where key is unique msgid
 5458: #                        and value is message (in XML)
 5459: #   $client    - Socket open on the client.
 5460: #
 5461: # Returns:
 5462: #    1 - indicating processing should continue.
 5463: # Side effects
 5464: #     reply is written to $client.
 5465: #
 5466: sub put_dcmail_handler {
 5467:     my ($cmd,$tail,$client) = @_;
 5468:     my $userinput = "$cmd:$tail";
 5469: 
 5470: 
 5471:     my ($udom,$what)=split(/:/,$tail);
 5472:     chomp($what);
 5473:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
 5474:     if ($hashref) {
 5475:         my ($key,$value)=split(/=/,$what);
 5476:         $hashref->{$key}=$value;
 5477:     }
 5478:     if (&untie_domain_hash($hashref)) {
 5479:         &Reply($client, "ok\n", $userinput);
 5480:     } else {
 5481:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5482:                  "while attempting dcmailput\n", $userinput);
 5483:     }
 5484:     return 1;
 5485: }
 5486: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
 5487: 
 5488: #
 5489: # Retrieves broadcast e-mail from nohist_dcmail database
 5490: # Returns to client an & separated list of key=value pairs,
 5491: # where key is msgid and value is message information.
 5492: #
 5493: # Parameters
 5494: #   $cmd       - Command keyword that caused us to be dispatched.
 5495: #   $tail      - Tail of the command.  Consists of a colon separated:
 5496: #               domain - the domain whose dcmail table we dump
 5497: #               startfilter - beginning of time window 
 5498: #               endfilter - end of time window
 5499: #               sendersfilter - & separated list of username:domain 
 5500: #                 for senders to search for.
 5501: #   $client    - Socket open on the client.
 5502: #
 5503: # Returns:
 5504: #    1 - indicating processing should continue.
 5505: # Side effects
 5506: #     reply (& separated list of msgid=messageinfo pairs) is 
 5507: #     written to $client.
 5508: #
 5509: sub dump_dcmail_handler {
 5510:     my ($cmd, $tail, $client) = @_;
 5511:                                                                                 
 5512:     my $userinput = "$cmd:$tail";
 5513:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
 5514:     chomp($sendersfilter);
 5515:     my @senders = ();
 5516:     if (defined($startfilter)) {
 5517:         $startfilter=&unescape($startfilter);
 5518:     } else {
 5519:         $startfilter='.';
 5520:     }
 5521:     if (defined($endfilter)) {
 5522:         $endfilter=&unescape($endfilter);
 5523:     } else {
 5524:         $endfilter='.';
 5525:     }
 5526:     if (defined($sendersfilter)) {
 5527:         $sendersfilter=&unescape($sendersfilter);
 5528: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
 5529:     }
 5530: 
 5531:     my $qresult='';
 5532:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
 5533:     if ($hashref) {
 5534:         while (my ($key,$value) = each(%$hashref)) {
 5535:             my $match = 1;
 5536:             my ($timestamp,$subj,$uname,$udom) = 
 5537: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
 5538:             $subj = &unescape($subj);
 5539:             unless ($startfilter eq '.' || !defined($startfilter)) {
 5540:                 if ($timestamp < $startfilter) {
 5541:                     $match = 0;
 5542:                 }
 5543:             }
 5544:             unless ($endfilter eq '.' || !defined($endfilter)) {
 5545:                 if ($timestamp > $endfilter) {
 5546:                     $match = 0;
 5547:                 }
 5548:             }
 5549:             unless (@senders < 1) {
 5550:                 unless (grep/^$uname:$udom$/,@senders) {
 5551:                     $match = 0;
 5552:                 }
 5553:             }
 5554:             if ($match == 1) {
 5555:                 $qresult.=$key.'='.$value.'&';
 5556:             }
 5557:         }
 5558:         if (&untie_domain_hash($hashref)) {
 5559:             chop($qresult);
 5560:             &Reply($client, \$qresult, $userinput);
 5561:         } else {
 5562:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5563:                     "while attempting dcmaildump\n", $userinput);
 5564:         }
 5565:     } else {
 5566:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 5567:                 "while attempting dcmaildump\n", $userinput);
 5568:     }
 5569:     return 1;
 5570: }
 5571: 
 5572: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
 5573: 
 5574: #
 5575: # Puts domain roles in nohist_domainroles database
 5576: #
 5577: # Parameters
 5578: #   $cmd       - Command keyword that caused us to be dispatched.
 5579: #   $tail      - Tail of the command.  Consists of a colon separated:
 5580: #               domain - the domain whose roles we are recording  
 5581: #               role -   Consists of key=value pair
 5582: #                        where key is unique role
 5583: #                        and value is start/end date information
 5584: #   $client    - Socket open on the client.
 5585: #
 5586: # Returns:
 5587: #    1 - indicating processing should continue.
 5588: # Side effects
 5589: #     reply is written to $client.
 5590: #
 5591: 
 5592: sub put_domainroles_handler {
 5593:     my ($cmd,$tail,$client) = @_;
 5594: 
 5595:     my $userinput = "$cmd:$tail";
 5596:     my ($udom,$what)=split(/:/,$tail);
 5597:     chomp($what);
 5598:     my @pairs=split(/\&/,$what);
 5599:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
 5600:     if ($hashref) {
 5601:         foreach my $pair (@pairs) {
 5602:             my ($key,$value)=split(/=/,$pair);
 5603:             $hashref->{$key}=$value;
 5604:         }
 5605:         if (&untie_domain_hash($hashref)) {
 5606:             &Reply($client, "ok\n", $userinput);
 5607:         } else {
 5608:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5609:                      "while attempting domroleput\n", $userinput);
 5610:         }
 5611:     } else {
 5612:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 5613:                   "while attempting domroleput\n", $userinput);
 5614:     }
 5615:                                                                                   
 5616:     return 1;
 5617: }
 5618: 
 5619: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
 5620: 
 5621: #
 5622: # Retrieves domain roles from nohist_domainroles database
 5623: # Returns to client an & separated list of key=value pairs,
 5624: # where key is role and value is start and end date information.
 5625: #
 5626: # Parameters
 5627: #   $cmd       - Command keyword that caused us to be dispatched.
 5628: #   $tail      - Tail of the command.  Consists of a colon separated:
 5629: #               domain - the domain whose domain roles table we dump
 5630: #   $client    - Socket open on the client.
 5631: #
 5632: # Returns:
 5633: #    1 - indicating processing should continue.
 5634: # Side effects
 5635: #     reply (& separated list of role=start/end info pairs) is
 5636: #     written to $client.
 5637: #
 5638: sub dump_domainroles_handler {
 5639:     my ($cmd, $tail, $client) = @_;
 5640:                                                                                            
 5641:     my $userinput = "$cmd:$tail";
 5642:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
 5643:     chomp($rolesfilter);
 5644:     my @roles = ();
 5645:     if (defined($startfilter)) {
 5646:         $startfilter=&unescape($startfilter);
 5647:     } else {
 5648:         $startfilter='.';
 5649:     }
 5650:     if (defined($endfilter)) {
 5651:         $endfilter=&unescape($endfilter);
 5652:     } else {
 5653:         $endfilter='.';
 5654:     }
 5655:     if (defined($rolesfilter)) {
 5656:         $rolesfilter=&unescape($rolesfilter);
 5657: 	@roles = split(/\&/,$rolesfilter);
 5658:     }
 5659: 
 5660:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
 5661:     if ($hashref) {
 5662:         my $qresult = '';
 5663:         while (my ($key,$value) = each(%$hashref)) {
 5664:             my $match = 1;
 5665:             my ($end,$start) = split(/:/,&unescape($value));
 5666:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
 5667:             unless (@roles < 1) {
 5668:                 unless (grep/^\Q$trole\E$/,@roles) {
 5669:                     $match = 0;
 5670:                     next;
 5671:                 }
 5672:             }
 5673:             unless ($startfilter eq '.' || !defined($startfilter)) {
 5674:                 if ((defined($start)) && ($start >= $startfilter)) {
 5675:                     $match = 0;
 5676:                     next;
 5677:                 }
 5678:             }
 5679:             unless ($endfilter eq '.' || !defined($endfilter)) {
 5680:                 if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
 5681:                     $match = 0;
 5682:                     next;
 5683:                 }
 5684:             }
 5685:             if ($match == 1) {
 5686:                 $qresult.=$key.'='.$value.'&';
 5687:             }
 5688:         }
 5689:         if (&untie_domain_hash($hashref)) {
 5690:             chop($qresult);
 5691:             &Reply($client, \$qresult, $userinput);
 5692:         } else {
 5693:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5694:                     "while attempting domrolesdump\n", $userinput);
 5695:         }
 5696:     } else {
 5697:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 5698:                 "while attempting domrolesdump\n", $userinput);
 5699:     }
 5700:     return 1;
 5701: }
 5702: 
 5703: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
 5704: 
 5705: 
 5706: #  Process the tmpput command I'm not sure what this does.. Seems to
 5707: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
 5708: # where Id is the client's ip concatenated with a sequence number.
 5709: # The file will contain some value that is passed in.  Is this e.g.
 5710: # a login token?
 5711: #
 5712: # Parameters:
 5713: #    $cmd     - The command that got us dispatched.
 5714: #    $tail    - The remainder of the request following $cmd:
 5715: #               In this case this will be the contents of the file.
 5716: #    $client  - Socket connected to the client.
 5717: # Returns:
 5718: #    1 indicating processing can continue.
 5719: # Side effects:
 5720: #   A file is created in the local filesystem.
 5721: #   A reply is sent to the client.
 5722: sub tmp_put_handler {
 5723:     my ($cmd, $what, $client) = @_;
 5724: 
 5725:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
 5726: 
 5727:     my ($record,$context) = split(/:/,$what);
 5728:     if ($context ne '') {
 5729:         chomp($context);
 5730:         $context = &unescape($context);
 5731:     }
 5732:     my ($id,$store);
 5733:     $tmpsnum++;
 5734:     my $numtries = 0;
 5735:     my $execdir=$perlvar{'lonDaemons'};
 5736:     if (($context eq 'resetpw') || ($context eq 'createaccount') ||
 5737:         ($context eq 'sso') || ($context eq 'link') || ($context eq 'retry')) {
 5738:         $id = &md5_hex(&md5_hex(time.{}.rand().$$.$tmpsnum));
 5739:         while ((-e "$execdir/tmp/$id.tmp") && ($numtries <10)) {
 5740:             undef($id);
 5741:             $id = &md5_hex(&md5_hex(time.{}.rand().$$.$tmpsnum));
 5742:             $numtries ++;
 5743:         }
 5744:     } else {
 5745:         $id = $$.'_'.$clientip.'_'.$tmpsnum;
 5746:     }
 5747:     $id=~s/\W/\_/g;
 5748:     $record=~s/\n//g;
 5749:     if (($id ne '') &&
 5750:         ($store=IO::File->new(">$execdir/tmp/$id.tmp"))) {
 5751: 	print $store $record;
 5752: 	close $store;
 5753: 	&Reply($client, \$id, $userinput);
 5754:     } else {
 5755: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
 5756: 		  "while attempting tmpput\n", $userinput);
 5757:     }
 5758:     return 1;
 5759:   
 5760: }
 5761: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
 5762: 
 5763: #   Processes the tmpget command.  This command returns the contents
 5764: #  of a temporary resource file(?) created via tmpput.
 5765: #
 5766: # Paramters:
 5767: #    $cmd      - Command that got us dispatched.
 5768: #    $id       - Tail of the command, contain the id of the resource
 5769: #                we want to fetch.
 5770: #    $client   - socket open on the client.
 5771: # Return:
 5772: #    1         - Inidcating processing can continue.
 5773: # Side effects:
 5774: #   A reply is sent to the client.
 5775: #
 5776: sub tmp_get_handler {
 5777:     my ($cmd, $id, $client) = @_;
 5778: 
 5779:     my $userinput = "$cmd:$id"; 
 5780:     
 5781: 
 5782:     $id=~s/\W/\_/g;
 5783:     my $store;
 5784:     my $execdir=$perlvar{'lonDaemons'};
 5785:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
 5786: 	my $reply=<$store>;
 5787: 	&Reply( $client, \$reply, $userinput);
 5788: 	close $store;
 5789:     } else {
 5790: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
 5791: 		  "while attempting tmpget\n", $userinput);
 5792:     }
 5793: 
 5794:     return 1;
 5795: }
 5796: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
 5797: 
 5798: #
 5799: #  Process the tmpdel command.  This command deletes a temp resource
 5800: #  created by the tmpput command.
 5801: #
 5802: # Parameters:
 5803: #   $cmd      - Command that got us here.
 5804: #   $id       - Id of the temporary resource created.
 5805: #   $client   - socket open on the client process.
 5806: #
 5807: # Returns:
 5808: #   1     - Indicating processing should continue.
 5809: # Side Effects:
 5810: #   A file is deleted
 5811: #   A reply is sent to the client.
 5812: sub tmp_del_handler {
 5813:     my ($cmd, $id, $client) = @_;
 5814:     
 5815:     my $userinput= "$cmd:$id";
 5816:     
 5817:     chomp($id);
 5818:     $id=~s/\W/\_/g;
 5819:     my $execdir=$perlvar{'lonDaemons'};
 5820:     if (unlink("$execdir/tmp/$id.tmp")) {
 5821: 	&Reply($client, "ok\n", $userinput);
 5822:     } else {
 5823: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
 5824: 		  "while attempting tmpdel\n", $userinput);
 5825:     }
 5826:     
 5827:     return 1;
 5828: 
 5829: }
 5830: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
 5831: 
 5832: #
 5833: #  Process the updatebalcookie command.  This command updates a
 5834: #  cookie in the lonBalancedir directory on a load balancer node.
 5835: #
 5836: # Parameters:
 5837: #   $cmd      - Command that got us here.
 5838: #   $tail     - Tail of the request (escaped cookie: escaped current entry)
 5839: #
 5840: #   $client   - socket open on the client process.
 5841: #
 5842: # Returns:
 5843: #   1     - Indicating processing should continue.
 5844: # Side Effects:
 5845: #   A cookie file is updated from the lonBalancedir directory
 5846: #   A reply is sent to the client.
 5847: #
 5848: sub update_balcookie_handler {
 5849:     my ($cmd, $tail, $client) = @_;
 5850: 
 5851:     my $userinput= "$cmd:$tail";
 5852:     chomp($tail);
 5853:     my ($cookie,$lastentry) = map { &unescape($_) } (split(/:/,$tail));
 5854: 
 5855:     my $updatedone;
 5856:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
 5857:         my $execdir=$perlvar{'lonBalanceDir'};
 5858:         if (-e "$execdir/$cookie.id") {
 5859:             my $doupdate;
 5860:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
 5861:                 while (my $line = <$fh>) {
 5862:                     chomp($line);
 5863:                     if ($line eq $lastentry) {
 5864:                         $doupdate = 1;
 5865:                         last;
 5866:                     }
 5867:                 }
 5868:                 close($fh);
 5869:             }
 5870:             if ($doupdate) {
 5871:                 if (open(my $fh,'>',"$execdir/$cookie.id")) {
 5872:                     print $fh $clientname;
 5873:                     close($fh);
 5874:                     $updatedone = 1;
 5875:                 }
 5876:             }
 5877:         }
 5878:     }
 5879:     if ($updatedone) {
 5880:         &Reply($client, "ok\n", $userinput);
 5881:     } else {
 5882:         &Failure( $client, "error: ".($!+0)."file update failed ".
 5883:                   "while attempting updatebalcookie\n", $userinput);
 5884:     }
 5885:     return 1;
 5886: }
 5887: &register_handler("updatebalcookie", \&update_balcookie_handler, 0, 1, 0);
 5888: 
 5889: #
 5890: #  Process the delbalcookie command. This command deletes a balancer
 5891: #  cookie in the lonBalancedir directory on a load balancer node.
 5892: #
 5893: # Parameters:
 5894: #   $cmd      - Command that got us here.
 5895: #   $cookie   - Cookie to be deleted.
 5896: #   $client   - socket open on the client process.
 5897: #
 5898: # Returns:
 5899: #   1     - Indicating processing should continue.
 5900: # Side Effects:
 5901: #   A cookie file is deleted from the lonBalancedir directory
 5902: #   A reply is sent to the client.
 5903: sub del_balcookie_handler {
 5904:     my ($cmd, $cookie, $client) = @_;
 5905: 
 5906:     my $userinput= "$cmd:$cookie";
 5907: 
 5908:     chomp($cookie);
 5909:     $cookie = &unescape($cookie);
 5910:     my $deleted = '';
 5911:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
 5912:         my $execdir=$perlvar{'lonBalanceDir'};
 5913:         if (-e "$execdir/$cookie.id") {
 5914:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
 5915:                 my $dodelete;
 5916:                 while (my $line = <$fh>) {
 5917:                     chomp($line);
 5918:                     if ($line eq $clientname) {
 5919:                         $dodelete = 1;
 5920:                         last;
 5921:                     }
 5922:                 }
 5923:                 close($fh);
 5924:                 if ($dodelete) {
 5925:                     if (unlink("$execdir/$cookie.id")) {
 5926:                         $deleted = 1;
 5927:                     }
 5928:                 }
 5929:             }
 5930:         }
 5931:     }
 5932:     if ($deleted) {
 5933:         &Reply($client, "ok\n", $userinput);
 5934:     } else {
 5935:         &Failure( $client, "error: ".($!+0)."Unlinking cookie file Failed ".
 5936:                   "while attempting delbalcookie\n", $userinput);
 5937:     }
 5938:     return 1;
 5939: }
 5940: &register_handler("delbalcookie", \&del_balcookie_handler, 0, 1, 0);
 5941: 
 5942: #
 5943: #   Processes the setannounce command.  This command
 5944: #   creates a file named announce.txt in the top directory of
 5945: #   the documentn root and sets its contents.  The announce.txt file is
 5946: #   printed in its entirety at the LonCAPA login page.  Note:
 5947: #   once the announcement.txt fileis created it cannot be deleted.
 5948: #   However, setting the contents of the file to empty removes the
 5949: #   announcement from the login page of loncapa so who cares.
 5950: #
 5951: # Parameters:
 5952: #    $cmd          - The command that got us dispatched.
 5953: #    $announcement - The text of the announcement.
 5954: #    $client       - Socket open on the client process.
 5955: # Retunrns:
 5956: #   1             - Indicating request processing should continue
 5957: # Side Effects:
 5958: #   The file {DocRoot}/announcement.txt is created.
 5959: #   A reply is sent to $client.
 5960: #
 5961: sub set_announce_handler {
 5962:     my ($cmd, $announcement, $client) = @_;
 5963:   
 5964:     my $userinput    = "$cmd:$announcement";
 5965: 
 5966:     chomp($announcement);
 5967:     $announcement=&unescape($announcement);
 5968:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
 5969: 				'/announcement.txt')) {
 5970: 	print $store $announcement;
 5971: 	close $store;
 5972: 	&Reply($client, "ok\n", $userinput);
 5973:     } else {
 5974: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
 5975:     }
 5976: 
 5977:     return 1;
 5978: }
 5979: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
 5980: 
 5981: #
 5982: #  Return the version of the daemon.  This can be used to determine
 5983: #  the compatibility of cross version installations or, alternatively to
 5984: #  simply know who's out of date and who isn't.  Note that the version
 5985: #  is returned concatenated with the tail.
 5986: # Parameters:
 5987: #   $cmd        - the request that dispatched to us.
 5988: #   $tail       - Tail of the request (client's version?).
 5989: #   $client     - Socket open on the client.
 5990: #Returns:
 5991: #   1 - continue processing requests.
 5992: # Side Effects:
 5993: #   Replies with version to $client.
 5994: sub get_version_handler {
 5995:     my ($cmd, $tail, $client) = @_;
 5996: 
 5997:     my $userinput  = $cmd.$tail;
 5998:     
 5999:     &Reply($client, &version($userinput)."\n", $userinput);
 6000: 
 6001: 
 6002:     return 1;
 6003: }
 6004: &register_handler("version", \&get_version_handler, 0, 1, 0);
 6005: 
 6006: #  Set the current host and domain.  This is used to support
 6007: #  multihomed systems.  Each IP of the system, or even separate daemons
 6008: #  on the same IP can be treated as handling a separate lonCAPA virtual
 6009: #  machine.  This command selects the virtual lonCAPA.  The client always
 6010: #  knows the right one since it is lonc and it is selecting the domain/system
 6011: #  from the hosts.tab file.
 6012: # Parameters:
 6013: #    $cmd      - Command that dispatched us.
 6014: #    $tail     - Tail of the command (domain/host requested).
 6015: #    $socket   - Socket open on the client.
 6016: #
 6017: # Returns:
 6018: #     1   - Indicates the program should continue to process requests.
 6019: # Side-effects:
 6020: #     The default domain/system context is modified for this daemon.
 6021: #     a reply is sent to the client.
 6022: #
 6023: sub set_virtual_host_handler {
 6024:     my ($cmd, $tail, $socket) = @_;
 6025:   
 6026:     my $userinput  ="$cmd:$tail";
 6027: 
 6028:     &Reply($client, &sethost($userinput)."\n", $userinput);
 6029: 
 6030: 
 6031:     return 1;
 6032: }
 6033: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
 6034: 
 6035: #  Process a request to exit:
 6036: #   - "bye" is sent to the client.
 6037: #   - The client socket is shutdown and closed.
 6038: #   - We indicate to the caller that we should exit.
 6039: # Formal Parameters:
 6040: #   $cmd                - The command that got us here.
 6041: #   $tail               - Tail of the command (empty).
 6042: #   $client             - Socket open on the tail.
 6043: # Returns:
 6044: #   0      - Indicating the program should exit!!
 6045: #
 6046: sub exit_handler {
 6047:     my ($cmd, $tail, $client) = @_;
 6048: 
 6049:     my $userinput = "$cmd:$tail";
 6050: 
 6051:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
 6052:     &Reply($client, "bye\n", $userinput);
 6053:     $client->shutdown(2);        # shutdown the socket forcibly.
 6054:     $client->close();
 6055: 
 6056:     return 0;
 6057: }
 6058: &register_handler("exit", \&exit_handler, 0,1,1);
 6059: &register_handler("init", \&exit_handler, 0,1,1);
 6060: &register_handler("quit", \&exit_handler, 0,1,1);
 6061: 
 6062: #  Determine if auto-enrollment is enabled.
 6063: #  Note that the original had what I believe to be a defect.
 6064: #  The original returned 0 if the requestor was not a registerd client.
 6065: #  It should return "refused".
 6066: # Formal Parameters:
 6067: #   $cmd       - The command that invoked us.
 6068: #   $tail      - The tail of the command (Extra command parameters.
 6069: #   $client    - The socket open on the client that issued the request.
 6070: # Returns:
 6071: #    1         - Indicating processing should continue.
 6072: #
 6073: sub enrollment_enabled_handler {
 6074:     my ($cmd, $tail, $client) = @_;
 6075:     my $userinput = $cmd.":".$tail; # For logging purposes.
 6076: 
 6077:     
 6078:     my ($cdom) = split(/:/, $tail, 2);   # Domain we're asking about.
 6079: 
 6080:     my $outcome  = &localenroll::run($cdom);
 6081:     &Reply($client, \$outcome, $userinput);
 6082: 
 6083:     return 1;
 6084: }
 6085: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
 6086: 
 6087: #
 6088: #   Validate an institutional code used for a LON-CAPA course.          
 6089: #
 6090: # Formal Parameters:
 6091: #   $cmd          - The command request that got us dispatched.
 6092: #   $tail         - The tail of the command.  In this case,
 6093: #                   this is a colon separated set of words that will be split
 6094: #                   into:
 6095: #                        $dom      - The domain for which the check of 
 6096: #                                    institutional course code will occur.
 6097: #
 6098: #                        $instcode - The institutional code for the course
 6099: #                                    being requested, or validated for rights
 6100: #                                    to request.
 6101: #
 6102: #                        $owner    - The course requestor (who will be the
 6103: #                                    course owner, in the form username:domain
 6104: #
 6105: #   $client       - Socket open on the client.
 6106: # Returns:
 6107: #    1           - Indicating processing should continue.
 6108: #
 6109: sub validate_instcode_handler {
 6110:     my ($cmd, $tail, $client) = @_;
 6111:     my $userinput = "$cmd:$tail";
 6112:     my ($dom,$instcode,$owner) = split(/:/, $tail);
 6113:     $instcode = &unescape($instcode);
 6114:     $owner = &unescape($owner);
 6115:     my ($outcome,$description,$credits) = 
 6116:         &localenroll::validate_instcode($dom,$instcode,$owner);
 6117:     my $result = &escape($outcome).'&'.&escape($description).'&'.
 6118:                  &escape($credits);
 6119:     &Reply($client, \$result, $userinput);
 6120: 
 6121:     return 1;
 6122: }
 6123: &register_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
 6124: 
 6125: #
 6126: #  Validate co-owner for cross-listed institutional code and
 6127: #  institutional course code itself used for a LON-CAPA course.
 6128: #
 6129: # Formal Parameters:
 6130: #   $cmd          - The command request that got us dispatched.
 6131: #   $tail         - The tail of the command.  In this case,
 6132: #                   this is a colon separated string containing:
 6133: #      $dom            - Course's LON-CAPA domain
 6134: #      $instcode       - Institutional course code for the course
 6135: #      $inst_xlist     - Institutional course Id for the crosslisting
 6136: #      $coowner        - Username of co-owner
 6137: #      (values for all but $dom have been escaped). 
 6138: #
 6139: #   $client       - Socket open on the client.
 6140: # Returns:
 6141: #    1           - Indicating processing should continue.
 6142: #
 6143: sub validate_instcrosslist_handler  {
 6144:     my ($cmd, $tail, $client) = @_;
 6145:     my $userinput = "$cmd:$tail";
 6146:     my ($dom,$instcode,$inst_xlist,$coowner) = split(/:/,$tail);
 6147:     $instcode = &unescape($instcode);
 6148:     $inst_xlist = &unescape($inst_xlist);
 6149:     $coowner = &unescape($coowner);
 6150:     my $outcome = &localenroll::validate_crosslist_access($dom,$instcode,
 6151:                                                           $inst_xlist,$coowner);
 6152:     &Reply($client, \$outcome, $userinput);
 6153: 
 6154:     return 1;
 6155: }
 6156: &register_handler("autovalidateinstcrosslist", \&validate_instcrosslist_handler, 0, 1, 0);
 6157: 
 6158: #   Get the official sections for which auto-enrollment is possible.
 6159: #   Since the admin people won't know about 'unofficial sections' 
 6160: #   we cannot auto-enroll on them.
 6161: # Formal Parameters:
 6162: #    $cmd     - The command request that got us dispatched here.
 6163: #    $tail    - The remainder of the request.  In our case this
 6164: #               will be split into:
 6165: #               $coursecode   - The course name from the admin point of view.
 6166: #               $cdom         - The course's domain(?).
 6167: #    $client  - Socket open on the client.
 6168: # Returns:
 6169: #    1    - Indiciting processing should continue.
 6170: #
 6171: sub get_sections_handler {
 6172:     my ($cmd, $tail, $client) = @_;
 6173:     my $userinput = "$cmd:$tail";
 6174: 
 6175:     my ($coursecode, $cdom) = split(/:/, $tail);
 6176:     my @secs = &localenroll::get_sections($coursecode,$cdom);
 6177:     my $seclist = &escape(join(':',@secs));
 6178: 
 6179:     &Reply($client, \$seclist, $userinput);
 6180:     
 6181: 
 6182:     return 1;
 6183: }
 6184: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
 6185: 
 6186: #   Validate the owner of a new course section.  
 6187: #
 6188: # Formal Parameters:
 6189: #   $cmd      - Command that got us dispatched.
 6190: #   $tail     - the remainder of the command.  For us this consists of a
 6191: #               colon separated string containing:
 6192: #                  $inst    - Course Id from the institutions point of view.
 6193: #                  $owner   - Proposed owner of the course.
 6194: #                  $cdom    - Domain of the course (from the institutions
 6195: #                             point of view?)..
 6196: #   $client   - Socket open on the client.
 6197: #
 6198: # Returns:
 6199: #   1        - Processing should continue.
 6200: #
 6201: sub validate_course_owner_handler {
 6202:     my ($cmd, $tail, $client)  = @_;
 6203:     my $userinput = "$cmd:$tail";
 6204:     my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
 6205:     
 6206:     $owner = &unescape($owner);
 6207:     $coowners = &unescape($coowners);
 6208:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
 6209:     &Reply($client, \$outcome, $userinput);
 6210: 
 6211: 
 6212: 
 6213:     return 1;
 6214: }
 6215: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
 6216: 
 6217: #
 6218: #   Validate a course section in the official schedule of classes
 6219: #   from the institutions point of view (part of autoenrollment).
 6220: #
 6221: # Formal Parameters:
 6222: #   $cmd          - The command request that got us dispatched.
 6223: #   $tail         - The tail of the command.  In this case,
 6224: #                   this is a colon separated set of words that will be split
 6225: #                   into:
 6226: #                        $inst_course_id - The course/section id from the
 6227: #                                          institutions point of view.
 6228: #                        $cdom           - The domain from the institutions
 6229: #                                          point of view.
 6230: #   $client       - Socket open on the client.
 6231: # Returns:
 6232: #    1           - Indicating processing should continue.
 6233: #
 6234: sub validate_course_section_handler {
 6235:     my ($cmd, $tail, $client) = @_;
 6236:     my $userinput = "$cmd:$tail";
 6237:     my ($inst_course_id, $cdom) = split(/:/, $tail);
 6238: 
 6239:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
 6240:     &Reply($client, \$outcome, $userinput);
 6241: 
 6242: 
 6243:     return 1;
 6244: }
 6245: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
 6246: 
 6247: #
 6248: #   Validate course owner's access to enrollment data for specific class section. 
 6249: #   
 6250: #
 6251: # Formal Parameters:
 6252: #    $cmd     - The command request that got us dispatched.
 6253: #    $tail    - The tail of the command.   In this case this is a colon separated
 6254: #               set of values that will be split into:
 6255: #               $inst_class  - Institutional code for the specific class section   
 6256: #               $ownerlist   - An escaped comma-separated list of username:domain 
 6257: #                              of the course owner, and co-owner(s).
 6258: #               $cdom        - The domain of the course from the institution's
 6259: #                              point of view.
 6260: #    $client  - The socket open on the client.
 6261: # Returns:
 6262: #    1 - continue processing.
 6263: #
 6264: 
 6265: sub validate_class_access_handler {
 6266:     my ($cmd, $tail, $client) = @_;
 6267:     my $userinput = "$cmd:$tail";
 6268:     my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
 6269:     my $owners = &unescape($ownerlist);
 6270:     my $outcome;
 6271:     eval {
 6272: 	local($SIG{__DIE__})='DEFAULT';
 6273: 	$outcome=&localenroll::check_section($inst_class,$owners,$cdom);
 6274:     };
 6275:     &Reply($client,\$outcome, $userinput);
 6276: 
 6277:     return 1;
 6278: }
 6279: &register_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
 6280: 
 6281: #
 6282: #    Modify institutional sections (using customized &instsec_reformat()
 6283: #    routine in localenroll.pm), to either clutter or declutter, for  
 6284: #    purposes of ensuring an institutional course section (string) can
 6285: #    be unambiguously separated into institutional course and section.
 6286: #
 6287: # Formal Parameters:
 6288: #    $cmd     - The command request that got us dispatched.
 6289: #    $tail    - The tail of the command.   In this case this is a colon separated
 6290: #               set of values that will be split into:
 6291: #               $cdom        - The LON-CAPA domain of the course.
 6292: #               $action      - Either: clutter or declutter
 6293: #                              clutter adds character(s) to eliminate ambiguity
 6294: #                              declutter removes the added characters (e.g., for
 6295: #                              display of the institutional course section string.
 6296: #               $info        - A frozen hash in which keys are: 
 6297: #                              LON-CAPA course number:Institutional course code
 6298: #                              and values are a reference to an array of the
 6299: #                              items to modify -- either institutional sections,
 6300: #                              or institutional course sections (for crosslistings). 
 6301: #    $client  - The socket open on the client.
 6302: # Returns:
 6303: #    1 - continue processing.
 6304: #   
 6305: 
 6306: sub instsec_reformat_handler {
 6307:     my ($cmd, $tail, $client) = @_;
 6308:     my $userinput = "$cmd:$tail";
 6309:     my ($cdom,$action,$info) = split(/:/,$tail);
 6310:     my $instsecref = &Apache::lonnet::thaw_unescape($info);
 6311:     my ($outcome,$result);
 6312:     eval {
 6313:         local($SIG{__DIE__})='DEFAULT';
 6314:         $outcome=&localenroll::instsec_reformat($cdom,$action,$instsecref);
 6315:         if ($outcome eq 'ok') {
 6316:             if (ref($instsecref) eq 'HASH') {
 6317:                 foreach my $key (keys(%{$instsecref})) {
 6318:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($instsecref->{$key}).'&';
 6319:                 }
 6320:                 $result =~ s/\&$//;
 6321:             }
 6322:         }
 6323:     };
 6324:     if (!$@) {
 6325:         if ($outcome eq 'ok') {
 6326:             &Reply( $client, \$result, $userinput);
 6327:         } else {
 6328:             &Reply($client,\$outcome, $userinput);
 6329:         }
 6330:     } else {
 6331:         &Failure($client,"unknown_cmd\n",$userinput);
 6332:     }
 6333:     return 1;
 6334: }
 6335: &register_handler("autoinstsecreformat",\&instsec_reformat_handler, 0, 1, 0);
 6336: 
 6337: #
 6338: #   Validate course owner or co-owners(s) access to enrollment data for all sections
 6339: #   and crosslistings for a particular course.
 6340: #
 6341: #
 6342: # Formal Parameters:
 6343: #    $cmd     - The command request that got us dispatched.
 6344: #    $tail    - The tail of the command.   In this case this is a colon separated
 6345: #               set of values that will be split into:
 6346: #               $ownerlist   - An escaped comma-separated list of username:domain
 6347: #                              of the course owner, and co-owner(s).
 6348: #               $cdom        - The domain of the course from the institution's
 6349: #                              point of view.
 6350: #               $classes     - Frozen hash of institutional course sections and
 6351: #                              crosslistings.
 6352: #    $client  - The socket open on the client.
 6353: # Returns:
 6354: #    1 - continue processing.
 6355: #
 6356: 
 6357: sub validate_classes_handler {
 6358:     my ($cmd, $tail, $client) = @_;
 6359:     my $userinput = "$cmd:$tail";
 6360:     my ($ownerlist,$cdom,$classes) = split(/:/, $tail);
 6361:     my $classesref = &Apache::lonnet::thaw_unescape($classes);
 6362:     my $owners = &unescape($ownerlist);
 6363:     my $result;
 6364:     eval {
 6365:         local($SIG{__DIE__})='DEFAULT';
 6366:         my %validations;
 6367:         my $response = &localenroll::check_instclasses($owners,$cdom,$classesref,
 6368:                                                        \%validations);
 6369:         if ($response eq 'ok') {
 6370:             foreach my $key (keys(%validations)) {
 6371:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
 6372:             }
 6373:             $result =~ s/\&$//;
 6374:         } else {
 6375:             $result = 'error';
 6376:         }
 6377:     };
 6378:     if (!$@) {
 6379:         &Reply($client, \$result, $userinput);
 6380:     } else {
 6381:         &Failure($client,"unknown_cmd\n",$userinput);
 6382:     }
 6383:     return 1;
 6384: }
 6385: &register_handler("autovalidateinstclasses", \&validate_classes_handler, 0, 1, 0);
 6386: 
 6387: #
 6388: #   Create a password for a new LON-CAPA user added by auto-enrollment.
 6389: #   Only used for case where authentication method for new user is localauth
 6390: #
 6391: # Formal Parameters:
 6392: #    $cmd     - The command request that got us dispatched.
 6393: #    $tail    - The tail of the command.   In this case this is a colon separated
 6394: #               set of words that will be split into:
 6395: #               $authparam - An authentication parameter (localauth parameter).
 6396: #               $cdom      - The domain of the course from the institution's
 6397: #                            point of view.
 6398: #    $client  - The socket open on the client.
 6399: # Returns:
 6400: #    1 - continue processing.
 6401: #
 6402: sub create_auto_enroll_password_handler {
 6403:     my ($cmd, $tail, $client) = @_;
 6404:     my $userinput = "$cmd:$tail";
 6405: 
 6406:     my ($authparam, $cdom) = split(/:/, $userinput);
 6407: 
 6408:     my ($create_passwd,$authchk);
 6409:     ($authparam,
 6410:      $create_passwd,
 6411:      $authchk) = &localenroll::create_password($authparam,$cdom);
 6412: 
 6413:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
 6414: 	   $userinput);
 6415: 
 6416: 
 6417:     return 1;
 6418: }
 6419: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
 6420: 		  0, 1, 0);
 6421: 
 6422: sub auto_export_grades_handler {
 6423:     my ($cmd, $tail, $client) = @_;
 6424:     my $userinput = "$cmd:$tail";
 6425:     my ($cdom,$cnum,$info,$data) = split(/:/,$tail);
 6426:     my $inforef = &Apache::lonnet::thaw_unescape($info);
 6427:     my $dataref = &Apache::lonnet::thaw_unescape($data);
 6428:     my ($outcome,$result);;
 6429:     eval {
 6430:         local($SIG{__DIE__})='DEFAULT';
 6431:         my %rtnhash;
 6432:         $outcome=&localenroll::export_grades($cdom,$cnum,$inforef,$dataref,\%rtnhash);
 6433:         if ($outcome eq 'ok') {
 6434:             foreach my $key (keys(%rtnhash)) {
 6435:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
 6436:             }
 6437:             $result =~ s/\&$//;
 6438:         }
 6439:     };
 6440:     if (!$@) {
 6441:         if ($outcome eq 'ok') {
 6442:             if ($cipher) {
 6443:                 my $cmdlength=length($result);
 6444:                 $result.="         ";
 6445:                 my $encresult='';
 6446:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 6447:                     $encresult.= unpack("H16",
 6448:                                         $cipher->encrypt(substr($result,
 6449:                                                                 $encidx,
 6450:                                                                 8)));
 6451:                 }
 6452:                 &Reply( $client, "enc:$cmdlength:$encresult\n", $userinput);
 6453:             } else {
 6454:                 &Failure( $client, "error:no_key\n", $userinput);
 6455:             }
 6456:         } else {
 6457:             &Reply($client, "$outcome\n", $userinput);
 6458:         }
 6459:     } else {
 6460:         &Failure($client,"export_error\n",$userinput);
 6461:     }
 6462:     return 1;
 6463: }
 6464: &register_handler("autoexportgrades", \&auto_export_grades_handler,
 6465:                   1, 1, 0);
 6466: 
 6467: #   Retrieve and remove temporary files created by/during autoenrollment.
 6468: #
 6469: # Formal Parameters:
 6470: #    $cmd      - The command that got us dispatched.
 6471: #    $tail     - The tail of the command.  In our case this is a colon 
 6472: #                separated list that will be split into:
 6473: #                $filename - The name of the file to retrieve.
 6474: #                            The filename is given as a path relative to
 6475: #                            the LonCAPA temp file directory.
 6476: #    $client   - Socket open on the client.
 6477: #
 6478: # Returns:
 6479: #   1     - Continue processing.
 6480: sub retrieve_auto_file_handler {
 6481:     my ($cmd, $tail, $client)    = @_;
 6482:     my $userinput                = "cmd:$tail";
 6483: 
 6484:     my ($filename)   = split(/:/, $tail);
 6485: 
 6486:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
 6487: 
 6488:     if ($filename =~m{/\.\./}) {
 6489:         &Failure($client, "refused\n", $userinput);
 6490:     } elsif ($filename !~ /^$LONCAPA::match_domain\_$LONCAPA::match_courseid\_.+_classlist\.xml$/) {
 6491:         &Failure($client, "refused\n", $userinput);
 6492:     } elsif ( (-e $source) && ($filename ne '') ) {
 6493: 	my $reply = '';
 6494: 	if (open(my $fh,$source)) {
 6495: 	    while (<$fh>) {
 6496: 		chomp($_);
 6497: 		$_ =~ s/^\s+//g;
 6498: 		$_ =~ s/\s+$//g;
 6499: 		$reply .= $_;
 6500: 	    }
 6501: 	    close($fh);
 6502: 	    &Reply($client, &escape($reply)."\n", $userinput);
 6503: 
 6504: #   Does this have to be uncommented??!?  (RF).
 6505: #
 6506: #                                unlink($source);
 6507: 	} else {
 6508: 	    &Failure($client, "error\n", $userinput);
 6509: 	}
 6510:     } else {
 6511: 	&Failure($client, "error\n", $userinput);
 6512:     }
 6513:     
 6514: 
 6515:     return 1;
 6516: }
 6517: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
 6518: 
 6519: sub crsreq_checks_handler {
 6520:     my ($cmd, $tail, $client) = @_;
 6521:     my $userinput = "$cmd:$tail";
 6522:     my $dom = $tail;
 6523:     my $result;
 6524:     my @reqtypes = ('official','unofficial','community','textbook','placement');
 6525:     eval {
 6526:         local($SIG{__DIE__})='DEFAULT';
 6527:         my %validations;
 6528:         my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
 6529:                                                    \%validations);
 6530:         if ($response eq 'ok') { 
 6531:             foreach my $key (keys(%validations)) {
 6532:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
 6533:             }
 6534:             $result =~ s/\&$//;
 6535:         } else {
 6536:             $result = 'error';
 6537:         }
 6538:     };
 6539:     if (!$@) {
 6540:         &Reply($client, \$result, $userinput);
 6541:     } else {
 6542:         &Failure($client,"unknown_cmd\n",$userinput);
 6543:     }
 6544:     return 1;
 6545: }
 6546: &register_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
 6547: 
 6548: sub validate_crsreq_handler {
 6549:     my ($cmd, $tail, $client) = @_;
 6550:     my $userinput = "$cmd:$tail";
 6551:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
 6552:     $instcode = &unescape($instcode);
 6553:     $owner = &unescape($owner);
 6554:     $crstype = &unescape($crstype);
 6555:     $inststatuslist = &unescape($inststatuslist);
 6556:     $instcode = &unescape($instcode);
 6557:     $instseclist = &unescape($instseclist);
 6558:     my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
 6559:     my $outcome;
 6560:     eval {
 6561:         local($SIG{__DIE__})='DEFAULT';
 6562:         $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
 6563:                                                  $inststatuslist,$instcode,
 6564:                                                  $instseclist,$custominfo);
 6565:     };
 6566:     if (!$@) {
 6567:         &Reply($client, \$outcome, $userinput);
 6568:     } else {
 6569:         &Failure($client,"unknown_cmd\n",$userinput);
 6570:     }
 6571:     return 1;
 6572: }
 6573: &register_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
 6574: 
 6575: sub crsreq_update_handler {
 6576:     my ($cmd, $tail, $client) = @_;
 6577:     my $userinput = "$cmd:$tail";
 6578:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
 6579:         $accessstart,$accessend,$infohashref) =
 6580:         split(/:/, $tail);
 6581:     $crstype = &unescape($crstype);
 6582:     $action = &unescape($action);
 6583:     $ownername = &unescape($ownername);
 6584:     $ownerdomain = &unescape($ownerdomain);
 6585:     $fullname = &unescape($fullname);
 6586:     $title = &unescape($title);
 6587:     $code = &unescape($code);
 6588:     $accessstart = &unescape($accessstart);
 6589:     $accessend = &unescape($accessend);
 6590:     my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
 6591:     my ($result,$outcome);
 6592:     eval {
 6593:         local($SIG{__DIE__})='DEFAULT';
 6594:         my %rtnhash;
 6595:         $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
 6596:                                                 $ownername,$ownerdomain,$fullname,
 6597:                                                 $title,$code,$accessstart,$accessend,
 6598:                                                 $incoming,\%rtnhash);
 6599:         if ($outcome eq 'ok') {
 6600:             my @posskeys = qw(createdweb createdmsg createdcustomized createdactions queuedweb queuedmsg formitems reviewweb validationjs onload javascript);
 6601:             foreach my $key (keys(%rtnhash)) {
 6602:                 if (grep(/^\Q$key\E/,@posskeys)) {
 6603:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
 6604:                 }
 6605:             }
 6606:             $result =~ s/\&$//;
 6607:         }
 6608:     };
 6609:     if (!$@) {
 6610:         if ($outcome eq 'ok') {
 6611:             &Reply($client, \$result, $userinput);
 6612:         } else {
 6613:             &Reply($client, "format_error\n", $userinput);
 6614:         }
 6615:     } else {
 6616:         &Failure($client,"unknown_cmd\n",$userinput);
 6617:     }
 6618:     return 1;
 6619: }
 6620: &register_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
 6621: 
 6622: #
 6623: #   Read and retrieve institutional code format (for support form).
 6624: # Formal Parameters:
 6625: #    $cmd        - Command that dispatched us.
 6626: #    $tail       - Tail of the command.  In this case it conatins 
 6627: #                  the course domain and the coursename.
 6628: #    $client     - Socket open on the client.
 6629: # Returns:
 6630: #    1     - Continue processing.
 6631: #
 6632: sub get_institutional_code_format_handler {
 6633:     my ($cmd, $tail, $client)   = @_;
 6634:     my $userinput               = "$cmd:$tail";
 6635: 
 6636:     my $reply;
 6637:     my($cdom,$course) = split(/:/,$tail);
 6638:     my @pairs = split/\&/,$course;
 6639:     my %instcodes = ();
 6640:     my %codes = ();
 6641:     my @codetitles = ();
 6642:     my %cat_titles = ();
 6643:     my %cat_order = ();
 6644:     foreach (@pairs) {
 6645: 	my ($key,$value) = split/=/,$_;
 6646: 	$instcodes{&unescape($key)} = &unescape($value);
 6647:     }
 6648:     my $formatreply = &localenroll::instcode_format($cdom,
 6649: 						    \%instcodes,
 6650: 						    \%codes,
 6651: 						    \@codetitles,
 6652: 						    \%cat_titles,
 6653: 						    \%cat_order);
 6654:     if ($formatreply eq 'ok') {
 6655: 	my $codes_str = &Apache::lonnet::hash2str(%codes);
 6656: 	my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
 6657: 	my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
 6658: 	my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
 6659: 	&Reply($client,
 6660: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
 6661: 	       .$cat_order_str."\n",
 6662: 	       $userinput);
 6663:     } else {
 6664: 	# this else branch added by RF since if not ok, lonc will
 6665: 	# hang waiting on reply until timeout.
 6666: 	#
 6667: 	&Reply($client, "format_error\n", $userinput);
 6668:     }
 6669:     
 6670:     return 1;
 6671: }
 6672: &register_handler("autoinstcodeformat",
 6673: 		  \&get_institutional_code_format_handler,0,1,0);
 6674: 
 6675: sub get_institutional_defaults_handler {
 6676:     my ($cmd, $tail, $client)   = @_;
 6677:     my $userinput               = "$cmd:$tail";
 6678: 
 6679:     my $dom = $tail;
 6680:     my %defaults_hash;
 6681:     my @code_order;
 6682:     my $outcome;
 6683:     eval {
 6684:         local($SIG{__DIE__})='DEFAULT';
 6685:         $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
 6686:                                                    \@code_order);
 6687:     };
 6688:     if (!$@) {
 6689:         if ($outcome eq 'ok') {
 6690:             my $result='';
 6691:             while (my ($key,$value) = each(%defaults_hash)) {
 6692:                 $result.=&escape($key).'='.&escape($value).'&';
 6693:             }
 6694:             $result .= 'code_order='.&escape(join('&',@code_order));
 6695:             &Reply($client,\$result,$userinput);
 6696:         } else {
 6697:             &Reply($client,"error\n", $userinput);
 6698:         }
 6699:     } else {
 6700:         &Failure($client,"unknown_cmd\n",$userinput);
 6701:     }
 6702: }
 6703: &register_handler("autoinstcodedefaults",
 6704:                   \&get_institutional_defaults_handler,0,1,0);
 6705: 
 6706: sub get_possible_instcodes_handler {
 6707:     my ($cmd, $tail, $client)   = @_;
 6708:     my $userinput               = "$cmd:$tail";
 6709: 
 6710:     my $reply;
 6711:     my $cdom = $tail;
 6712:     my (@codetitles,%cat_titles,%cat_order,@code_order);
 6713:     my $formatreply = &localenroll::possible_instcodes($cdom,
 6714:                                                        \@codetitles,
 6715:                                                        \%cat_titles,
 6716:                                                        \%cat_order,
 6717:                                                        \@code_order);
 6718:     if ($formatreply eq 'ok') {
 6719:         my $result = join('&',map {&escape($_);} (@codetitles)).':';
 6720:         $result .= join('&',map {&escape($_);} (@code_order)).':';
 6721:         foreach my $key (keys(%cat_titles)) {
 6722:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
 6723:         }
 6724:         $result =~ s/\&$//;
 6725:         $result .= ':';
 6726:         foreach my $key (keys(%cat_order)) {
 6727:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
 6728:         }
 6729:         $result =~ s/\&$//;
 6730:         &Reply($client,\$result,$userinput);
 6731:     } else {
 6732:         &Reply($client, "format_error\n", $userinput);
 6733:     }
 6734:     return 1;
 6735: }
 6736: &register_handler("autopossibleinstcodes",
 6737:                   \&get_possible_instcodes_handler,0,1,0);
 6738: 
 6739: sub get_institutional_user_rules {
 6740:     my ($cmd, $tail, $client)   = @_;
 6741:     my $userinput               = "$cmd:$tail";
 6742:     my $dom = &unescape($tail);
 6743:     my (%rules_hash,@rules_order);
 6744:     my $outcome;
 6745:     eval {
 6746:         local($SIG{__DIE__})='DEFAULT';
 6747:         $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
 6748:     };
 6749:     if (!$@) {
 6750:         if ($outcome eq 'ok') {
 6751:             my $result;
 6752:             foreach my $key (keys(%rules_hash)) {
 6753:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
 6754:             }
 6755:             $result =~ s/\&$//;
 6756:             $result .= ':';
 6757:             if (@rules_order > 0) {
 6758:                 foreach my $item (@rules_order) {
 6759:                     $result .= &escape($item).'&';
 6760:                 }
 6761:             }
 6762:             $result =~ s/\&$//;
 6763:             &Reply($client,\$result,$userinput);
 6764:         } else {
 6765:             &Reply($client,"error\n", $userinput);
 6766:         }
 6767:     } else {
 6768:         &Failure($client,"unknown_cmd\n",$userinput);
 6769:     }
 6770: }
 6771: &register_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
 6772: 
 6773: sub get_institutional_id_rules {
 6774:     my ($cmd, $tail, $client)   = @_;
 6775:     my $userinput               = "$cmd:$tail";
 6776:     my $dom = &unescape($tail);
 6777:     my (%rules_hash,@rules_order);
 6778:     my $outcome;
 6779:     eval {
 6780:         local($SIG{__DIE__})='DEFAULT';
 6781:         $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
 6782:     };
 6783:     if (!$@) {
 6784:         if ($outcome eq 'ok') {
 6785:             my $result;
 6786:             foreach my $key (keys(%rules_hash)) {
 6787:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
 6788:             }
 6789:             $result =~ s/\&$//;
 6790:             $result .= ':';
 6791:             if (@rules_order > 0) {
 6792:                 foreach my $item (@rules_order) {
 6793:                     $result .= &escape($item).'&';
 6794:                 }
 6795:             }
 6796:             $result =~ s/\&$//;
 6797:             &Reply($client,\$result,$userinput);
 6798:         } else {
 6799:             &Reply($client,"error\n", $userinput);
 6800:         }
 6801:     } else {
 6802:         &Failure($client,"unknown_cmd\n",$userinput);
 6803:     }
 6804: }
 6805: &register_handler("instidrules",\&get_institutional_id_rules,0,1,0);
 6806: 
 6807: sub get_institutional_selfcreate_rules {
 6808:     my ($cmd, $tail, $client)   = @_;
 6809:     my $userinput               = "$cmd:$tail";
 6810:     my $dom = &unescape($tail);
 6811:     my (%rules_hash,@rules_order);
 6812:     my $outcome;
 6813:     eval {
 6814:         local($SIG{__DIE__})='DEFAULT';
 6815:         $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
 6816:     };
 6817:     if (!$@) {
 6818:         if ($outcome eq 'ok') {
 6819:             my $result;
 6820:             foreach my $key (keys(%rules_hash)) {
 6821:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
 6822:             }
 6823:             $result =~ s/\&$//;
 6824:             $result .= ':';
 6825:             if (@rules_order > 0) {
 6826:                 foreach my $item (@rules_order) {
 6827:                     $result .= &escape($item).'&';
 6828:                 }
 6829:             }
 6830:             $result =~ s/\&$//;
 6831:             &Reply($client,\$result,$userinput);
 6832:         } else {
 6833:             &Reply($client,"error\n", $userinput);
 6834:         }
 6835:     } else {
 6836:         &Failure($client,"unknown_cmd\n",$userinput);
 6837:     }
 6838: }
 6839: &register_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
 6840: 
 6841: sub get_unamemap_rules {
 6842:     my ($cmd, $tail, $client)   = @_;
 6843:     my $userinput               = "$cmd:$tail";
 6844:     my $dom = &unescape($tail);
 6845:     my (%rules_hash,@rules_order);
 6846:     my $outcome;
 6847:     eval {
 6848:         local($SIG{__DIE__})='DEFAULT';
 6849:         $outcome = &localenroll::unamemap_rules($dom,\%rules_hash,\@rules_order);
 6850:     };
 6851:     if (!$@) {
 6852:         if ($outcome eq 'ok') {
 6853:             my $result;
 6854:             foreach my $key (keys(%rules_hash)) {
 6855:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
 6856:             }
 6857:             $result =~ s/\&$//;
 6858:             $result .= ':';
 6859:             if (@rules_order > 0) {
 6860:                 foreach my $item (@rules_order) {
 6861:                     $result .= &escape($item).'&';
 6862:                 }
 6863:             }
 6864:             $result =~ s/\&$//;
 6865:             &Reply($client,\$result,$userinput);
 6866:         } else {
 6867:             &Reply($client,"error\n", $userinput);
 6868:         }
 6869:     } else {
 6870:         &Failure($client,"unknown_cmd\n",$userinput);
 6871:     }
 6872: }
 6873: &register_handler("unamemaprules",\&get_unamemap_rules,0,1,0);
 6874: 
 6875: sub institutional_username_check {
 6876:     my ($cmd, $tail, $client)   = @_;
 6877:     my $userinput               = "$cmd:$tail";
 6878:     my %rulecheck;
 6879:     my $outcome;
 6880:     my ($udom,$uname,@rules) = split(/:/,$tail);
 6881:     $udom = &unescape($udom);
 6882:     $uname = &unescape($uname);
 6883:     @rules = map {&unescape($_);} (@rules);
 6884:     eval {
 6885:         local($SIG{__DIE__})='DEFAULT';
 6886:         $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
 6887:     };
 6888:     if (!$@) {
 6889:         if ($outcome eq 'ok') {
 6890:             my $result='';
 6891:             foreach my $key (keys(%rulecheck)) {
 6892:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
 6893:             }
 6894:             &Reply($client,\$result,$userinput);
 6895:         } else {
 6896:             &Reply($client,"error\n", $userinput);
 6897:         }
 6898:     } else {
 6899:         &Failure($client,"unknown_cmd\n",$userinput);
 6900:     }
 6901: }
 6902: &register_handler("instrulecheck",\&institutional_username_check,0,1,0);
 6903: 
 6904: sub institutional_id_check {
 6905:     my ($cmd, $tail, $client)   = @_;
 6906:     my $userinput               = "$cmd:$tail";
 6907:     my %rulecheck;
 6908:     my $outcome;
 6909:     my ($udom,$id,@rules) = split(/:/,$tail);
 6910:     $udom = &unescape($udom);
 6911:     $id = &unescape($id);
 6912:     @rules = map {&unescape($_);} (@rules);
 6913:     eval {
 6914:         local($SIG{__DIE__})='DEFAULT';
 6915:         $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
 6916:     };
 6917:     if (!$@) {
 6918:         if ($outcome eq 'ok') {
 6919:             my $result='';
 6920:             foreach my $key (keys(%rulecheck)) {
 6921:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
 6922:             }
 6923:             &Reply($client,\$result,$userinput);
 6924:         } else {
 6925:             &Reply($client,"error\n", $userinput);
 6926:         }
 6927:     } else {
 6928:         &Failure($client,"unknown_cmd\n",$userinput);
 6929:     }
 6930: }
 6931: &register_handler("instidrulecheck",\&institutional_id_check,0,1,0);
 6932: 
 6933: sub institutional_selfcreate_check {
 6934:     my ($cmd, $tail, $client)   = @_;
 6935:     my $userinput               = "$cmd:$tail";
 6936:     my %rulecheck;
 6937:     my $outcome;
 6938:     my ($udom,$email,@rules) = split(/:/,$tail);
 6939:     $udom = &unescape($udom);
 6940:     $email = &unescape($email);
 6941:     @rules = map {&unescape($_);} (@rules);
 6942:     eval {
 6943:         local($SIG{__DIE__})='DEFAULT';
 6944:         $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
 6945:     };
 6946:     if (!$@) {
 6947:         if ($outcome eq 'ok') {
 6948:             my $result='';
 6949:             foreach my $key (keys(%rulecheck)) {
 6950:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
 6951:             }
 6952:             &Reply($client,\$result,$userinput);
 6953:         } else {
 6954:             &Reply($client,"error\n", $userinput);
 6955:         }
 6956:     } else {
 6957:         &Failure($client,"unknown_cmd\n",$userinput);
 6958:     }
 6959: }
 6960: &register_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
 6961: 
 6962: # Get domain specific conditions for import of student photographs to a course
 6963: #
 6964: # Retrieves information from photo_permission subroutine in localenroll.
 6965: # Returns outcome (ok) if no processing errors, and whether course owner is 
 6966: # required to accept conditions of use (yes/no).
 6967: #
 6968: #    
 6969: sub photo_permission_handler {
 6970:     my ($cmd, $tail, $client)   = @_;
 6971:     my $userinput               = "$cmd:$tail";
 6972:     my $cdom = $tail;
 6973:     my ($perm_reqd,$conditions);
 6974:     my $outcome;
 6975:     eval {
 6976: 	local($SIG{__DIE__})='DEFAULT';
 6977: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
 6978: 						  \$conditions);
 6979:     };
 6980:     if (!$@) {
 6981: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
 6982: 	       $userinput);
 6983:     } else {
 6984: 	&Failure($client,"unknown_cmd\n",$userinput);
 6985:     }
 6986:     return 1;
 6987: }
 6988: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
 6989: 
 6990: #
 6991: # Checks if student photo is available for a user in the domain, in the user's
 6992: # directory (in /userfiles/internal/studentphoto.jpg).
 6993: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
 6994: # the student's photo.   
 6995: 
 6996: sub photo_check_handler {
 6997:     my ($cmd, $tail, $client)   = @_;
 6998:     my $userinput               = "$cmd:$tail";
 6999:     my ($udom,$uname,$pid) = split(/:/,$tail);
 7000:     $udom = &unescape($udom);
 7001:     $uname = &unescape($uname);
 7002:     $pid = &unescape($pid);
 7003:     my $path=&propath($udom,$uname).'/userfiles/internal/';
 7004:     if (!-e $path) {
 7005:         &mkpath($path);
 7006:     }
 7007:     my $response;
 7008:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
 7009:     $result .= ':'.$response;
 7010:     &Reply($client, &escape($result)."\n",$userinput);
 7011:     return 1;
 7012: }
 7013: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
 7014: 
 7015: #
 7016: # Retrieve information from localenroll about whether to provide a button     
 7017: # for users who have enbled import of student photos to initiate an 
 7018: # update of photo files for registered students. Also include 
 7019: # comment to display alongside button.  
 7020: 
 7021: sub photo_choice_handler {
 7022:     my ($cmd, $tail, $client) = @_;
 7023:     my $userinput             = "$cmd:$tail";
 7024:     my $cdom                  = &unescape($tail);
 7025:     my ($update,$comment);
 7026:     eval {
 7027: 	local($SIG{__DIE__})='DEFAULT';
 7028: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
 7029:     };
 7030:     if (!$@) {
 7031: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
 7032:     } else {
 7033: 	&Failure($client,"unknown_cmd\n",$userinput);
 7034:     }
 7035:     return 1;
 7036: }
 7037: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
 7038: 
 7039: #
 7040: # Gets a student's photo to exist (in the correct image type) in the user's 
 7041: # directory.
 7042: # Formal Parameters:
 7043: #    $cmd     - The command request that got us dispatched.
 7044: #    $tail    - A colon separated set of words that will be split into:
 7045: #               $domain - student's domain
 7046: #               $uname  - student username
 7047: #               $type   - image type desired
 7048: #    $client  - The socket open on the client.
 7049: # Returns:
 7050: #    1 - continue processing.
 7051: 
 7052: sub student_photo_handler {
 7053:     my ($cmd, $tail, $client) = @_;
 7054:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
 7055: 
 7056:     my $path=&propath($domain,$uname). '/userfiles/internal/';
 7057:     my $filename = 'studentphoto.'.$ext;
 7058:     if ($type eq 'thumbnail') {
 7059:         $filename = 'studentphoto_tn.'.$ext;
 7060:     }
 7061:     if (-e $path.$filename) {
 7062: 	&Reply($client,"ok\n","$cmd:$tail");
 7063: 	return 1;
 7064:     }
 7065:     &mkpath($path);
 7066:     my $file;
 7067:     if ($type eq 'thumbnail') {
 7068: 	eval {
 7069: 	    local($SIG{__DIE__})='DEFAULT';
 7070: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
 7071: 	};
 7072:     } else {
 7073:         $file=&localstudentphoto::fetch($domain,$uname);
 7074:     }
 7075:     if (!$file) {
 7076: 	&Failure($client,"unavailable\n","$cmd:$tail");
 7077: 	return 1;
 7078:     }
 7079:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
 7080:     if (-e $path.$filename) {
 7081: 	&Reply($client,"ok\n","$cmd:$tail");
 7082: 	return 1;
 7083:     }
 7084:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
 7085:     return 1;
 7086: }
 7087: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
 7088: 
 7089: sub inst_usertypes_handler {
 7090:     my ($cmd, $domain, $client) = @_;
 7091:     my $res;
 7092:     my $userinput = $cmd.":".$domain; # For logging purposes.
 7093:     my (%typeshash,@order,$result);
 7094:     eval {
 7095: 	local($SIG{__DIE__})='DEFAULT';
 7096: 	$result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
 7097:     };
 7098:     if ($result eq 'ok') {
 7099:         if (keys(%typeshash) > 0) {
 7100:             foreach my $key (keys(%typeshash)) {
 7101:                 $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
 7102:             }
 7103:         }
 7104:         $res=~s/\&$//;
 7105:         $res .= ':';
 7106:         if (@order > 0) {
 7107:             foreach my $item (@order) {
 7108:                 $res .= &escape($item).'&';
 7109:             }
 7110:         }
 7111:         $res=~s/\&$//;
 7112:     }
 7113:     &Reply($client, \$res, $userinput);
 7114:     return 1;
 7115: }
 7116: &register_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
 7117: 
 7118: # mkpath makes all directories for a file, expects an absolute path with a
 7119: # file or a trailing / if just a dir is passed
 7120: # returns 1 on success 0 on failure
 7121: sub mkpath {
 7122:     my ($file)=@_;
 7123:     my @parts=split(/\//,$file,-1);
 7124:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
 7125:     for (my $i=3;$i<= ($#parts-1);$i++) {
 7126: 	$now.='/'.$parts[$i]; 
 7127: 	if (!-e $now) {
 7128: 	    if  (!mkdir($now,0770)) { return 0; }
 7129: 	}
 7130:     }
 7131:     return 1;
 7132: }
 7133: 
 7134: #---------------------------------------------------------------
 7135: #
 7136: #   Getting, decoding and dispatching requests:
 7137: #
 7138: #
 7139: #   Get a Request:
 7140: #   Gets a Request message from the client.  The transaction
 7141: #   is defined as a 'line' of text.  We remove the new line
 7142: #   from the text line.  
 7143: #
 7144: sub get_request {
 7145:     my $input = <$client>;
 7146:     chomp($input);
 7147: 
 7148:     &Debug("get_request: Request = $input\n");
 7149: 
 7150:     &status('Processing '.$clientname.':'.$input);
 7151: 
 7152:     return $input;
 7153: }
 7154: #---------------------------------------------------------------
 7155: #
 7156: #  Process a request.  This sub should shrink as each action
 7157: #  gets farmed out into a separat sub that is registered 
 7158: #  with the dispatch hash.  
 7159: #
 7160: # Parameters:
 7161: #    user_input   - The request received from the client (lonc).
 7162: #
 7163: # Returns:
 7164: #    true to keep processing, false if caller should exit.
 7165: #
 7166: sub process_request {
 7167:     my ($userinput) = @_; # Easier for now to break style than to
 7168:                           # fix all the userinput -> user_input.
 7169:     my $wasenc    = 0;		# True if request was encrypted.
 7170: # ------------------------------------------------------------ See if encrypted
 7171:     # for command
 7172:     # sethost:<server>
 7173:     # <command>:<args>
 7174:     #   we just send it to the processor
 7175:     # for
 7176:     # sethost:<server>:<command>:<args>
 7177:     #  we do the implict set host and then do the command
 7178:     if ($userinput =~ /^sethost:/) {
 7179: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
 7180: 	if (defined($userinput)) {
 7181: 	    &sethost("$cmd:$newid");
 7182: 	} else {
 7183: 	    $userinput = "$cmd:$newid";
 7184: 	}
 7185:     }
 7186: 
 7187:     if ($userinput =~ /^enc/) {
 7188: 	$userinput = decipher($userinput);
 7189: 	$wasenc=1;
 7190: 	if(!$userinput) {	# Cipher not defined.
 7191: 	    &Failure($client, "error: Encrypted data without negotated key\n");
 7192: 	    return 0;
 7193: 	}
 7194:     }
 7195:     Debug("process_request: $userinput\n");
 7196:     
 7197:     #  
 7198:     #   The 'correct way' to add a command to lond is now to
 7199:     #   write a sub to execute it and Add it to the command dispatch
 7200:     #   hash via a call to register_handler..  The comments to that
 7201:     #   sub should give you enough to go on to show how to do this
 7202:     #   along with the examples that are building up as this code
 7203:     #   is getting refactored.   Until all branches of the
 7204:     #   if/elseif monster below have been factored out into
 7205:     #   separate procesor subs, if the dispatch hash is missing
 7206:     #   the command keyword, we will fall through to the remainder
 7207:     #   of the if/else chain below in order to keep this thing in 
 7208:     #   working order throughout the transmogrification.
 7209: 
 7210:     my ($command, $tail) = split(/:/, $userinput, 2);
 7211:     chomp($command);
 7212:     chomp($tail);
 7213:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
 7214:     $command =~ s/(\r)//;	# And this too for parameterless commands.
 7215:     if(!$tail) {
 7216: 	$tail ="";		# defined but blank.
 7217:     }
 7218: 
 7219:     &Debug("Command received: $command, encoded = $wasenc");
 7220: 
 7221:     if(defined $Dispatcher{$command}) {
 7222: 
 7223: 	my $dispatch_info = $Dispatcher{$command};
 7224: 	my $handler       = $$dispatch_info[0];
 7225: 	my $need_encode   = $$dispatch_info[1];
 7226: 	my $client_types  = $$dispatch_info[2];
 7227: 	Debug("Matched dispatch hash: mustencode: $need_encode "
 7228: 	      ."ClientType $client_types");
 7229:       
 7230: 	#  Validate the request:
 7231:       
 7232: 	my $ok = 1;
 7233: 	my $requesterprivs = 0;
 7234: 	if(&isClient()) {
 7235: 	    $requesterprivs |= $CLIENT_OK;
 7236: 	}
 7237: 	if(&isManager()) {
 7238: 	    $requesterprivs |= $MANAGER_OK;
 7239: 	}
 7240: 	if($need_encode && (!$wasenc)) {
 7241: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
 7242: 	    $ok = 0;
 7243: 	}
 7244: 	if(($client_types & $requesterprivs) == 0) {
 7245: 	    Debug("Client not privileged to do this operation");
 7246: 	    $ok = 0;
 7247: 	}
 7248:         if ($ok) {
 7249:             my $realcommand = $command;
 7250:             if ($command eq 'querysend') {
 7251:                 my ($query,$rest)=split(/\:/,$tail,2);
 7252:                 $query=~s/\n*$//g;
 7253:                 my @possqueries = 
 7254:                     qw(userlog courselog fetchenrollment institutionalphotos usersearch instdirsearch getinstuser getmultinstusers);
 7255:                 if (grep(/^\Q$query\E$/,@possqueries)) {
 7256:                     $command .= '_'.$query;
 7257:                 } elsif ($query eq 'prepare activity log') {
 7258:                     $command .= '_activitylog';
 7259:                 }
 7260:             }
 7261:             if (ref($trust{$command}) eq 'HASH') {
 7262:                 my $donechecks;
 7263:                 if ($trust{$command}{'anywhere'}) {
 7264:                    $donechecks = 1;
 7265:                 } elsif ($trust{$command}{'manageronly'}) {
 7266:                     unless (&isManager()) {
 7267:                         $ok = 0;
 7268:                     }
 7269:                     $donechecks = 1;
 7270:                 } elsif ($trust{$command}{'institutiononly'}) {
 7271:                     unless ($clientsameinst) {
 7272:                         $ok = 0;
 7273:                     }
 7274:                     $donechecks = 1;
 7275:                 } elsif ($clientsameinst) {
 7276:                     $donechecks = 1;
 7277:                 }
 7278:                 unless ($donechecks) {
 7279:                     foreach my $rule (keys(%{$trust{$command}})) {
 7280:                         next if ($rule eq 'remote');
 7281:                         if ($trust{$command}{$rule}) {
 7282:                             if ($clientprohibited{$rule}) {
 7283:                                 $ok = 0;
 7284:                             } else {
 7285:                                 $ok = 1;
 7286:                                 $donechecks = 1;
 7287:                                 last;
 7288:                             }
 7289:                         }
 7290:                     }
 7291:                 }
 7292:                 unless ($donechecks) {
 7293:                     if ($trust{$command}{'remote'}) {
 7294:                         if ($clientremoteok) {
 7295:                             $ok = 1;
 7296:                         } else {
 7297:                             $ok = 0;
 7298:                         } 
 7299:                     }
 7300:                 }
 7301:             }
 7302:             $command = $realcommand;
 7303:         }
 7304: 
 7305: 	if($ok) {
 7306: 	    Debug("Dispatching to handler $command $tail");
 7307: 	    my $keep_going = &$handler($command, $tail, $client);
 7308: 	    return $keep_going;
 7309: 	} else {
 7310: 	    Debug("Refusing to dispatch because client did not match requirements");
 7311: 	    Failure($client, "refused\n", $userinput);
 7312: 	    return 1;
 7313: 	}
 7314:     }
 7315: 
 7316:     print $client "unknown_cmd\n";
 7317: # -------------------------------------------------------------------- complete
 7318:     Debug("process_request - returning 1");
 7319:     return 1;
 7320: }
 7321: #
 7322: #   Decipher encoded traffic
 7323: #  Parameters:
 7324: #     input      - Encoded data.
 7325: #  Returns:
 7326: #     Decoded data or undef if encryption key was not yet negotiated.
 7327: #  Implicit input:
 7328: #     cipher  - This global holds the negotiated encryption key.
 7329: #
 7330: sub decipher {
 7331:     my ($input)  = @_;
 7332:     my $output = '';
 7333:     
 7334:     
 7335:     if($cipher) {
 7336: 	my($enc, $enclength, $encinput) = split(/:/, $input);
 7337: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
 7338: 	    $output .= 
 7339: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
 7340: 	}
 7341: 	return substr($output, 0, $enclength);
 7342:     } else {
 7343: 	return undef;
 7344:     }
 7345: }
 7346: 
 7347: #
 7348: #   Register a command processor.  This function is invoked to register a sub
 7349: #   to process a request.  Once registered, the ProcessRequest sub can automatically
 7350: #   dispatch requests to an appropriate sub, and do the top level validity checking
 7351: #   as well:
 7352: #    - Is the keyword recognized.
 7353: #    - Is the proper client type attempting the request.
 7354: #    - Is the request encrypted if it has to be.
 7355: #   Parameters:
 7356: #    $request_name         - Name of the request being registered.
 7357: #                           This is the command request that will match
 7358: #                           against the hash keywords to lookup the information
 7359: #                           associated with the dispatch information.
 7360: #    $procedure           - Reference to a sub to call to process the request.
 7361: #                           All subs get called as follows:
 7362: #                             Procedure($cmd, $tail, $replyfd, $key)
 7363: #                             $cmd    - the actual keyword that invoked us.
 7364: #                             $tail   - the tail of the request that invoked us.
 7365: #                             $replyfd- File descriptor connected to the client
 7366: #    $must_encode          - True if the request must be encoded to be good.
 7367: #    $client_ok            - True if it's ok for a client to request this.
 7368: #    $manager_ok           - True if it's ok for a manager to request this.
 7369: # Side effects:
 7370: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
 7371: #      - On failure, the program will die as it's a bad internal bug to try to 
 7372: #        register a duplicate command handler.
 7373: #
 7374: sub register_handler {
 7375:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
 7376: 
 7377:     #  Don't allow duplication#
 7378:    
 7379:     if (defined $Dispatcher{$request_name}) {
 7380: 	die "Attempting to define a duplicate request handler for $request_name\n";
 7381:     }
 7382:     #   Build the client type mask:
 7383:     
 7384:     my $client_type_mask = 0;
 7385:     if($client_ok) {
 7386: 	$client_type_mask  |= $CLIENT_OK;
 7387:     }
 7388:     if($manager_ok) {
 7389: 	$client_type_mask  |= $MANAGER_OK;
 7390:     }
 7391:    
 7392:     #  Enter the hash:
 7393:       
 7394:     my @entry = ($procedure, $must_encode, $client_type_mask);
 7395:    
 7396:     $Dispatcher{$request_name} = \@entry;
 7397:    
 7398: }
 7399: 
 7400: 
 7401: #------------------------------------------------------------------
 7402: 
 7403: 
 7404: 
 7405: 
 7406: #
 7407: #  Convert an error return code from lcpasswd to a string value.
 7408: #
 7409: sub lcpasswdstrerror {
 7410:     my $ErrorCode = shift;
 7411:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
 7412: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
 7413:     } else {
 7414: 	return $passwderrors[$ErrorCode];
 7415:     }
 7416: }
 7417: 
 7418: # grabs exception and records it to log before exiting
 7419: sub catchexception {
 7420:     my ($error)=@_;
 7421:     $SIG{'QUIT'}='DEFAULT';
 7422:     $SIG{__DIE__}='DEFAULT';
 7423:     &status("Catching exception");
 7424:     &logthis("<font color='red'>CRITICAL: "
 7425:      ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
 7426:      ."a crash with this error msg->[$error]</font>");
 7427:     &logthis('Famous last words: '.$status.' - '.$lastlog);
 7428:     if ($client) { print $client "error: $error\n"; }
 7429:     $server->close();
 7430:     die($error);
 7431: }
 7432: sub timeout {
 7433:     &status("Handling Timeout");
 7434:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
 7435:     &catchexception('Timeout');
 7436: }
 7437: # -------------------------------- Set signal handlers to record abnormal exits
 7438: 
 7439: 
 7440: $SIG{'QUIT'}=\&catchexception;
 7441: $SIG{__DIE__}=\&catchexception;
 7442: 
 7443: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
 7444: &status("Read loncapa.conf and loncapa_apache.conf");
 7445: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
 7446: %perlvar=%{$perlvarref};
 7447: undef $perlvarref;
 7448: 
 7449: # ----------------------------- Make sure this process is running from user=www
 7450: my $wwwid=getpwnam('www');
 7451: if ($wwwid!=$<) {
 7452:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
 7453:    my $subj="LON: $currenthostid User ID mismatch";
 7454:    system("echo 'User ID mismatch.  lond must be run as user www.' |".
 7455:           " mail -s '$subj' $emailto > /dev/null");
 7456:    exit 1;
 7457: }
 7458: 
 7459: # --------------------------------------------- Check if other instance running
 7460: 
 7461: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
 7462: 
 7463: if (-e $pidfile) {
 7464:    my $lfh=IO::File->new("$pidfile");
 7465:    my $pide=<$lfh>;
 7466:    chomp($pide);
 7467:    if (kill 0 => $pide) { die "already running"; }
 7468: }
 7469: 
 7470: # ------------------------------------------------------------- Read hosts file
 7471: 
 7472: 
 7473: 
 7474: # establish SERVER socket, bind and listen.
 7475: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
 7476:                                 Type      => SOCK_STREAM,
 7477:                                 Proto     => 'tcp',
 7478:                                 ReuseAddr     => 1,
 7479:                                 Listen    => 10 )
 7480:   or die "making socket: $@\n";
 7481: 
 7482: # --------------------------------------------------------- Do global variables
 7483: 
 7484: # global variables
 7485: 
 7486: my %children               = ();       # keys are current child process IDs
 7487: 
 7488: sub REAPER {                        # takes care of dead children
 7489:     $SIG{CHLD} = \&REAPER;
 7490:     &status("Handling child death");
 7491:     my $pid;
 7492:     do {
 7493: 	$pid = waitpid(-1,&WNOHANG());
 7494: 	if (defined($children{$pid})) {
 7495: 	    &logthis("Child $pid died");
 7496: 	    delete($children{$pid});
 7497: 	} elsif ($pid > 0) {
 7498: 	    &logthis("Unknown Child $pid died");
 7499: 	}
 7500:     } while ( $pid > 0 );
 7501:     foreach my $child (keys(%children)) {
 7502: 	$pid = waitpid($child,&WNOHANG());
 7503: 	if ($pid > 0) {
 7504: 	    &logthis("Child $child - $pid looks like we missed it's death");
 7505: 	    delete($children{$pid});
 7506: 	}
 7507:     }
 7508:     &status("Finished Handling child death");
 7509: }
 7510: 
 7511: sub HUNTSMAN {                      # signal handler for SIGINT
 7512:     &status("Killing children (INT)");
 7513:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
 7514:     kill 'INT' => keys %children;
 7515:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
 7516:     my $execdir=$perlvar{'lonDaemons'};
 7517:     unlink("$execdir/logs/lond.pid");
 7518:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
 7519:     &status("Done killing children");
 7520:     exit;                           # clean up with dignity
 7521: }
 7522: 
 7523: sub HUPSMAN {                      # signal handler for SIGHUP
 7524:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
 7525:     &status("Killing children for restart (HUP)");
 7526:     kill 'INT' => keys %children;
 7527:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
 7528:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
 7529:     my $execdir=$perlvar{'lonDaemons'};
 7530:     unlink("$execdir/logs/lond.pid");
 7531:     &status("Restarting self (HUP)");
 7532:     exec("$execdir/lond");         # here we go again
 7533: }
 7534: 
 7535: #
 7536: #  Reload the Apache daemon's state.
 7537: #  This is done by invoking /home/httpd/perl/apachereload
 7538: #  a setuid perl script that can be root for us to do this job.
 7539: #
 7540: sub ReloadApache {
 7541: # --------------------------- Handle case of another apachereload process (locking)
 7542:     if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
 7543:         my $execdir = $perlvar{'lonDaemons'};
 7544:         my $script  = $execdir."/apachereload";
 7545:         system($script);
 7546:         unlink('/tmp/lock_apachereload'); #  Remove the lock file.
 7547:     }
 7548: }
 7549: 
 7550: #
 7551: #   Called in response to a USR2 signal.
 7552: #   - Reread hosts.tab
 7553: #   - All children connected to hosts that were removed from hosts.tab
 7554: #     are killed via SIGINT
 7555: #   - All children connected to previously existing hosts are sent SIGUSR1
 7556: #   - Our internal hosts hash is updated to reflect the new contents of
 7557: #     hosts.tab causing connections from hosts added to hosts.tab to
 7558: #     now be honored.
 7559: #
 7560: sub UpdateHosts {
 7561:     &status("Reload hosts.tab");
 7562:     logthis('<font color="blue"> Updating connections </font>');
 7563:     #
 7564:     #  The %children hash has the set of IP's we currently have children
 7565:     #  on.  These need to be matched against records in the hosts.tab
 7566:     #  Any ip's no longer in the table get killed off they correspond to
 7567:     #  either dropped or changed hosts.  Note that the re-read of the table
 7568:     #  will take care of new and changed hosts as connections come into being.
 7569: 
 7570:     &Apache::lonnet::reset_hosts_info();
 7571:     my %active;
 7572: 
 7573:     foreach my $child (keys(%children)) {
 7574: 	my $childip = $children{$child};
 7575: 	if ($childip ne '127.0.0.1'
 7576: 	    && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
 7577: 	    logthis('<font color="blue"> UpdateHosts killing child '
 7578: 		    ." $child for ip $childip </font>");
 7579: 	    kill('INT', $child);
 7580: 	} else {
 7581:             $active{$child} = $childip;
 7582: 	    logthis('<font color="green"> keeping child for ip '
 7583: 		    ." $childip (pid=$child) </font>");
 7584: 	}
 7585:     }
 7586: 
 7587:     my %oldconf = %secureconf;
 7588:     my %connchange;
 7589:     if (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
 7590:         logthis('<font color="blue"> Reloaded SSL connection rules and cleared CRL checking history </font>');
 7591:     } else {
 7592:         logthis('<font color="yellow"> Failed to reload SSL connection rules and clear CRL checking history </font>');
 7593:     }
 7594:     if ((ref($oldconf{'connfrom'}) eq 'HASH') && (ref($secureconf{'connfrom'}) eq 'HASH')) {
 7595:         foreach my $type ('dom','intdom','other') {
 7596:             if ((($oldconf{'connfrom'}{$type} eq 'no') && ($secureconf{'connfrom'}{$type} eq 'req')) ||
 7597:                 (($oldconf{'connfrom'}{$type} eq 'req') && ($secureconf{'connfrom'}{$type} eq 'no'))) {
 7598:                 $connchange{$type} = 1;
 7599:             }
 7600:         }
 7601:     }
 7602:     if (keys(%connchange)) {
 7603:         foreach my $child (keys(%active)) {
 7604:             my $childip = $active{$child};
 7605:             if ($childip ne '127.0.0.1') {
 7606:                 my $childhostname  = gethostbyaddr(Socket::inet_aton($childip),AF_INET);
 7607:                 if ($childhostname ne '') {
 7608:                     my $childlonhost = &Apache::lonnet::get_server_homeID($childhostname);
 7609:                     my ($samedom,$sameinst) = &set_client_info($childlonhost);
 7610:                     if ($samedom) {
 7611:                         if ($connchange{'dom'}) {
 7612:                             logthis('<font color="blue"> UpdateHosts killing child '
 7613:                                    ." $child for ip $childip </font>");
 7614:                             kill('INT', $child);
 7615:                         }
 7616:                     } elsif ($sameinst) {
 7617:                         if ($connchange{'intdom'}) {
 7618:                             logthis('<font color="blue"> UpdateHosts killing child '
 7619:                                    ." $child for ip $childip </font>");
 7620:                            kill('INT', $child);
 7621:                         }
 7622:                     } else {
 7623:                         if ($connchange{'other'}) {
 7624:                             logthis('<font color="blue"> UpdateHosts killing child '
 7625:                                    ." $child for ip $childip </font>");
 7626:                             kill('INT', $child);
 7627:                         }
 7628:                     }
 7629:                 }
 7630:             }
 7631:         }
 7632:     }
 7633:     ReloadApache;
 7634:     &status("Finished reloading hosts.tab");
 7635: }
 7636: 
 7637: sub checkchildren {
 7638:     &status("Checking on the children (sending signals)");
 7639:     &initnewstatus();
 7640:     &logstatus();
 7641:     &logthis('Going to check on the children');
 7642:     my $docdir=$perlvar{'lonDocRoot'};
 7643:     foreach (sort keys %children) {
 7644: 	#sleep 1;
 7645:         unless (kill 'USR1' => $_) {
 7646: 	    &logthis ('Child '.$_.' is dead');
 7647:             &logstatus($$.' is dead');
 7648: 	    delete($children{$_});
 7649:         } 
 7650:     }
 7651:     sleep 5;
 7652:     $SIG{ALRM} = sub { Debug("timeout"); 
 7653: 		       die "timeout";  };
 7654:     $SIG{__DIE__} = 'DEFAULT';
 7655:     &status("Checking on the children (waiting for reports)");
 7656:     foreach (sort keys %children) {
 7657:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
 7658:           eval {
 7659:             alarm(300);
 7660: 	    &logthis('Child '.$_.' did not respond');
 7661: 	    kill 9 => $_;
 7662: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
 7663: 	    #$subj="LON: $currenthostid killed lond process $_";
 7664: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
 7665: 	    #$execdir=$perlvar{'lonDaemons'};
 7666: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
 7667: 	    delete($children{$_});
 7668: 	    alarm(0);
 7669: 	  }
 7670:         }
 7671:     }
 7672:     $SIG{ALRM} = 'DEFAULT';
 7673:     $SIG{__DIE__} = \&catchexception;
 7674:     &status("Finished checking children");
 7675:     &logthis('Finished Checking children');
 7676: }
 7677: 
 7678: # --------------------------------------------------------------------- Logging
 7679: 
 7680: sub logthis {
 7681:     my $message=shift;
 7682:     my $execdir=$perlvar{'lonDaemons'};
 7683:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
 7684:     my $now=time;
 7685:     my $local=localtime($now);
 7686:     $lastlog=$local.': '.$message;
 7687:     print $fh "$local ($$): $message\n";
 7688: }
 7689: 
 7690: # ------------------------- Conditional log if $DEBUG true.
 7691: sub Debug {
 7692:     my $message = shift;
 7693:     if($DEBUG) {
 7694: 	&logthis($message);
 7695:     }
 7696: }
 7697: 
 7698: #
 7699: #   Sub to do replies to client.. this gives a hook for some
 7700: #   debug tracing too:
 7701: #  Parameters:
 7702: #     fd      - File open on client.
 7703: #     reply   - Text to send to client.
 7704: #     request - Original request from client.
 7705: #
 7706: #NOTE $reply must be terminated by exactly *one* \n. If $reply is a reference
 7707: #this is done automatically ($$reply must not contain any \n in this case). 
 7708: #If $reply is a string the caller has to ensure this.
 7709: sub Reply {
 7710:     my ($fd, $reply, $request) = @_;
 7711:     if (ref($reply)) {
 7712: 	print $fd $$reply;
 7713: 	print $fd "\n";
 7714: 	if ($DEBUG) { Debug("Request was $request  Reply was $$reply"); }
 7715:     } else {
 7716: 	print $fd $reply;
 7717: 	if ($DEBUG) { Debug("Request was $request  Reply was $reply"); }
 7718:     }
 7719:     $Transactions++;
 7720: }
 7721: 
 7722: 
 7723: #
 7724: #    Sub to report a failure.
 7725: #    This function:
 7726: #     -   Increments the failure statistic counters.
 7727: #     -   Invokes Reply to send the error message to the client.
 7728: # Parameters:
 7729: #    fd       - File descriptor open on the client
 7730: #    reply    - Reply text to emit.
 7731: #    request  - The original request message (used by Reply
 7732: #               to debug if that's enabled.
 7733: # Implicit outputs:
 7734: #    $Failures- The number of failures is incremented.
 7735: #    Reply (invoked here) sends a message to the 
 7736: #    client:
 7737: #
 7738: sub Failure {
 7739:     my $fd      = shift;
 7740:     my $reply   = shift;
 7741:     my $request = shift;
 7742:    
 7743:     $Failures++;
 7744:     Reply($fd, $reply, $request);      # That's simple eh?
 7745: }
 7746: # ------------------------------------------------------------------ Log status
 7747: 
 7748: sub logstatus {
 7749:     &status("Doing logging");
 7750:     my $docdir=$perlvar{'lonDocRoot'};
 7751:     {
 7752: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
 7753:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
 7754:         $fh->close();
 7755:     }
 7756:     &status("Finished $$.txt");
 7757:     {
 7758: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
 7759: 	flock(LOG,LOCK_EX);
 7760: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
 7761: 	    .$status."\t".$lastlog."\t $keymode\n";
 7762: 	flock(LOG,LOCK_UN);
 7763: 	close(LOG);
 7764:     }
 7765:     &status("Finished logging");
 7766: }
 7767: 
 7768: sub initnewstatus {
 7769:     my $docdir=$perlvar{'lonDocRoot'};
 7770:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
 7771:     my $now=time();
 7772:     my $local=localtime($now);
 7773:     print $fh "LOND status $local - parent $$\n\n";
 7774:     opendir(DIR,"$docdir/lon-status/londchld");
 7775:     while (my $filename=readdir(DIR)) {
 7776:         unlink("$docdir/lon-status/londchld/$filename");
 7777:     }
 7778:     closedir(DIR);
 7779: }
 7780: 
 7781: # -------------------------------------------------------------- Status setting
 7782: 
 7783: sub status {
 7784:     my $what=shift;
 7785:     my $now=time;
 7786:     my $local=localtime($now);
 7787:     $status=$local.': '.$what;
 7788:     $0='lond: '.$what.' '.$local;
 7789: }
 7790: 
 7791: # -------------------------------------------------------------- Talk to lonsql
 7792: 
 7793: sub sql_reply {
 7794:     my ($cmd)=@_;
 7795:     my $answer=&sub_sql_reply($cmd);
 7796:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
 7797:     return $answer;
 7798: }
 7799: 
 7800: sub sub_sql_reply {
 7801:     my ($cmd)=@_;
 7802:     my $unixsock="mysqlsock";
 7803:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
 7804:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
 7805:                                       Type    => SOCK_STREAM,
 7806:                                       Timeout => 10)
 7807:        or return "con_lost";
 7808:     print $sclient "$cmd:$currentdomainid\n";
 7809:     my $answer=<$sclient>;
 7810:     chomp($answer);
 7811:     if (!$answer) { $answer="con_lost"; }
 7812:     return $answer;
 7813: }
 7814: 
 7815: # --------------------------------------- Is this the home server of an author?
 7816: 
 7817: sub ishome {
 7818:     my $author=shift;
 7819:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 7820:     my ($udom,$uname)=split(/\//,$author);
 7821:     my $proname=propath($udom,$uname);
 7822:     if (-e $proname) {
 7823: 	return 'owner';
 7824:     } else {
 7825:         return 'not_owner';
 7826:     }
 7827: }
 7828: 
 7829: # ======================================================= Continue main program
 7830: # ---------------------------------------------------- Fork once and dissociate
 7831: 
 7832: my $fpid=fork;
 7833: exit if $fpid;
 7834: die "Couldn't fork: $!" unless defined ($fpid);
 7835: 
 7836: POSIX::setsid() or die "Can't start new session: $!";
 7837: 
 7838: # ------------------------------------------------------- Write our PID on disk
 7839: 
 7840: my $execdir=$perlvar{'lonDaemons'};
 7841: open (PIDSAVE,">$execdir/logs/lond.pid");
 7842: print PIDSAVE "$$\n";
 7843: close(PIDSAVE);
 7844: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
 7845: &status('Starting');
 7846: 
 7847: 
 7848: 
 7849: # ----------------------------------------------------- Install signal handlers
 7850: 
 7851: 
 7852: $SIG{CHLD} = \&REAPER;
 7853: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 7854: $SIG{HUP}  = \&HUPSMAN;
 7855: $SIG{USR1} = \&checkchildren;
 7856: $SIG{USR2} = \&UpdateHosts;
 7857: 
 7858: #  Read the host hashes:
 7859: &Apache::lonnet::load_hosts_tab();
 7860: my %iphost = &Apache::lonnet::get_iphost(1);
 7861: 
 7862: $dist=`$perlvar{'lonDaemons'}/distprobe`;
 7863: 
 7864: my $arch = `uname -i`;
 7865: chomp($arch);
 7866: if ($arch eq 'unknown') {
 7867:     $arch = `uname -m`;
 7868:     chomp($arch);
 7869: }
 7870: 
 7871: unless (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
 7872:     &logthis('<font color="blue">No connectionrules table. Will fallback to loncapa.conf</font>');
 7873: }
 7874: 
 7875: # --------------------------------------------------------------
 7876: #   Accept connections.  When a connection comes in, it is validated
 7877: #   and if good, a child process is created to process transactions
 7878: #   along the connection.
 7879: 
 7880: while (1) {
 7881:     &status('Starting accept');
 7882:     $client = $server->accept() or next;
 7883:     &status('Accepted '.$client.' off to spawn');
 7884:     make_new_child($client);
 7885:     &status('Finished spawning');
 7886: }
 7887: 
 7888: sub make_new_child {
 7889:     my $pid;
 7890: #    my $cipher;     # Now global
 7891:     my $sigset;
 7892: 
 7893:     $client = shift;
 7894:     &status('Starting new child '.$client);
 7895:     &logthis('<font color="green"> Attempting to start child ('.$client.
 7896: 	     ")</font>");    
 7897:     # block signal for fork
 7898:     $sigset = POSIX::SigSet->new(SIGINT);
 7899:     sigprocmask(SIG_BLOCK, $sigset)
 7900:         or die "Can't block SIGINT for fork: $!\n";
 7901: 
 7902:     die "fork: $!" unless defined ($pid = fork);
 7903: 
 7904:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
 7905: 	                               # connection liveness.
 7906: 
 7907:     #
 7908:     #  Figure out who we're talking to so we can record the peer in 
 7909:     #  the pid hash.
 7910:     #
 7911:     my $caller = getpeername($client);
 7912:     my ($port,$iaddr);
 7913:     if (defined($caller) && length($caller) > 0) {
 7914: 	($port,$iaddr)=unpack_sockaddr_in($caller);
 7915:     } else {
 7916: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
 7917:     }
 7918:     if (defined($iaddr)) {
 7919: 	$clientip  = inet_ntoa($iaddr);
 7920: 	Debug("Connected with $clientip");
 7921:     } else {
 7922: 	&logthis("Unable to determine clientip");
 7923: 	$clientip='Unavailable';
 7924:     }
 7925:     
 7926:     if ($pid) {
 7927:         # Parent records the child's birth and returns.
 7928:         sigprocmask(SIG_UNBLOCK, $sigset)
 7929:             or die "Can't unblock SIGINT for fork: $!\n";
 7930:         $children{$pid} = $clientip;
 7931:         &status('Started child '.$pid);
 7932: 	close($client);
 7933:         return;
 7934:     } else {
 7935:         # Child can *not* return from this subroutine.
 7936:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
 7937:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
 7938:                                 #don't get intercepted
 7939:         $SIG{USR1}= \&logstatus;
 7940:         $SIG{ALRM}= \&timeout;
 7941: 	#
 7942: 	# Block sigpipe as it gets thrownon socket disconnect and we want to 
 7943: 	# deal with that as a read faiure instead.
 7944: 	#
 7945: 	my $blockset = POSIX::SigSet->new(SIGPIPE);
 7946: 	sigprocmask(SIG_BLOCK, $blockset);
 7947: 
 7948:         $lastlog='Forked ';
 7949:         $status='Forked';
 7950: 
 7951:         # unblock signals
 7952:         sigprocmask(SIG_UNBLOCK, $sigset)
 7953:             or die "Can't unblock SIGINT for fork: $!\n";
 7954: 
 7955: #        my $tmpsnum=0;            # Now global
 7956: #---------------------------------------------------- kerberos 5 initialization
 7957:         &Authen::Krb5::init_context();
 7958: 
 7959:         my $no_ets;
 7960:         if ($dist =~ /^(?:centos|rhes|scientific|oracle|rocky|alma)(\d+)/) {
 7961:             if ($1 >= 7) {
 7962:                 $no_ets = 1;
 7963:             }
 7964:         } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
 7965:             if (($1 eq '9.3') || ($1 >= 12.2)) {
 7966:                 $no_ets = 1; 
 7967:             }
 7968:         } elsif ($dist =~ /^sles(\d+)$/) {
 7969:             if ($1 > 11) {
 7970:                 $no_ets = 1;
 7971:             }
 7972:         } elsif ($dist =~ /^fedora(\d+)$/) {
 7973:             if ($1 < 7) {
 7974:                 $no_ets = 1;
 7975:             }
 7976:         }
 7977:         unless ($no_ets) {
 7978: 	    &Authen::Krb5::init_ets();
 7979: 	}
 7980: 
 7981: 	&status('Accepted connection');
 7982: # =============================================================================
 7983:             # do something with the connection
 7984: # -----------------------------------------------------------------------------
 7985: 	# see if we know client and 'check' for spoof IP by ineffective challenge
 7986: 
 7987: 	my $outsideip=$clientip;
 7988: 	if ($clientip eq '127.0.0.1') {
 7989: 	    $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
 7990: 	}
 7991: 	&ReadManagerTable();
 7992: 	my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
 7993: 	my $ismanager=($managers{$outsideip}    ne undef);
 7994: 	$clientname  = "[unknown]";
 7995: 	if($clientrec) {	# Establish client type.
 7996: 	    $ConnectionType = "client";
 7997: 	    $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
 7998: 	    if($ismanager) {
 7999: 		$ConnectionType = "both";
 8000: 	    }
 8001: 	} else {
 8002: 	    $ConnectionType = "manager";
 8003: 	    $clientname = $managers{$outsideip};
 8004: 	}
 8005: 	my $clientok;
 8006: 
 8007: 	if ($clientrec || $ismanager) {
 8008: 	    &status("Waiting for init from $clientip $clientname");
 8009: 	    &logthis('<font color="yellow">INFO: Connection, '.
 8010: 		     $clientip.
 8011: 		  " ($clientname) connection type = $ConnectionType </font>" );
 8012: 	    &status("Connecting $clientip  ($clientname))"); 
 8013: 	    my $remotereq=<$client>;
 8014: 	    chomp($remotereq);
 8015: 	    Debug("Got init: $remotereq");
 8016: 
 8017: 	    if ($remotereq =~ /^init/) {
 8018: 		&sethost("sethost:$perlvar{'lonHostID'}");
 8019: 		#
 8020: 		#  If the remote is attempting a local init... give that a try:
 8021: 		#
 8022: 		(my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
 8023:         # For LON-CAPA 2.9, the  client session will have sent its LON-CAPA
 8024:         # version when initiating the connection. For LON-CAPA 2.8 and older,
 8025:         # the version is retrieved from the global %loncaparevs in lonnet.pm.            
 8026:         # $clientversion contains path to keyfile if $inittype eq 'local'
 8027:         # it's overridden below in this case
 8028:         $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
 8029: 
 8030: 		# If the connection type is ssl, but I didn't get my
 8031: 		# certificate files yet, then I'll drop  back to 
 8032: 		# insecure (if allowed).
 8033: 
 8034:                 if ($inittype eq "ssl") {
 8035:                     my $context;
 8036:                     if ($clientsamedom) {
 8037:                         $context = 'dom';
 8038:                         if ($secureconf{'connfrom'}{'dom'} eq 'no') {
 8039:                             $inittype = "";
 8040:                         }
 8041:                     } elsif ($clientsameinst) {
 8042:                         $context = 'intdom';
 8043:                         if ($secureconf{'connfrom'}{'intdom'} eq 'no') {
 8044:                             $inittype = "";
 8045:                         }
 8046:                     } else {
 8047:                         $context = 'other';
 8048:                         if ($secureconf{'connfrom'}{'other'} eq 'no') {
 8049:                             $inittype = "";
 8050:                         }
 8051:                     }
 8052:                     if ($inittype eq '') {
 8053:                         &logthis("<font color=\"blue\"> Domain config set "
 8054:                                 ."to no ssl for $clientname (context: $context)"
 8055:                                 ." -- trying insecure auth</font>");
 8056:                     }
 8057:                 }
 8058: 
 8059: 		if($inittype eq "ssl") {
 8060: 		    my ($ca, $cert) = lonssl::CertificateFile;
 8061: 		    my $kfile       = lonssl::KeyFile;
 8062: 		    if((!$ca)   || 
 8063: 		       (!$cert) || 
 8064: 		       (!$kfile)) {
 8065: 			$inittype = ""; # This forces insecure attempt.
 8066: 			&logthis("<font color=\"blue\"> Certificates not "
 8067: 				 ."installed -- trying insecure auth</font>");
 8068: 		    } else {	# SSL certificates are in place so
 8069: 		    }		# Leave the inittype alone.
 8070: 		}
 8071: 
 8072: 		if($inittype eq "local") {
 8073:                     $clientversion = $perlvar{'lonVersion'};
 8074: 		    my $key = LocalConnection($client, $remotereq);
 8075: 		    if($key) {
 8076: 			Debug("Got local key $key");
 8077: 			$clientok     = 1;
 8078: 			my $cipherkey = pack("H32", $key);
 8079: 			$cipher       = new IDEA($cipherkey);
 8080: 			print $client "ok:local\n";
 8081: 			&logthis('<font color="green">'
 8082: 				 . "Successful local authentication </font>");
 8083: 			$keymode = "local"
 8084: 		    } else {
 8085: 			Debug("Failed to get local key");
 8086: 			$clientok = 0;
 8087: 			shutdown($client, 3);
 8088: 			close $client;
 8089: 		    }
 8090: 		} elsif ($inittype eq "ssl") {
 8091: 		    my $key = SSLConnection($client,$clientname);
 8092: 		    if ($key) {
 8093: 			$clientok = 1;
 8094: 			my $cipherkey = pack("H32", $key);
 8095: 			$cipher       = new IDEA($cipherkey);
 8096: 			&logthis('<font color="green">'
 8097: 				 ."Successfull ssl authentication with $clientname </font>");
 8098: 			$keymode = "ssl";
 8099: 	     
 8100: 		    } else {
 8101: 			$clientok = 0;
 8102: 			close $client;
 8103: 		    }
 8104: 	   
 8105: 		} else {
 8106: 		    my $ok = InsecureConnection($client);
 8107: 		    if($ok) {
 8108: 			$clientok = 1;
 8109: 			&logthis('<font color="green">'
 8110: 				 ."Successful insecure authentication with $clientname </font>");
 8111: 			print $client "ok\n";
 8112: 			$keymode = "insecure";
 8113: 		    } else {
 8114: 			&logthis('<font color="yellow">'
 8115: 				  ."Attempted insecure connection disallowed </font>");
 8116: 			close $client;
 8117: 			$clientok = 0;
 8118: 		    }
 8119: 		}
 8120: 	    } else {
 8121: 		&logthis(
 8122: 			 "<font color='blue'>WARNING: "
 8123: 			 ."$clientip failed to initialize: >$remotereq< </font>");
 8124: 		&status('No init '.$clientip);
 8125: 	    }
 8126: 	} else {
 8127: 	    &logthis(
 8128: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
 8129: 	    &status('Hung up on '.$clientip);
 8130: 	}
 8131:  
 8132: 	if ($clientok) {
 8133: # ---------------- New known client connecting, could mean machine online again
 8134: 	    if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip 
 8135: 		&& $clientip ne '127.0.0.1') {
 8136: 		&Apache::lonnet::reconlonc($clientname);
 8137: 	    }
 8138: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
 8139: 	    &status('Will listen to '.$clientname);
 8140: # ------------------------------------------------------------ Process requests
 8141: 	    my $keep_going = 1;
 8142: 	    my $user_input;
 8143: 
 8144: 	    while(($user_input = get_request) && $keep_going) {
 8145: 		alarm(120);
 8146: 		Debug("Main: Got $user_input\n");
 8147: 		$keep_going = &process_request($user_input);
 8148: 		alarm(0);
 8149: 		&status('Listening to '.$clientname." ($keymode)");
 8150: 	    }
 8151: 
 8152: # --------------------------------------------- client unknown or fishy, refuse
 8153: 	}  else {
 8154: 	    print $client "refused\n";
 8155: 	    $client->close();
 8156: 	    &logthis("<font color='blue'>WARNING: "
 8157: 		     ."Rejected client $clientip, closing connection</font>");
 8158: 	}
 8159:     }
 8160:     
 8161: # =============================================================================
 8162:     
 8163:     &logthis("<font color='red'>CRITICAL: "
 8164: 	     ."Disconnect from $clientip ($clientname)</font>");    
 8165: 
 8166: 
 8167:     # this exit is VERY important, otherwise the child will become
 8168:     # a producer of more and more children, forking yourself into
 8169:     # process death.
 8170:     exit;
 8171:     
 8172: }
 8173: 
 8174: #
 8175: #  Used to determine if a particular client is from the same domain
 8176: #  as the current server, or from the same internet domain, and
 8177: #  also if the client can host sessions for the domain's users.
 8178: #  A hash is populated with keys set to commands sent by the client
 8179: #  which may not be executed for this domain.
 8180: #
 8181: #  Optional input -- the client to check for domain and internet domain.
 8182: #  If not specified, defaults to the package variable: $clientname
 8183: #
 8184: #  If called in array context will not set package variables, but will
 8185: #  instead return an array of two values - (a) true if client is in the
 8186: #  same domain as the server, and (b) true if client is in the same 
 8187: #  internet domain.
 8188: #
 8189: #  If called in scalar context, sets package variables for current client:
 8190: #
 8191: #  $clienthomedom    - LonCAPA domain of homeID for client.
 8192: #  $clientsamedom    - LonCAPA domain same for this host and client.
 8193: #  $clientintdom     - LonCAPA "internet domain" for client.
 8194: #  $clientsameinst   - LonCAPA "internet domain" same for this host & client.
 8195: #  $clientremoteok   - If current domain permits hosting on this client: 1
 8196: #  %clientprohibited - Commands prohibited for domain's users for this client.
 8197: #
 8198: #  if the host and client have the same "internet domain", then the value
 8199: #  of $clientremoteok is not used, and no commands are prohibited.
 8200: #
 8201: #  returns 1 to indicate package variables have been set for current client.
 8202: #
 8203: 
 8204: sub set_client_info {
 8205:     my ($lonhost) = @_;
 8206:     $lonhost ||= $clientname;
 8207:     my $clienthost = &Apache::lonnet::hostname($lonhost);
 8208:     my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
 8209:     my $homedom = &Apache::lonnet::host_domain($clientserverhomeID);
 8210:     my $samedom = 0;
 8211:     if ($perlvar{'lonDefDomain'} eq $homedom) {
 8212:         $samedom = 1;
 8213:     }
 8214:     my $intdom = &Apache::lonnet::internet_dom($clientserverhomeID);
 8215:     my $sameinst = 0;
 8216:     if ($intdom ne '') {
 8217:         my $internet_names = &Apache::lonnet::get_internet_names($currenthostid);
 8218:         if (ref($internet_names) eq 'ARRAY') {
 8219:             if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 8220:                 $sameinst = 1;
 8221:             }
 8222:         }
 8223:     }
 8224:     if (wantarray) {
 8225:         return ($samedom,$sameinst);
 8226:     } else {
 8227:         $clienthomedom = $homedom;
 8228:         $clientsamedom = $samedom;
 8229:         $clientintdom = $intdom;
 8230:         $clientsameinst = $sameinst;
 8231:         if ($clientsameinst) {
 8232:             undef($clientremoteok);
 8233:             undef(%clientprohibited);
 8234:         } else {
 8235:             $clientremoteok = &get_remote_hostable($currentdomainid);
 8236:             %clientprohibited = &get_prohibited($currentdomainid);
 8237:         }
 8238:         return 1;
 8239:     }
 8240: }
 8241: 
 8242: #
 8243: #   Determine if a user is an author for the indicated domain.
 8244: #
 8245: # Parameters:
 8246: #    domain          - domain to check in .
 8247: #    user            - Name of user to check.
 8248: #
 8249: # Return:
 8250: #     1             - User is an author for domain.
 8251: #     0             - User is not an author for domain.
 8252: sub is_author {
 8253:     my ($domain, $user) = @_;
 8254: 
 8255:     &Debug("is_author: $user @ $domain");
 8256: 
 8257:     my $hashref = &tie_user_hash($domain, $user, "roles",
 8258: 				 &GDBM_READER());
 8259: 
 8260:     #  Author role should show up as a key /domain/_au
 8261: 
 8262:     my $value;
 8263:     if ($hashref) {
 8264: 
 8265: 	my $key    = "/$domain/_au";
 8266: 	if (defined($hashref)) {
 8267: 	    $value = $hashref->{$key};
 8268: 	    if(!untie_user_hash($hashref)) {
 8269: 		return 'error: ' .  ($!+0)." untie (GDBM) Failed";
 8270: 	    }
 8271: 	}
 8272: 	
 8273: 	if(defined($value)) {
 8274: 	    &Debug("$user @ $domain is an author");
 8275: 	}
 8276:     } else {
 8277: 	return 'error: '.($!+0)." tie (GDBM) Failed";
 8278:     }
 8279: 
 8280:     return defined($value);
 8281: }
 8282: #
 8283: #   Checks to see if the input roleput request was to set
 8284: # an author role.  If so, creates construction space 
 8285: # Parameters:
 8286: #    request   - The request sent to the rolesput subchunk.
 8287: #                We're looking for  /domain/_au
 8288: #    domain    - The domain in which the user is having roles doctored.
 8289: #    user      - Name of the user for which the role is being put.
 8290: #    authtype  - The authentication type associated with the user.
 8291: #
 8292: sub manage_permissions {
 8293:     my ($request, $domain, $user, $authtype) = @_;
 8294:     # See if the request is of the form /$domain/_au
 8295:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
 8296:         my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
 8297:         unless (-e $path) {        
 8298:            mkdir($path);
 8299:         }
 8300:         unless (-e $path.'/'.$user) {
 8301:            mkdir($path.'/'.$user);
 8302:         }
 8303:     }
 8304: }
 8305: 
 8306: 
 8307: #
 8308: #  Return the full path of a user password file, whether it exists or not.
 8309: # Parameters:
 8310: #   domain     - Domain in which the password file lives.
 8311: #   user       - name of the user.
 8312: # Returns:
 8313: #    Full passwd path:
 8314: #
 8315: sub password_path {
 8316:     my ($domain, $user) = @_;
 8317:     return &propath($domain, $user).'/passwd';
 8318: }
 8319: 
 8320: #   Password Filename
 8321: #   Returns the path to a passwd file given domain and user... only if
 8322: #  it exists.
 8323: # Parameters:
 8324: #   domain    - Domain in which to search.
 8325: #   user      - username.
 8326: # Returns:
 8327: #   - If the password file exists returns its path.
 8328: #   - If the password file does not exist, returns undefined.
 8329: #
 8330: sub password_filename {
 8331:     my ($domain, $user) = @_;
 8332: 
 8333:     Debug ("PasswordFilename called: dom = $domain user = $user");
 8334: 
 8335:     my $path  = &password_path($domain, $user);
 8336:     Debug("PasswordFilename got path: $path");
 8337:     if(-e $path) {
 8338: 	return $path;
 8339:     } else {
 8340: 	return undef;
 8341:     }
 8342: }
 8343: 
 8344: #
 8345: #   Rewrite the contents of the user's passwd file.
 8346: #  Parameters:
 8347: #    domain    - domain of the user.
 8348: #    name      - User's name.
 8349: #    contents  - New contents of the file.
 8350: #    saveold   - (optional). If true save old file in a passwd.bak file.
 8351: # Returns:
 8352: #   0    - Failed.
 8353: #   1    - Success.
 8354: #
 8355: sub rewrite_password_file {
 8356:     my ($domain, $user, $contents, $saveold) = @_;
 8357: 
 8358:     my $file = &password_filename($domain, $user);
 8359:     if (defined $file) {
 8360:         if ($saveold) {
 8361:             my $bakfile = $file.'.bak';
 8362:             if (CopyFile($file,$bakfile)) {
 8363:                 chmod(0400,$bakfile);
 8364:                 &logthis("Old password saved in passwd.bak for internally authenticated user: $user:$domain");
 8365:             } else {
 8366:                 &logthis("Failed to save old password in passwd.bak for internally authenticated user: $user:$domain");
 8367:             }
 8368:         }
 8369: 	my $pf = IO::File->new(">$file");
 8370: 	if($pf) {
 8371: 	    print $pf "$contents\n";
 8372: 	    return 1;
 8373: 	} else {
 8374: 	    return 0;
 8375: 	}
 8376:     } else {
 8377: 	return 0;
 8378:     }
 8379: 
 8380: }
 8381: 
 8382: #
 8383: #   get_auth_type - Determines the authorization type of a user in a domain.
 8384: 
 8385: #     Returns the authorization type or nouser if there is no such user.
 8386: #
 8387: sub get_auth_type {
 8388:     my ($domain, $user)  = @_;
 8389: 
 8390:     Debug("get_auth_type( $domain, $user ) \n");
 8391:     my $proname    = &propath($domain, $user); 
 8392:     my $passwdfile = "$proname/passwd";
 8393:     if( -e $passwdfile ) {
 8394: 	my $pf = IO::File->new($passwdfile);
 8395: 	my $realpassword = <$pf>;
 8396: 	chomp($realpassword);
 8397: 	Debug("Password info = $realpassword\n");
 8398: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
 8399: 	Debug("Authtype = $authtype, content = $contentpwd\n");
 8400: 	return "$authtype:$contentpwd";     
 8401:     } else {
 8402: 	Debug("Returning nouser");
 8403: 	return "nouser";
 8404:     }
 8405: }
 8406: 
 8407: #
 8408: #  Validate a user given their domain, name and password.  This utility
 8409: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
 8410: #  to validate the login credentials of a user.
 8411: # Parameters:
 8412: #    $domain    - The domain being logged into (this is required due to
 8413: #                 the capability for multihomed systems.
 8414: #    $user      - The name of the user being validated.
 8415: #    $password  - The user's propoposed password.
 8416: #
 8417: # Returns:
 8418: #     1        - The domain,user,pasword triplet corresponds to a valid
 8419: #                user.
 8420: #     0        - The domain,user,password triplet is not a valid user.
 8421: #
 8422: sub validate_user {
 8423:     my ($domain, $user, $password, $checkdefauth) = @_;
 8424: 
 8425:     # Why negative ~pi you may well ask?  Well this function is about
 8426:     # authentication, and therefore very important to get right.
 8427:     # I've initialized the flag that determines whether or not I've 
 8428:     # validated correctly to a value it's not supposed to get.
 8429:     # At the end of this function. I'll ensure that it's not still that
 8430:     # value so we don't just wind up returning some accidental value
 8431:     # as a result of executing an unforseen code path that
 8432:     # did not set $validated.  At the end of valid execution paths,
 8433:     # validated shoule be 1 for success or 0 for failuer.
 8434: 
 8435:     my $validated = -3.14159;
 8436: 
 8437:     #  How we authenticate is determined by the type of authentication
 8438:     #  the user has been assigned.  If the authentication type is
 8439:     #  "nouser", the user does not exist so we will return 0.
 8440: 
 8441:     my $contents = &get_auth_type($domain, $user);
 8442:     my ($howpwd, $contentpwd) = split(/:/, $contents);
 8443: 
 8444:     my $null = pack("C",0);	# Used by kerberos auth types.
 8445: 
 8446:     if ($howpwd eq 'nouser') {
 8447:         if ($checkdefauth) {
 8448:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 8449:             if ($domdefaults{'auth_def'} eq 'localauth') {
 8450:                 $howpwd = $domdefaults{'auth_def'};
 8451:                 $contentpwd = $domdefaults{'auth_arg_def'};
 8452:             } elsif ((($domdefaults{'auth_def'} eq 'krb4') || 
 8453:                       ($domdefaults{'auth_def'} eq 'krb5')) &&
 8454:                      ($domdefaults{'auth_arg_def'} ne '')) {
 8455:                 #
 8456:                 # Don't attempt authentication for username and password supplied
 8457:                 # for user without an account if uername contains @ to avoid
 8458:                 # call to &Authen::Krb5::parse_name() which will result in con_lost
 8459:                 #
 8460:                 unless ($user =~ /\@/) {
 8461:                     $howpwd = $domdefaults{'auth_def'};
 8462:                     $contentpwd = $domdefaults{'auth_arg_def'};
 8463:                 }
 8464:             }
 8465:         }
 8466:     }
 8467:     if ($howpwd ne 'nouser') {
 8468: 	if($howpwd eq "internal") { # Encrypted is in local password file.
 8469:             if (length($contentpwd) == 13) {
 8470:                 $validated = (crypt($password,$contentpwd) eq $contentpwd);
 8471:                 if ($validated) {
 8472:                     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 8473:                     if ($domdefaults{'intauth_switch'}) {
 8474:                         my $ncpass = &hash_passwd($domain,$password);
 8475:                         my $saveold;
 8476:                         if ($domdefaults{'intauth_switch'} == 2) {
 8477:                             $saveold = 1;
 8478:                         }
 8479:                         if (&rewrite_password_file($domain,$user,"$howpwd:$ncpass",$saveold)) {
 8480:                             &update_passwd_history($user,$domain,$howpwd,'conversion');
 8481:                             &logthis("Validated password hashed with bcrypt for $user:$domain");
 8482:                         }
 8483:                     }
 8484:                 }
 8485:             } else {
 8486:                 $validated = &check_internal_passwd($password,$contentpwd,$domain,$user);
 8487:             }
 8488: 	}
 8489: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
 8490: 	    $contentpwd = (getpwnam($user))[1];
 8491: 	    if($contentpwd) {
 8492: 		if($contentpwd eq 'x') { # Shadow password file...
 8493: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
 8494: 		    open PWAUTH,  "|$pwauth_path" or
 8495: 			die "Cannot invoke authentication";
 8496: 		    print PWAUTH "$user\n$password\n";
 8497: 		    close PWAUTH;
 8498: 		    $validated = ! $?;
 8499: 
 8500: 		} else { 	         # Passwords in /etc/passwd. 
 8501: 		    $validated = (crypt($password,
 8502: 					$contentpwd) eq $contentpwd);
 8503: 		}
 8504: 	    } else {
 8505: 		$validated = 0;
 8506: 	    }
 8507: 	} elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
 8508:             my $checkwithkrb5 = 0;
 8509:             if ($dist =~/^fedora(\d+)$/) {
 8510:                 if ($1 > 11) {
 8511:                     $checkwithkrb5 = 1;
 8512:                 }
 8513:             } elsif ($dist =~ /^suse([\d.]+)$/) {
 8514:                 if ($1 > 11.1) {
 8515:                     $checkwithkrb5 = 1; 
 8516:                 }
 8517:             }
 8518:             if ($checkwithkrb5) {
 8519:                 $validated = &krb5_authen($password,$null,$user,$contentpwd);
 8520:             } else {
 8521:                 $validated = &krb4_authen($password,$null,$user,$contentpwd);
 8522:             }
 8523: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
 8524:             $validated = &krb5_authen($password,$null,$user,$contentpwd);
 8525: 	} elsif ($howpwd eq "localauth") { 
 8526: 	    #  Authenticate via installation specific authentcation method:
 8527: 	    $validated = &localauth::localauth($user, 
 8528: 					       $password, 
 8529: 					       $contentpwd,
 8530: 					       $domain);
 8531: 	    if ($validated < 0) {
 8532: 		&logthis("localauth for $contentpwd $user:$domain returned a $validated");
 8533: 		$validated = 0;
 8534: 	    }
 8535: 	} else {			# Unrecognized auth is also bad.
 8536: 	    $validated = 0;
 8537: 	}
 8538:     } else {
 8539: 	$validated = 0;
 8540:     }
 8541:     #
 8542:     #  $validated has the correct stat of the authentication:
 8543:     #
 8544: 
 8545:     unless ($validated != -3.14159) {
 8546: 	#  I >really really< want to know if this happens.
 8547: 	#  since it indicates that user authentication is badly
 8548: 	#  broken in some code path.
 8549:         #
 8550: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
 8551:     }
 8552:     return $validated;
 8553: }
 8554: 
 8555: sub check_internal_passwd {
 8556:     my ($plainpass,$stored,$domain,$user) = @_;
 8557:     my (undef,$method,@rest) = split(/!/,$stored);
 8558:     if ($method eq 'bcrypt') {
 8559:         my $result = &hash_passwd($domain,$plainpass,@rest);
 8560:         if ($result ne $stored) {
 8561:             return 0;
 8562:         }
 8563:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 8564:         if ($domdefaults{'intauth_check'}) {
 8565:             # Upgrade to a larger number of rounds if necessary
 8566:             my $defaultcost = $domdefaults{'intauth_cost'};
 8567:             if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
 8568:                 $defaultcost = 10;
 8569:             }
 8570:             if (int($rest[0])<int($defaultcost)) {
 8571:                 if ($domdefaults{'intauth_check'} == 1) { 
 8572:                     my $ncpass = &hash_passwd($domain,$plainpass);
 8573:                     if (&rewrite_password_file($domain,$user,"internal:$ncpass")) {
 8574:                         &update_passwd_history($user,$domain,'internal','update cost');
 8575:                         &logthis("Validated password hashed with bcrypt for $user:$domain");
 8576:                     }
 8577:                     return 1;
 8578:                 } elsif ($domdefaults{'intauth_check'} == 2) {
 8579:                     return 0;
 8580:                 }
 8581:             }
 8582:         } else {
 8583:             return 1;
 8584:         }
 8585:     }
 8586:     return 0;
 8587: }
 8588: 
 8589: sub get_last_authchg {
 8590:     my ($domain,$user) = @_;
 8591:     my $lastmod;
 8592:     my $logname = &propath($domain,$user).'/passwd.log';
 8593:     if (-e "$logname") {
 8594:         $lastmod = (stat("$logname"))[9];
 8595:     }
 8596:     return $lastmod;
 8597: }
 8598: 
 8599: sub krb4_authen {
 8600:     my ($password,$null,$user,$contentpwd) = @_;
 8601:     my $validated = 0;
 8602:     if (!($password =~ /$null/) ) {  # Null password not allowed.
 8603:         eval {
 8604:             require Authen::Krb4;
 8605:         };
 8606:         if (!$@) {
 8607:             my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
 8608:                                                        "",
 8609:                                                        $contentpwd,,
 8610:                                                        'krbtgt',
 8611:                                                        $contentpwd,
 8612:                                                        1,
 8613:                                                        $password);
 8614:             if(!$k4error) {
 8615:                 $validated = 1;
 8616:             } else {
 8617:                 $validated = 0;
 8618:                 &logthis('krb4: '.$user.', '.$contentpwd.', '.
 8619:                           &Authen::Krb4::get_err_txt($Authen::Krb4::error));
 8620:             }
 8621:         } else {
 8622:             $validated = krb5_authen($password,$null,$user,$contentpwd);
 8623:         }
 8624:     }
 8625:     return $validated;
 8626: }
 8627: 
 8628: sub krb5_authen {
 8629:     my ($password,$null,$user,$contentpwd) = @_;
 8630:     my $validated = 0;
 8631:     if(!($password =~ /$null/)) { # Null password not allowed.
 8632:         my $krbclient = &Authen::Krb5::parse_name($user.'@'
 8633:                                                   .$contentpwd);
 8634:         my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
 8635:         my $krbserver  = &Authen::Krb5::parse_name($krbservice);
 8636:         my $credentials= &Authen::Krb5::cc_default();
 8637:         $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
 8638:                                                             .$contentpwd));
 8639:         my $krbreturn;
 8640:         if (exists(&Authen::Krb5::get_init_creds_password)) {
 8641:             $krbreturn =
 8642:                 &Authen::Krb5::get_init_creds_password($krbclient,$password,
 8643:                                                           $krbservice);
 8644:             $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
 8645:         } else {
 8646:             $krbreturn  =
 8647:                 &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
 8648:                                                          $password,$credentials);
 8649:             $validated = ($krbreturn == 1);
 8650:         }
 8651:         if (!$validated) {
 8652:             &logthis('krb5: '.$user.', '.$contentpwd.', '.
 8653:                      &Authen::Krb5::error());
 8654:         }
 8655:     }
 8656:     return $validated;
 8657: }
 8658: 
 8659: sub addline {
 8660:     my ($fname,$hostid,$ip,$newline)=@_;
 8661:     my $contents;
 8662:     my $found=0;
 8663:     my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
 8664:     my $sh;
 8665:     if ($sh=IO::File->new("$fname.subscription")) {
 8666: 	while (my $subline=<$sh>) {
 8667: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
 8668: 	}
 8669: 	$sh->close();
 8670:     }
 8671:     $sh=IO::File->new(">$fname.subscription");
 8672:     if ($contents) { print $sh $contents; }
 8673:     if ($newline) { print $sh $newline; }
 8674:     $sh->close();
 8675:     return $found;
 8676: }
 8677: 
 8678: sub get_chat {
 8679:     my ($cdom,$cname,$udom,$uname,$group)=@_;
 8680: 
 8681:     my @entries=();
 8682:     my $namespace = 'nohist_chatroom';
 8683:     my $namespace_inroom = 'nohist_inchatroom';
 8684:     if ($group ne '') {
 8685:         $namespace .= '_'.$group;
 8686:         $namespace_inroom .= '_'.$group;
 8687:     }
 8688:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
 8689: 				 &GDBM_READER());
 8690:     if ($hashref) {
 8691: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
 8692: 	&untie_user_hash($hashref);
 8693:     }
 8694:     my @participants=();
 8695:     my $cutoff=time-60;
 8696:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
 8697: 			      &GDBM_WRCREAT());
 8698:     if ($hashref) {
 8699:         $hashref->{$uname.':'.$udom}=time;
 8700:         foreach my $user (sort(keys(%$hashref))) {
 8701: 	    if ($hashref->{$user}>$cutoff) {
 8702: 		push(@participants, 'active_participant:'.$user);
 8703:             }
 8704:         }
 8705:         &untie_user_hash($hashref);
 8706:     }
 8707:     return (@participants,@entries);
 8708: }
 8709: 
 8710: sub chat_add {
 8711:     my ($cdom,$cname,$newchat,$group)=@_;
 8712:     my @entries=();
 8713:     my $time=time;
 8714:     my $namespace = 'nohist_chatroom';
 8715:     my $logfile = 'chatroom.log';
 8716:     if ($group ne '') {
 8717:         $namespace .= '_'.$group;
 8718:         $logfile = 'chatroom_'.$group.'.log';
 8719:     }
 8720:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
 8721: 				 &GDBM_WRCREAT());
 8722:     if ($hashref) {
 8723: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
 8724: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
 8725: 	my ($thentime,$idnum)=split(/\_/,$lastid);
 8726: 	my $newid=$time.'_000000';
 8727: 	if ($thentime==$time) {
 8728: 	    $idnum=~s/^0+//;
 8729: 	    $idnum++;
 8730: 	    $idnum=substr('000000'.$idnum,-6,6);
 8731: 	    $newid=$time.'_'.$idnum;
 8732: 	}
 8733: 	$hashref->{$newid}=$newchat;
 8734: 	my $expired=$time-3600;
 8735: 	foreach my $comment (keys(%$hashref)) {
 8736: 	    my ($thistime) = ($comment=~/(\d+)\_/);
 8737: 	    if ($thistime<$expired) {
 8738: 		delete $hashref->{$comment};
 8739: 	    }
 8740: 	}
 8741: 	{
 8742: 	    my $proname=&propath($cdom,$cname);
 8743: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
 8744: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
 8745: 	    }
 8746: 	    close(CHATLOG);
 8747: 	}
 8748: 	&untie_user_hash($hashref);
 8749:     }
 8750: }
 8751: 
 8752: sub unsub {
 8753:     my ($fname,$clientip)=@_;
 8754:     my $result;
 8755:     my $unsubs = 0;		# Number of successful unsubscribes:
 8756: 
 8757: 
 8758:     # An old way subscriptions were handled was to have a 
 8759:     # subscription marker file:
 8760: 
 8761:     Debug("Attempting unlink of $fname.$clientname");
 8762:     if (unlink("$fname.$clientname")) {
 8763: 	$unsubs++;		# Successful unsub via marker file.
 8764:     } 
 8765: 
 8766:     # The more modern way to do it is to have a subscription list
 8767:     # file:
 8768: 
 8769:     if (-e "$fname.subscription") {
 8770: 	my $found=&addline($fname,$clientname,$clientip,'');
 8771: 	if ($found) { 
 8772: 	    $unsubs++;
 8773: 	}
 8774:     } 
 8775: 
 8776:     #  If either or both of these mechanisms succeeded in unsubscribing a 
 8777:     #  resource we can return ok:
 8778: 
 8779:     if($unsubs) {
 8780: 	$result = "ok\n";
 8781:     } else {
 8782: 	$result = "not_subscribed\n";
 8783:     }
 8784: 
 8785:     return $result;
 8786: }
 8787: 
 8788: sub currentversion {
 8789:     my $fname=shift;
 8790:     my $version=-1;
 8791:     my $ulsdir='';
 8792:     if ($fname=~/^(.+)\/[^\/]+$/) {
 8793:        $ulsdir=$1;
 8794:     }
 8795:     my ($fnamere1,$fnamere2);
 8796:     # remove version if already specified
 8797:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
 8798:     # get the bits that go before and after the version number
 8799:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
 8800: 	$fnamere1=$1;
 8801: 	$fnamere2='.'.$2;
 8802:     }
 8803:     if (-e $fname) { $version=1; }
 8804:     if (-e $ulsdir) {
 8805: 	if(-d $ulsdir) {
 8806: 	    if (opendir(LSDIR,$ulsdir)) {
 8807: 		my $ulsfn;
 8808: 		while ($ulsfn=readdir(LSDIR)) {
 8809: # see if this is a regular file (ignore links produced earlier)
 8810: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
 8811: 		    unless (-l $thisfile) {
 8812: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
 8813: 			    if ($1>$version) { $version=$1; }
 8814: 			}
 8815: 		    }
 8816: 		}
 8817: 		closedir(LSDIR);
 8818: 		$version++;
 8819: 	    }
 8820: 	}
 8821:     }
 8822:     return $version;
 8823: }
 8824: 
 8825: sub thisversion {
 8826:     my $fname=shift;
 8827:     my $version=-1;
 8828:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
 8829: 	$version=$1;
 8830:     }
 8831:     return $version;
 8832: }
 8833: 
 8834: sub subscribe {
 8835:     my ($userinput,$clientip)=@_;
 8836:     my $result;
 8837:     my ($cmd,$fname)=split(/:/,$userinput,2);
 8838:     my $ownership=&ishome($fname);
 8839:     if ($ownership eq 'owner') {
 8840: # explitly asking for the current version?
 8841:         unless (-e $fname) {
 8842:             my $currentversion=&currentversion($fname);
 8843: 	    if (&thisversion($fname)==$currentversion) {
 8844:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
 8845: 		    my $root=$1;
 8846:                     my $extension=$2;
 8847:                     symlink($root.'.'.$extension,
 8848:                             $root.'.'.$currentversion.'.'.$extension);
 8849:                     unless ($extension=~/\.meta$/) {
 8850:                        symlink($root.'.'.$extension.'.meta',
 8851:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
 8852: 		    }
 8853:                 }
 8854:             }
 8855:         }
 8856: 	if (-e $fname) {
 8857: 	    if (-d $fname) {
 8858: 		$result="directory\n";
 8859: 	    } else {
 8860: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
 8861: 		my $now=time;
 8862: 		my $found=&addline($fname,$clientname,$clientip,
 8863: 				   "$clientname:$clientip:$now\n");
 8864: 		if ($found) { $result="$fname\n"; }
 8865: 		# if they were subscribed to only meta data, delete that
 8866:                 # subscription, when you subscribe to a file you also get
 8867:                 # the metadata
 8868: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
 8869: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
 8870:                 my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
 8871:                 $protocol = 'http' if ($protocol ne 'https');
 8872: 		$fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
 8873: 		$result="$fname\n";
 8874: 	    }
 8875: 	} else {
 8876: 	    $result="not_found\n";
 8877: 	}
 8878:     } else {
 8879: 	$result="rejected\n";
 8880:     }
 8881:     return $result;
 8882: }
 8883: #  Change the passwd of a unix user.  The caller must have
 8884: #  first verified that the user is a loncapa user.
 8885: #
 8886: # Parameters:
 8887: #    user      - Unix user name to change.
 8888: #    pass      - New password for the user.
 8889: # Returns:
 8890: #    ok    - if success
 8891: #    other - Some meaningfule error message string.
 8892: # NOTE:
 8893: #    invokes a setuid script to change the passwd.
 8894: sub change_unix_password {
 8895:     my ($user, $pass) = @_;
 8896: 
 8897:     &Debug("change_unix_password");
 8898:     my $execdir=$perlvar{'lonDaemons'};
 8899:     &Debug("Opening lcpasswd pipeline");
 8900:     my $pf = IO::File->new("|$execdir/lcpasswd > "
 8901: 			   ."$perlvar{'lonDaemons'}"
 8902: 			   ."/logs/lcpasswd.log");
 8903:     print $pf "$user\n$pass\n$pass\n";
 8904:     close $pf;
 8905:     my $err = $?;
 8906:     return ($err < @passwderrors) ? $passwderrors[$err] : 
 8907: 	"pwchange_falure - unknown error";
 8908: 
 8909:     
 8910: }
 8911: 
 8912: 
 8913: sub make_passwd_file {
 8914:     my ($uname,$udom,$umode,$npass,$passfilename,$action)=@_;
 8915:     my $result="ok";
 8916:     if ($umode eq 'krb4' or $umode eq 'krb5') {
 8917: 	{
 8918: 	    my $pf = IO::File->new(">$passfilename");
 8919: 	    if ($pf) {
 8920: 		print $pf "$umode:$npass\n";
 8921:                 &update_passwd_history($uname,$udom,$umode,$action);
 8922: 	    } else {
 8923: 		$result = "pass_file_failed_error";
 8924: 	    }
 8925: 	}
 8926:     } elsif ($umode eq 'internal') {
 8927:         my $ncpass = &hash_passwd($udom,$npass);
 8928: 	{
 8929: 	    &Debug("Creating internal auth");
 8930: 	    my $pf = IO::File->new(">$passfilename");
 8931: 	    if($pf) {
 8932: 		print $pf "internal:$ncpass\n";
 8933:                 &update_passwd_history($uname,$udom,$umode,$action); 
 8934: 	    } else {
 8935: 		$result = "pass_file_failed_error";
 8936: 	    }
 8937: 	}
 8938:     } elsif ($umode eq 'localauth') {
 8939: 	{
 8940: 	    my $pf = IO::File->new(">$passfilename");
 8941: 	    if($pf) {
 8942: 		print $pf "localauth:$npass\n";
 8943:                 &update_passwd_history($uname,$udom,$umode,$action);
 8944: 	    } else {
 8945: 		$result = "pass_file_failed_error";
 8946: 	    }
 8947: 	}
 8948:     } elsif ($umode eq 'unix') {
 8949: 	&logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
 8950: 	$result="no_new_unix_accounts";
 8951:     } elsif ($umode eq 'none') {
 8952: 	{
 8953: 	    my $pf = IO::File->new("> $passfilename");
 8954: 	    if($pf) {
 8955: 		print $pf "none:\n";
 8956: 	    } else {
 8957: 		$result = "pass_file_failed_error";
 8958: 	    }
 8959: 	}
 8960:     } elsif ($umode eq 'lti') {
 8961:         my $pf = IO::File->new(">$passfilename");
 8962:         if($pf) {
 8963:             print $pf "lti:\n";
 8964:             &update_passwd_history($uname,$udom,$umode,$action);
 8965:         } else {
 8966:             $result = "pass_file_failed_error";
 8967:         }
 8968:     } else {
 8969: 	$result="auth_mode_error";
 8970:     }
 8971:     return $result;
 8972: }
 8973: 
 8974: sub convert_photo {
 8975:     my ($start,$dest)=@_;
 8976:     system("convert $start $dest");
 8977: }
 8978: 
 8979: sub sethost {
 8980:     my ($remotereq) = @_;
 8981:     my (undef,$hostid)=split(/:/,$remotereq);
 8982:     # ignore sethost if we are already correct
 8983:     if ($hostid eq $currenthostid) {
 8984: 	return 'ok';
 8985:     }
 8986: 
 8987:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
 8988:     if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'}) 
 8989: 	eq &Apache::lonnet::get_host_ip($hostid)) {
 8990: 	$currenthostid  =$hostid;
 8991: 	$currentdomainid=&Apache::lonnet::host_domain($hostid);
 8992:         &set_client_info();
 8993: #	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
 8994:     } else {
 8995: 	&logthis("Requested host id $hostid not an alias of ".
 8996: 		 $perlvar{'lonHostID'}." refusing connection");
 8997: 	return 'unable_to_set';
 8998:     }
 8999:     return 'ok';
 9000: }
 9001: 
 9002: sub version {
 9003:     my ($userinput)=@_;
 9004:     $remoteVERSION=(split(/:/,$userinput))[1];
 9005:     return "version:$VERSION";
 9006: }
 9007: 
 9008: sub get_usersession_config {
 9009:     my ($dom,$name) = @_;
 9010:     my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
 9011:     if (defined($cached)) {
 9012:         return $usersessionconf;
 9013:     } else {
 9014:         my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
 9015:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
 9016:         return $domconfig{'usersessions'};
 9017:     }
 9018:     return;
 9019: }
 9020: 
 9021: sub get_usersearch_config {
 9022:     my ($dom,$name) = @_;
 9023:     my ($usersearchconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
 9024:     if (defined($cached)) {
 9025:         return $usersearchconf;
 9026:     } else {
 9027:         my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$dom);
 9028:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'directorysrch'},600);
 9029:         return $domconfig{'directorysrch'};
 9030:     }
 9031:     return;
 9032: }
 9033: 
 9034: sub get_prohibited {
 9035:     my ($dom) = @_;
 9036:     my $name = 'trust';
 9037:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
 9038:     unless (defined($cached)) {
 9039:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$dom);
 9040:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'trust'},3600);
 9041:         $trustconfig = $domconfig{'trust'};
 9042:     }
 9043:     my %prohibited;
 9044:     if (ref($trustconfig)) {
 9045:         foreach my $prefix (keys(%{$trustconfig})) {
 9046:             if (ref($trustconfig->{$prefix}) eq 'HASH') {
 9047:                 my $reject;
 9048:                 if (ref($trustconfig->{$prefix}->{'exc'}) eq 'ARRAY') {
 9049:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'exc'}})) {
 9050:                         $reject = 1;
 9051:                     }
 9052:                 }
 9053:                 if (ref($trustconfig->{$prefix}->{'inc'}) eq 'ARRAY') {
 9054:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'inc'}})) {
 9055:                         $reject = 0;
 9056:                     } else {
 9057:                         $reject = 1;
 9058:                     }
 9059:                 }
 9060:                 if ($reject) {
 9061:                     $prohibited{$prefix} = 1;
 9062:                 }
 9063:             }
 9064:         }
 9065:     }
 9066:     return %prohibited;
 9067: }
 9068: 
 9069: sub get_remote_hostable {
 9070:     my ($dom) = @_;
 9071:     my $result;
 9072:     if ($clientintdom) {
 9073:         $result = 1;
 9074:         my $remsessconf = &get_usersession_config($dom,'remotesession');
 9075:         if (ref($remsessconf) eq 'HASH') {
 9076:             if (ref($remsessconf->{'remote'}) eq 'HASH') {
 9077:                 if (ref($remsessconf->{'remote'}->{'excludedomain'}) eq 'ARRAY') {
 9078:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'excludedomain'}})) {
 9079:                         $result = 0;
 9080:                     }
 9081:                 }
 9082:                 if (ref($remsessconf->{'remote'}->{'includedomain'}) eq 'ARRAY') {
 9083:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'includedomain'}})) {
 9084:                         $result = 1;
 9085:                     } else {
 9086:                         $result = 0;
 9087:                     }
 9088:                 }
 9089:             }
 9090:         }
 9091:     }
 9092:     return $result;
 9093: }
 9094: 
 9095: sub distro_and_arch {
 9096:     return $dist.':'.$arch;
 9097: }
 9098: 
 9099: # ----------------------------------- POD (plain old documentation, CPAN style)
 9100: 
 9101: =head1 NAME
 9102: 
 9103: lond - "LON Daemon" Server (port "LOND" 5663)
 9104: 
 9105: =head1 SYNOPSIS
 9106: 
 9107: Usage: B<lond>
 9108: 
 9109: Should only be run as user=www.  This is a command-line script which
 9110: is invoked by B<loncron>.  There is no expectation that a typical user
 9111: will manually start B<lond> from the command-line.  (In other words,
 9112: DO NOT START B<lond> YOURSELF.)
 9113: 
 9114: =head1 DESCRIPTION
 9115: 
 9116: There are two characteristics associated with the running of B<lond>,
 9117: PROCESS MANAGEMENT (starting, stopping, handling child processes)
 9118: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
 9119: subscriptions, etc).  These are described in two large
 9120: sections below.
 9121: 
 9122: B<PROCESS MANAGEMENT>
 9123: 
 9124: Preforker - server who forks first. Runs as a daemon. HUPs.
 9125: Uses IDEA encryption
 9126: 
 9127: B<lond> forks off children processes that correspond to the other servers
 9128: in the network.  Management of these processes can be done at the
 9129: parent process level or the child process level.
 9130: 
 9131: B<logs/lond.log> is the location of log messages.
 9132: 
 9133: The process management is now explained in terms of linux shell commands,
 9134: subroutines internal to this code, and signal assignments:
 9135: 
 9136: =over 4
 9137: 
 9138: =item *
 9139: 
 9140: PID is stored in B<logs/lond.pid>
 9141: 
 9142: This is the process id number of the parent B<lond> process.
 9143: 
 9144: =item *
 9145: 
 9146: SIGTERM and SIGINT
 9147: 
 9148: Parent signal assignment:
 9149:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 9150: 
 9151: Child signal assignment:
 9152:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
 9153: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
 9154:  to restart a new child.)
 9155: 
 9156: Command-line invocations:
 9157:  B<kill> B<-s> SIGTERM I<PID>
 9158:  B<kill> B<-s> SIGINT I<PID>
 9159: 
 9160: Subroutine B<HUNTSMAN>:
 9161:  This is only invoked for the B<lond> parent I<PID>.
 9162: This kills all the children, and then the parent.
 9163: The B<lonc.pid> file is cleared.
 9164: 
 9165: =item *
 9166: 
 9167: SIGHUP
 9168: 
 9169: Current bug:
 9170:  This signal can only be processed the first time
 9171: on the parent process.  Subsequent SIGHUP signals
 9172: have no effect.
 9173: 
 9174: Parent signal assignment:
 9175:  $SIG{HUP}  = \&HUPSMAN;
 9176: 
 9177: Child signal assignment:
 9178:  none (nothing happens)
 9179: 
 9180: Command-line invocations:
 9181:  B<kill> B<-s> SIGHUP I<PID>
 9182: 
 9183: Subroutine B<HUPSMAN>:
 9184:  This is only invoked for the B<lond> parent I<PID>,
 9185: This kills all the children, and then the parent.
 9186: The B<lond.pid> file is cleared.
 9187: 
 9188: =item *
 9189: 
 9190: SIGUSR1
 9191: 
 9192: Parent signal assignment:
 9193:  $SIG{USR1} = \&USRMAN;
 9194: 
 9195: Child signal assignment:
 9196:  $SIG{USR1}= \&logstatus;
 9197: 
 9198: Command-line invocations:
 9199:  B<kill> B<-s> SIGUSR1 I<PID>
 9200: 
 9201: Subroutine B<USRMAN>:
 9202:  When invoked for the B<lond> parent I<PID>,
 9203: SIGUSR1 is sent to all the children, and the status of
 9204: each connection is logged.
 9205: 
 9206: =item *
 9207: 
 9208: SIGUSR2
 9209: 
 9210: Parent Signal assignment:
 9211:     $SIG{USR2} = \&UpdateHosts
 9212: 
 9213: Child signal assignment:
 9214:     NONE
 9215: 
 9216: 
 9217: =item *
 9218: 
 9219: SIGCHLD
 9220: 
 9221: Parent signal assignment:
 9222:  $SIG{CHLD} = \&REAPER;
 9223: 
 9224: Child signal assignment:
 9225:  none
 9226: 
 9227: Command-line invocations:
 9228:  B<kill> B<-s> SIGCHLD I<PID>
 9229: 
 9230: Subroutine B<REAPER>:
 9231:  This is only invoked for the B<lond> parent I<PID>.
 9232: Information pertaining to the child is removed.
 9233: The socket port is cleaned up.
 9234: 
 9235: =back
 9236: 
 9237: B<SERVER-SIDE ACTIVITIES>
 9238: 
 9239: Server-side information can be accepted in an encrypted or non-encrypted
 9240: method.
 9241: 
 9242: =over 4
 9243: 
 9244: =item ping
 9245: 
 9246: Query a client in the hosts.tab table; "Are you there?"
 9247: 
 9248: =item pong
 9249: 
 9250: Respond to a ping query.
 9251: 
 9252: =item ekey
 9253: 
 9254: Read in encrypted key, make cipher.  Respond with a buildkey.
 9255: 
 9256: =item load
 9257: 
 9258: Respond with CPU load based on a computation upon /proc/loadavg.
 9259: 
 9260: =item currentauth
 9261: 
 9262: Reply with current authentication information (only over an
 9263: encrypted channel).
 9264: 
 9265: =item auth
 9266: 
 9267: Only over an encrypted channel, reply as to whether a user's
 9268: authentication information can be validated.
 9269: 
 9270: =item passwd
 9271: 
 9272: Allow for a password to be set.
 9273: 
 9274: =item makeuser
 9275: 
 9276: Make a user.
 9277: 
 9278: =item changeuserauth
 9279: 
 9280: Allow for authentication mechanism and password to be changed.
 9281: 
 9282: =item home
 9283: 
 9284: Respond to a question "are you the home for a given user?"
 9285: 
 9286: =item update
 9287: 
 9288: Update contents of a subscribed resource.
 9289: 
 9290: =item unsubscribe
 9291: 
 9292: The server is unsubscribing from a resource.
 9293: 
 9294: =item subscribe
 9295: 
 9296: The server is subscribing to a resource.
 9297: 
 9298: =item log
 9299: 
 9300: Place in B<logs/lond.log>
 9301: 
 9302: =item put
 9303: 
 9304: stores hash in namespace
 9305: 
 9306: =item rolesput
 9307: 
 9308: put a role into a user's environment
 9309: 
 9310: =item get
 9311: 
 9312: returns hash with keys from array
 9313: reference filled in from namespace
 9314: 
 9315: =item eget
 9316: 
 9317: returns hash with keys from array
 9318: reference filled in from namesp (encrypts the return communication)
 9319: 
 9320: =item rolesget
 9321: 
 9322: get a role from a user's environment
 9323: 
 9324: =item del
 9325: 
 9326: deletes keys out of array from namespace
 9327: 
 9328: =item keys
 9329: 
 9330: returns namespace keys
 9331: 
 9332: =item dump
 9333: 
 9334: dumps the complete (or key matching regexp) namespace into a hash
 9335: 
 9336: =item store
 9337: 
 9338: stores hash permanently
 9339: for this url; hashref needs to be given and should be a \%hashname; the
 9340: remaining args aren't required and if they aren't passed or are '' they will
 9341: be derived from the ENV
 9342: 
 9343: =item restore
 9344: 
 9345: returns a hash for a given url
 9346: 
 9347: =item querysend
 9348: 
 9349: Tells client about the lonsql process that has been launched in response
 9350: to a sent query.
 9351: 
 9352: =item queryreply
 9353: 
 9354: Accept information from lonsql and make appropriate storage in temporary
 9355: file space.
 9356: 
 9357: =item idput
 9358: 
 9359: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
 9360: for each student, defined perhaps by the institutional Registrar.)
 9361: 
 9362: =item idget
 9363: 
 9364: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
 9365: for each student, defined perhaps by the institutional Registrar.)
 9366: 
 9367: =item iddel
 9368: 
 9369: Deletes one or more ids in a domain's id database.
 9370: 
 9371: =item tmpput
 9372: 
 9373: Accept and store information in temporary space.
 9374: 
 9375: =item tmpget
 9376: 
 9377: Send along temporarily stored information.
 9378: 
 9379: =item ls
 9380: 
 9381: List part of a user's directory.
 9382: 
 9383: =item pushtable
 9384: 
 9385: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
 9386: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
 9387: must be restored manually in case of a problem with the new table file.
 9388: pushtable requires that the request be encrypted and validated via
 9389: ValidateManager.  The form of the command is:
 9390: enc:pushtable tablename <tablecontents> \n
 9391: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
 9392: cleartext newline.
 9393: 
 9394: =item Hanging up (exit or init)
 9395: 
 9396: What to do when a client tells the server that they (the client)
 9397: are leaving the network.
 9398: 
 9399: =item unknown command
 9400: 
 9401: If B<lond> is sent an unknown command (not in the list above),
 9402: it replys to the client "unknown_cmd".
 9403: 
 9404: 
 9405: =item UNKNOWN CLIENT
 9406: 
 9407: If the anti-spoofing algorithm cannot verify the client,
 9408: the client is rejected (with a "refused" message sent
 9409: to the client, and the connection is closed.
 9410: 
 9411: =back
 9412: 
 9413: =head1 PREREQUISITES
 9414: 
 9415: IO::Socket
 9416: IO::File
 9417: Apache::File
 9418: POSIX
 9419: Crypt::IDEA
 9420: GDBM_File
 9421: Authen::Krb4
 9422: Authen::Krb5
 9423: 
 9424: =head1 COREQUISITES
 9425: 
 9426: none
 9427: 
 9428: =head1 OSNAMES
 9429: 
 9430: linux
 9431: 
 9432: =head1 SCRIPT CATEGORIES
 9433: 
 9434: Server/Process
 9435: 
 9436: =cut
 9437: 
 9438: 
 9439: =pod
 9440: 
 9441: =head1 LOG MESSAGES
 9442: 
 9443: The messages below can be emitted in the lond log.  This log is located
 9444: in ~httpd/perl/logs/lond.log  Many log messages have HTML encapsulation
 9445: to provide coloring if examined from inside a web page. Some do not.
 9446: Where color is used, the colors are; Red for sometihhng to get excited
 9447: about and to follow up on. Yellow for something to keep an eye on to
 9448: be sure it does not get worse, Green,and Blue for informational items.
 9449: 
 9450: In the discussions below, sometimes reference is made to ~httpd
 9451: when describing file locations.  There isn't really an httpd 
 9452: user, however there is an httpd directory that gets installed in the
 9453: place that user home directories go.  On linux, this is usually
 9454: (always?) /home/httpd.
 9455: 
 9456: 
 9457: Some messages are colorless.  These are usually (not always)
 9458: Green/Blue color level messages.
 9459: 
 9460: =over 2
 9461: 
 9462: =item (Red)  LocalConnection rejecting non local: <ip> ne 127.0.0.1
 9463: 
 9464: A local connection negotiation was attempted by
 9465: a host whose IP address was not 127.0.0.1.
 9466: The socket is closed and the child will exit.
 9467: lond has three ways to establish an encyrption
 9468: key with a client:
 9469: 
 9470: =over 2
 9471: 
 9472: =item local 
 9473: 
 9474: The key is written and read from a file.
 9475: This is only valid for connections from localhost.
 9476: 
 9477: =item insecure 
 9478: 
 9479: The key is generated by the server and
 9480: transmitted to the client.
 9481: 
 9482: =item  ssl (secure)
 9483: 
 9484: An ssl connection is negotiated with the client,
 9485: the key is generated by the server and sent to the 
 9486: client across this ssl connection before the
 9487: ssl connectionis terminated and clear text
 9488: transmission resumes.
 9489: 
 9490: =back
 9491: 
 9492: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
 9493: 
 9494: The client is local but has not sent an initialization
 9495: string that is the literal "init:local"  The connection
 9496: is closed and the child exits.
 9497: 
 9498: =item Red CRITICAL Can't get key file <error>        
 9499: 
 9500: SSL key negotiation is being attempted but the call to
 9501: lonssl::KeyFile failed.  This usually means that the
 9502: configuration file is not correctly defining or protecting
 9503: the directories/files lonCertificateDirectory or
 9504: lonnetPrivateKey
 9505: <error> is a string that describes the reason that
 9506: the key file could not be located.
 9507: 
 9508: =item (Red) CRITICAL  Can't get certificates <error>  
 9509: 
 9510: SSL key negotiation failed because we were not able to retrives our certificate
 9511: or the CA's certificate in the call to lonssl::CertificateFile
 9512: <error> is the textual reason this failed.  Usual reasons:
 9513: 
 9514: =over 2
 9515: 
 9516: =item Apache config file for loncapa  incorrect:
 9517: 
 9518: one of the variables 
 9519: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
 9520: undefined or incorrect
 9521: 
 9522: =item Permission error:
 9523: 
 9524: The directory pointed to by lonCertificateDirectory is not readable by lond
 9525: 
 9526: =item Permission error:
 9527: 
 9528: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
 9529: 
 9530: =item Installation error:                         
 9531: 
 9532: Either the certificate authority file or the certificate have not
 9533: been installed in lonCertificateDirectory.
 9534: 
 9535: =item (Red) CRITICAL SSL Socket promotion failed:  <err> 
 9536: 
 9537: The promotion of the connection from plaintext to SSL failed
 9538: <err> is the reason for the failure.  There are two
 9539: system calls involved in the promotion (one of which failed), 
 9540: a dup to produce
 9541: a second fd on the raw socket over which the encrypted data
 9542: will flow and IO::SOcket::SSL->new_from_fd which creates
 9543: the SSL connection on the duped fd.
 9544: 
 9545: =item (Blue)   WARNING client did not respond to challenge 
 9546: 
 9547: This occurs on an insecure (non SSL) connection negotiation request.
 9548: lond generates some number from the time, the PID and sends it to
 9549: the client.  The client must respond by echoing this information back.
 9550: If the client does not do so, that's a violation of the challenge
 9551: protocols and the connection will be failed.
 9552: 
 9553: =item (Red) No manager table. Nobody can manage!!    
 9554: 
 9555: lond has the concept of privileged hosts that
 9556: can perform remote management function such
 9557: as update the hosts.tab.   The manager hosts
 9558: are described in the 
 9559: ~httpd/lonTabs/managers.tab file.
 9560: this message is logged if this file is missing.
 9561: 
 9562: 
 9563: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
 9564: 
 9565: Reports the successful parse and registration
 9566: of a specific manager. 
 9567: 
 9568: =item Green existing host <clustername:dnsname>  
 9569: 
 9570: The manager host is already defined in the hosts.tab
 9571: the information in that table, rather than the info in the
 9572: manager table will be used to determine the manager's ip.
 9573: 
 9574: =item (Red) Unable to craete <filename>                 
 9575: 
 9576: lond has been asked to create new versions of an administrative
 9577: file (by a manager).  When this is done, the new file is created
 9578: in a temp file and then renamed into place so that there are always
 9579: usable administrative files, even if the update fails.  This failure
 9580: message means that the temp file could not be created.
 9581: The update is abandoned, and the old file is available for use.
 9582: 
 9583: =item (Green) CopyFile from <oldname> to <newname> failed
 9584: 
 9585: In an update of administrative files, the copy of the existing file to a
 9586: backup file failed.  The installation of the new file may still succeed,
 9587: but there will not be a back up file to rever to (this should probably
 9588: be yellow).
 9589: 
 9590: =item (Green) Pushfile: backed up <oldname> to <newname>
 9591: 
 9592: See above, the backup of the old administrative file succeeded.
 9593: 
 9594: =item (Red)  Pushfile: Unable to install <filename> <reason>
 9595: 
 9596: The new administrative file could not be installed.  In this case,
 9597: the old administrative file is still in use.
 9598: 
 9599: =item (Green) Installed new < filename>.                      
 9600: 
 9601: The new administrative file was successfullly installed.                                               
 9602: 
 9603: =item (Red) Reinitializing lond pid=<pid>                    
 9604: 
 9605: The lonc child process <pid> will be sent a USR2 
 9606: signal.
 9607: 
 9608: =item (Red) Reinitializing self                                    
 9609: 
 9610: We've been asked to re-read our administrative files,and
 9611: are doing so.
 9612: 
 9613: =item (Yellow) error:Invalid process identifier <ident>  
 9614: 
 9615: A reinit command was received, but the target part of the 
 9616: command was not valid.  It must be either
 9617: 'lond' or 'lonc' but was <ident>
 9618: 
 9619: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
 9620: 
 9621: Checking to see if lond has been handed a valid edit
 9622: command.  It is possible the edit command is not valid
 9623: in that case there are no log messages to indicate that.
 9624: 
 9625: =item Result of password change for  <username> pwchange_success
 9626: 
 9627: The password for <username> was
 9628: successfully changed.
 9629: 
 9630: =item Unable to open <user> passwd to change password
 9631: 
 9632: Could not rewrite the 
 9633: internal password file for a user
 9634: 
 9635: =item Result of password change for <user> : <result>
 9636: 
 9637: A unix password change for <user> was attempted 
 9638: and the pipe returned <result>  
 9639: 
 9640: =item LWP GET: <message> for <fname> (<remoteurl>)
 9641: 
 9642: The lightweight process fetch for a resource failed
 9643: with <message> the local filename that should
 9644: have existed/been created was  <fname> the
 9645: corresponding URI: <remoteurl>  This is emitted in several
 9646: places.
 9647: 
 9648: =item Unable to move <transname> to <destname>     
 9649: 
 9650: From fetch_user_file_handler - the user file was replicated but could not
 9651: be mv'd to its final location.
 9652: 
 9653: =item Looking for <domain> <username>              
 9654: 
 9655: From user_has_session_handler - This should be a Debug call instead
 9656: it indicates lond is about to check whether the specified user has a 
 9657: session active on the specified domain on the local host.
 9658: 
 9659: =item Client <ip> (<name>) hanging up: <input>     
 9660: 
 9661: lond has been asked to exit by its client.  The <ip> and <name> identify the
 9662: client systemand <input> is the full exit command sent to the server.
 9663: 
 9664: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
 9665: 
 9666: A lond child terminated.  NOte that this termination can also occur when the
 9667: child receives the QUIT or DIE signals.  <pid> is the process id of the child,
 9668: <hostname> the host lond is working for, and <message> the reason the child died
 9669: to the best of our ability to get it (I would guess that any numeric value
 9670: represents and errno value).  This is immediately followed by
 9671: 
 9672: =item  Famous last words: Catching exception - <log> 
 9673: 
 9674: Where log is some recent information about the state of the child.
 9675: 
 9676: =item Red CRITICAL: TIME OUT <pid>                     
 9677: 
 9678: Some timeout occured for server <pid>.  THis is normally a timeout on an LWP
 9679: doing an HTTP::GET.
 9680: 
 9681: =item child <pid> died                              
 9682: 
 9683: The reaper caught a SIGCHILD for the lond child process <pid>
 9684: This should be modified to also display the IP of the dying child
 9685: $children{$pid}
 9686: 
 9687: =item Unknown child 0 died                           
 9688: A child died but the wait for it returned a pid of zero which really should not
 9689: ever happen. 
 9690: 
 9691: =item Child <which> - <pid> looks like we missed it's death 
 9692: 
 9693: When a sigchild is received, the reaper process checks all children to see if they are
 9694: alive.  If children are dying quite quickly, the lack of signal queuing can mean
 9695: that a signal hearalds the death of more than one child.  If so this message indicates
 9696: which other one died. <which> is the ip of a dead child
 9697: 
 9698: =item Free socket: <shutdownretval>                
 9699: 
 9700: The HUNTSMAN sub was called due to a SIGINT in a child process.  The socket is being shutdown.
 9701: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
 9702: to return anything. This is followed by: 
 9703: 
 9704: =item Red CRITICAL: Shutting down                       
 9705: 
 9706: Just prior to exit.
 9707: 
 9708: =item Free socket: <shutdownretval>                 
 9709: 
 9710: The HUPSMAN sub was called due to a SIGHUP.  all children get killsed, and lond execs itself.
 9711: This is followed by:
 9712: 
 9713: =item (Red) CRITICAL: Restarting                         
 9714: 
 9715: lond is about to exec itself to restart.
 9716: 
 9717: =item (Blue) Updating connections                        
 9718: 
 9719: (In response to a USR2).  All the children (except the one for localhost)
 9720: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
 9721: 
 9722: =item (Blue) UpdateHosts killing child <pid> for ip <ip>   
 9723: 
 9724: Due to USR2 as above.
 9725: 
 9726: =item (Green) keeping child for ip <ip> (pid = <pid>)    
 9727: 
 9728: In response to USR2 as above, the child indicated is not being restarted because
 9729: it's assumed that we'll always need a child for the localhost.
 9730: 
 9731: 
 9732: =item Going to check on the children                
 9733: 
 9734: Parent is about to check on the health of the child processes.
 9735: Note that this is in response to a USR1 sent to the parent lond.
 9736: there may be one or more of the next two messages:
 9737: 
 9738: =item <pid> is dead                                 
 9739: 
 9740: A child that we have in our child hash as alive has evidently died.
 9741: 
 9742: =item  Child <pid> did not respond                   
 9743: 
 9744: In the health check the child <pid> did not update/produce a pid_.txt
 9745: file when sent it's USR1 signal.  That process is killed with a 9 signal, as it's
 9746: assumed to be hung in some un-fixable way.
 9747: 
 9748: =item Finished checking children                   
 9749: 
 9750: Master processs's USR1 processing is cojmplete.
 9751: 
 9752: =item (Red) CRITICAL: ------- Starting ------            
 9753: 
 9754: (There are more '-'s on either side).  Lond has forked itself off to 
 9755: form a new session and is about to start actual initialization.
 9756: 
 9757: =item (Green) Attempting to start child (<client>)       
 9758: 
 9759: Started a new child process for <client>.  Client is IO::Socket object
 9760: connected to the child.  This was as a result of a TCP/IP connection from a client.
 9761: 
 9762: =item Unable to determine who caller was, getpeername returned nothing
 9763: 
 9764: In child process initialization.  either getpeername returned undef or
 9765: a zero sized object was returned.  Processing continues, but in my opinion,
 9766: this should be cause for the child to exit.
 9767: 
 9768: =item Unable to determine clientip                  
 9769: 
 9770: In child process initialization.  The peer address from getpeername was not defined.
 9771: The client address is stored as "Unavailable" and processing continues.
 9772: 
 9773: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
 9774: 
 9775: In child initialization.  A good connectionw as received from <ip>.
 9776: 
 9777: =over 2
 9778: 
 9779: =item <name> 
 9780: 
 9781: is the name of the client from hosts.tab.
 9782: 
 9783: =item <type> 
 9784: 
 9785: Is the connection type which is either 
 9786: 
 9787: =over 2
 9788: 
 9789: =item manager 
 9790: 
 9791: The connection is from a manager node, not in hosts.tab
 9792: 
 9793: =item client  
 9794: 
 9795: the connection is from a non-manager in the hosts.tab
 9796: 
 9797: =item both
 9798: 
 9799: The connection is from a manager in the hosts.tab.
 9800: 
 9801: =back
 9802: 
 9803: =back
 9804: 
 9805: =item (Blue) Certificates not installed -- trying insecure auth
 9806: 
 9807: One of the certificate file, key file or
 9808: certificate authority file could not be found for a client attempting
 9809: SSL connection intiation.  COnnection will be attemptied in in-secure mode.
 9810: (this would be a system with an up to date lond that has not gotten a 
 9811: certificate from us).
 9812: 
 9813: =item (Green)  Successful local authentication            
 9814: 
 9815: A local connection successfully negotiated the encryption key. 
 9816: In this case the IDEA key is in a file (that is hopefully well protected).
 9817: 
 9818: =item (Green) Successful ssl authentication with <client>  
 9819: 
 9820: The client (<client> is the peer's name in hosts.tab), has successfully
 9821: negotiated an SSL connection with this child process.
 9822: 
 9823: =item (Green) Successful insecure authentication with <client>
 9824: 
 9825: 
 9826: The client has successfully negotiated an  insecure connection withthe child process.
 9827: 
 9828: =item (Yellow) Attempted insecure connection disallowed    
 9829: 
 9830: The client attempted and failed to successfully negotiate a successful insecure
 9831: connection.  This can happen either because the variable londAllowInsecure is false
 9832: or undefined, or becuse the child did not successfully echo back the challenge
 9833: string.
 9834: 
 9835: 
 9836: =back
 9837: 
 9838: =back
 9839: 
 9840: 
 9841: =cut

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