File:  [LON-CAPA] / loncom / lond
Revision 1.542: download - view: text, annotated - select for diffs
Thu Feb 1 04:50:41 2018 UTC (6 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Checking if enrollment data can be accessed for a course uses a single
  call to localenroll::check_instclasses(), mediated via lonnet/lond.

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

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