File:  [LON-CAPA] / loncom / lond
Revision 1.550: download - view: text, annotated - select for diffs
Mon Oct 29 02:57:30 2018 UTC (5 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Replace use of mailto (metamail package) with mail command.
  metamail was in Red Hat 7.3, but is absent from Fedora, CentOS, RHEL etc.

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

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