File:  [LON-CAPA] / loncom / lond
Revision 1.560: download - view: text, annotated - select for diffs
Thu Jul 18 18:28:40 2019 UTC (4 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6754. LON-CAPA as LTI Provider.
  Domain configuration to support session expiration in LON-CAPA,
  after user logs out of LTI Consumer which originally launched session,
  (if Consumer supports logoutServiceUrl; e.g. custom_logout_url in Canvas).

    1: #!/usr/bin/perl
    2: # The LearningOnline Network
    3: # lond "LON Daemon" Server (port "LOND" 5663)
    4: #
    5: # $Id: lond,v 1.560 2019/07/18 18:28:40 raeburn Exp $
    6: #
    7: # Copyright Michigan State University Board of Trustees
    8: #
    9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
   10: #
   11: # LON-CAPA is free software; you can redistribute it and/or modify
   12: # it under the terms of the GNU General Public License as published by
   13: # the Free Software Foundation; either version 2 of the License, or 
   14: # (at your option) any later version.
   15: #
   16: # LON-CAPA is distributed in the hope that it will be useful,
   17: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   18: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   19: # GNU General Public License for more details.
   20: #
   21: # You should have received a copy of the GNU General Public License
   22: # along with LON-CAPA; if not, write to the Free Software
   23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   24: #
   25: # /home/httpd/html/adm/gpl.txt
   26: #
   27: 
   28: 
   29: # http://www.lon-capa.org/
   30: #
   31: 
   32: use strict;
   33: use lib '/home/httpd/lib/perl/';
   34: use LONCAPA;
   35: use LONCAPA::Configuration;
   36: use LONCAPA::Lond;
   37: 
   38: use Socket;
   39: use IO::Socket;
   40: use IO::File;
   41: #use Apache::File;
   42: use POSIX;
   43: use Crypt::IDEA;
   44: use HTTP::Request;
   45: use Digest::MD5 qw(md5_hex);
   46: use GDBM_File;
   47: use Authen::Krb5;
   48: use localauth;
   49: use localenroll;
   50: use localstudentphoto;
   51: use File::Copy;
   52: use File::Find;
   53: use LONCAPA::lonlocal;
   54: use LONCAPA::lonssl;
   55: use Fcntl qw(:flock);
   56: use Apache::lonnet;
   57: use Mail::Send;
   58: use Crypt::Eksblowfish::Bcrypt;
   59: use Digest::SHA;
   60: use Encode;
   61: use LONCAPA::LWPReq;
   62: 
   63: my $DEBUG = 0;		       # Non zero to enable debug log entries.
   64: 
   65: my $status='';
   66: my $lastlog='';
   67: 
   68: my $VERSION='$Revision: 1.560 $'; #' stupid emacs
   69: my $remoteVERSION;
   70: my $currenthostid="default";
   71: my $currentdomainid;
   72: 
   73: my $client;
   74: my $clientip;			# IP address of client.
   75: my $clientname;			# LonCAPA name of client.
   76: my $clientversion;              # LonCAPA version running on client.
   77: my $clienthomedom;              # LonCAPA domain of homeID for client. 
   78: my $clientintdom;               # LonCAPA "internet domain" for client.
   79: my $clientsamedom;              # LonCAPA domain same for this host 
   80:                                 # and client.
   81: my $clientsameinst;             # LonCAPA "internet domain" same for 
   82:                                 # this host and client.
   83: my $clientremoteok;             # Current domain permits hosting on client
   84:                                 # (not set if host and client share "internet domain").
   85:                                 # Values are 0 or 1; 1 if allowed.
   86: my %clientprohibited;           # Commands from client prohibited for domain's
   87:                                 # users.
   88: 
   89: my $server;
   90: 
   91: my $keymode;
   92: 
   93: my $cipher;			# Cipher key negotiated with client
   94: my $tmpsnum = 0;		# Id of tmpputs.
   95: 
   96: # 
   97: #   Connection type is:
   98: #      client                   - All client actions are allowed
   99: #      manager                  - only management functions allowed.
  100: #      both                     - Both management and client actions are allowed
  101: #
  102: 
  103: my $ConnectionType;
  104: 
  105: my %managers;			# Ip -> manager names
  106: 
  107: my %perlvar;			# Will have the apache conf defined perl vars.
  108: 
  109: my %secureconf;                 # Will have requirements for security 
  110:                                 # of lond connections
  111: 
  112: my %crlchecked;                 # Will contain clients for which the client's SSL
  113:                                 # has been checked against the cluster's Certificate
  114:                                 # Revocation List.
  115: 
  116: my $dist;
  117: 
  118: #
  119: #   The hash below is used for command dispatching, and is therefore keyed on the request keyword.
  120: #    Each element of the hash contains a reference to an array that contains:
  121: #          A reference to a sub that executes the request corresponding to the keyword.
  122: #          A flag that is true if the request must be encoded to be acceptable.
  123: #          A mask with bits as follows:
  124: #                      CLIENT_OK    - Set when the function is allowed by ordinary clients
  125: #                      MANAGER_OK   - Set when the function is allowed to manager clients.
  126: #
  127: my $CLIENT_OK  = 1;
  128: my $MANAGER_OK = 2;
  129: my %Dispatcher;
  130: 
  131: 
  132: #
  133: #  The array below are password error strings."
  134: #
  135: my $lastpwderror    = 13;		# Largest error number from lcpasswd.
  136: my @passwderrors = ("ok",
  137: 		   "pwchange_failure - lcpasswd must be run as user 'www'",
  138: 		   "pwchange_failure - lcpasswd got incorrect number of arguments",
  139: 		   "pwchange_failure - lcpasswd did not get the right nubmer of input text lines",
  140: 		   "pwchange_failure - lcpasswd too many simultaneous pwd changes in progress",
  141: 		   "pwchange_failure - lcpasswd User does not exist.",
  142: 		   "pwchange_failure - lcpasswd Incorrect current passwd",
  143: 		   "pwchange_failure - lcpasswd Unable to su to root.",
  144: 		   "pwchange_failure - lcpasswd Cannot set new passwd.",
  145: 		   "pwchange_failure - lcpasswd Username has invalid characters",
  146: 		   "pwchange_failure - lcpasswd Invalid characters in password",
  147: 		   "pwchange_failure - lcpasswd User already exists", 
  148:                    "pwchange_failure - lcpasswd Something went wrong with user addition.",
  149: 		   "pwchange_failure - lcpasswd Password mismatch",
  150: 		   "pwchange_failure - lcpasswd Error filename is invalid");
  151: 
  152: 
  153: # This array are the errors from lcinstallfile:
  154: 
  155: my @installerrors = ("ok",
  156: 		     "Initial user id of client not that of www",
  157: 		     "Usage error, not enough command line arguments",
  158: 		     "Source filename does not exist",
  159: 		     "Destination filename does not exist",
  160: 		     "Some file operation failed",
  161: 		     "Invalid table filename."
  162: 		     );
  163: 
  164: #
  165: # The %trust hash classifies commands according to type of trust 
  166: # required for execution of the command.
  167: #
  168: # When clients from a different institution request execution of a
  169: # particular command, the trust settings for that institution set
  170: # for this domain (or default domain for a multi-domain server) will
  171: # be checked to see if running the command is allowed.
  172: #
  173: # Trust types which depend on the "Trust" domain configuration
  174: # for the machine's default domain are:
  175: #
  176: # content   ("Access to this domain's content by others")
  177: # shared    ("Access to other domain's content by this domain")
  178: # enroll    ("Enrollment in this domain's courses by others")
  179: # coaurem   ("Co-author roles for this domain's users elsewhere")
  180: # othcoau   ("Co-author roles in this domain for others")
  181: # domroles  ("Domain roles in this domain assignable to others")
  182: # catalog   ("Course Catalog for this domain displayed elsewhere")
  183: # reqcrs    ("Requests for creation of courses in this domain by others")
  184: # msg       ("Users in other domains can send messages to this domain")
  185: # 
  186: # Trust type which depends on the User Session Hosting (remote) 
  187: # domain configuration for machine's default domain is: "remote".
  188: #
  189: # Trust types which depend on contents of manager.tab in 
  190: # /home/httpd/lonTabs is: "manageronly".
  191: # 
  192: # Trust type which requires client to share the same LON-CAPA
  193: # "internet domain" (i.e., same institution as this server) is:
  194: # "institutiononly".
  195: #
  196: 
  197: my %trust = (
  198:                auth => {remote => 1},
  199:                autocreatepassword => {remote => 1},
  200:                autocrsreqchecks => {remote => 1, reqcrs => 1},
  201:                autocrsrequpdate => {remote => 1},
  202:                autocrsreqvalidation => {remote => 1},
  203:                autogetsections => {remote => 1},
  204:                autoinstcodedefaults => {remote => 1, catalog => 1},
  205:                autoinstcodeformat => {remote => 1, catalog => 1},
  206:                autonewcourse => {remote => 1, reqcrs => 1},
  207:                autophotocheck => {remote => 1, enroll => 1},
  208:                autophotochoice => {remote => 1},
  209:                autophotopermission => {remote => 1, enroll => 1},
  210:                autopossibleinstcodes => {remote => 1, reqcrs => 1},
  211:                autoretrieve => {remote => 1, enroll => 1, catalog => 1},
  212:                autorun => {remote => 1, enroll => 1, reqcrs => 1},
  213:                autovalidateclass_sec => {catalog => 1},
  214:                autovalidatecourse => {remote => 1, enroll => 1},
  215:                autovalidateinstcode => {domroles => 1, remote => 1, enroll => 1},
  216:                changeuserauth => {remote => 1, domroles => 1},
  217:                chatretr => {remote => 1, enroll => 1},
  218:                chatsend => {remote => 1, enroll => 1},
  219:                courseiddump => {remote => 1, domroles => 1, enroll => 1},
  220:                courseidput => {remote => 1, domroles => 1, enroll => 1},
  221:                courseidputhash => {remote => 1, domroles => 1, enroll => 1},
  222:                courselastaccess => {remote => 1, domroles => 1, enroll => 1},
  223:                currentauth => {remote => 1, domroles => 1, enroll => 1},
  224:                currentdump => {remote => 1, enroll => 1},
  225:                currentversion => {remote=> 1, content => 1},
  226:                dcmaildump => {remote => 1, domroles => 1},
  227:                dcmailput => {remote => 1, domroles => 1},
  228:                del => {remote => 1, domroles => 1, enroll => 1, content => 1},
  229:                delbalcookie => {institutiononly => 1},
  230:                delusersession => {institutiononly => 1},
  231:                deldom => {remote => 1, domroles => 1}, # not currently used
  232:                devalidatecache => {institutiononly => 1},
  233:                domroleput => {remote => 1, enroll => 1},
  234:                domrolesdump => {remote => 1, catalog => 1},
  235:                du => {remote => 1, enroll => 1},
  236:                du2 => {remote => 1, enroll => 1},
  237:                dump => {remote => 1, enroll => 1, domroles => 1},
  238:                edit => {institutiononly => 1},  #not used currently
  239:                eget => {remote => 1, domroles => 1, enroll => 1}, #not used currently
  240:                egetdom => {remote => 1, domroles => 1, enroll => 1, },
  241:                ekey => {anywhere => 1},
  242:                exit => {anywhere => 1},
  243:                fetchuserfile => {remote => 1, enroll => 1},
  244:                get => {remote => 1, domroles => 1, enroll => 1},
  245:                getdom => {anywhere => 1},
  246:                home => {anywhere => 1},
  247:                iddel => {remote => 1, enroll => 1},
  248:                idget => {remote => 1, enroll => 1},
  249:                idput => {remote => 1, domroles => 1, enroll => 1},
  250:                inc => {remote => 1, enroll => 1},
  251:                init => {anywhere => 1},
  252:                inst_usertypes => {remote => 1, domroles => 1, enroll => 1},
  253:                instemailrules => {remote => 1, domroles => 1},
  254:                instidrulecheck => {remote => 1, domroles => 1,},
  255:                instidrules => {remote => 1, domroles => 1,},
  256:                instrulecheck => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
  257:                instselfcreatecheck => {institutiononly => 1},
  258:                instuserrules => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
  259:                keys => {remote => 1,},
  260:                load => {anywhere => 1},
  261:                log => {anywhere => 1},
  262:                ls => {remote => 1, enroll => 1, content => 1,},
  263:                ls2 => {remote => 1, enroll => 1, content => 1,},
  264:                ls3 => {remote => 1, enroll => 1, content => 1,},
  265:                makeuser => {remote => 1, enroll => 1, domroles => 1,},
  266:                mkdiruserfile => {remote => 1, enroll => 1,},
  267:                newput => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1,},
  268:                passwd => {remote => 1},
  269:                ping => {anywhere => 1},
  270:                pong => {anywhere => 1},
  271:                pushfile => {manageronly => 1},
  272:                put => {remote => 1, enroll => 1, domroles => 1, msg => 1, content => 1, shared => 1},
  273:                putdom => {remote => 1, domroles => 1,},
  274:                putstore => {remote => 1, enroll => 1},
  275:                queryreply => {anywhere => 1},
  276:                querysend => {anywhere => 1},
  277:                querysend_activitylog => {remote => 1},
  278:                querysend_allusers => {remote => 1, domroles => 1},
  279:                querysend_courselog => {remote => 1},
  280:                querysend_fetchenrollment => {remote => 1},
  281:                querysend_getinstuser => {remote => 1},
  282:                querysend_getmultinstusers => {remote => 1},
  283:                querysend_instdirsearch => {remote => 1, domroles => 1, coaurem => 1},
  284:                querysend_institutionalphotos => {remote => 1},
  285:                querysend_portfolio_metadata => {remote => 1, content => 1},
  286:                querysend_userlog => {remote => 1, domroles => 1},
  287:                querysend_usersearch => {remote => 1, enroll => 1, coaurem => 1},
  288:                quit => {anywhere => 1},
  289:                readlonnetglobal => {institutiononly => 1},
  290:                reinit => {manageronly => 1}, #not used currently
  291:                removeuserfile => {remote => 1, enroll => 1},
  292:                renameuserfile => {remote => 1,},
  293:                restore => {remote => 1, enroll => 1, reqcrs => 1,},
  294:                rolesdel => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
  295:                rolesput => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
  296:                servercerts => {institutiononly => 1},
  297:                serverdistarch => {anywhere => 1},
  298:                serverhomeID => {anywhere => 1},
  299:                serverloncaparev => {anywhere => 1},
  300:                servertimezone => {remote => 1, enroll => 1},
  301:                setannounce => {remote => 1, domroles => 1},
  302:                sethost => {anywhere => 1},
  303:                store => {remote => 1, enroll => 1, reqcrs => 1,},
  304:                studentphoto => {remote => 1, enroll => 1},
  305:                sub => {content => 1,},
  306:                tmpdel => {institutiononly => 1},
  307:                tmpget => {institutiononly => 1},
  308:                tmpput => {remote => 1, othcoau => 1},
  309:                tokenauthuserfile => {anywhere => 1},
  310:                unsub => {content => 1,},
  311:                update => {shared => 1},
  312:                updateclickers => {remote => 1},
  313:                userhassession => {anywhere => 1},
  314:                userload => {anywhere => 1},
  315:                version => {anywhere => 1}, #not used
  316:             );
  317: 
  318: #
  319: #   Statistics that are maintained and dislayed in the status line.
  320: #
  321: my $Transactions = 0;		# Number of attempted transactions.
  322: my $Failures     = 0;		# Number of transcations failed.
  323: 
  324: #   ResetStatistics: 
  325: #      Resets the statistics counters:
  326: #
  327: sub ResetStatistics {
  328:     $Transactions = 0;
  329:     $Failures     = 0;
  330: }
  331: 
  332: #------------------------------------------------------------------------
  333: #
  334: #   LocalConnection
  335: #     Completes the formation of a locally authenticated connection.
  336: #     This function will ensure that the 'remote' client is really the
  337: #     local host.  If not, the connection is closed, and the function fails.
  338: #     If so, initcmd is parsed for the name of a file containing the
  339: #     IDEA session key.  The fie is opened, read, deleted and the session
  340: #     key returned to the caller.
  341: #
  342: # Parameters:
  343: #   $Socket      - Socket open on client.
  344: #   $initcmd     - The full text of the init command.
  345: #
  346: # Returns:
  347: #     IDEA session key on success.
  348: #     undef on failure.
  349: #
  350: sub LocalConnection {
  351:     my ($Socket, $initcmd) = @_;
  352:     Debug("Attempting local connection: $initcmd client: $clientip");
  353:     if($clientip ne "127.0.0.1") {
  354: 	&logthis('<font color="red"> LocalConnection rejecting non local: '
  355: 		 ."$clientip ne 127.0.0.1 </font>");
  356: 	close $Socket;
  357: 	return undef;
  358:     }  else {
  359: 	chomp($initcmd);	# Get rid of \n in filename.
  360: 	my ($init, $type, $name) = split(/:/, $initcmd);
  361: 	Debug(" Init command: $init $type $name ");
  362: 
  363: 	# Require that $init = init, and $type = local:  Otherwise
  364: 	# the caller is insane:
  365: 
  366: 	if(($init ne "init") && ($type ne "local")) {
  367: 	    &logthis('<font color = "red"> LocalConnection: caller is insane! '
  368: 		     ."init = $init, and type = $type </font>");
  369: 	    close($Socket);;
  370: 	    return undef;
  371: 		
  372: 	}
  373: 	#  Now get the key filename:
  374: 
  375: 	my $IDEAKey = lonlocal::ReadKeyFile($name);
  376: 	return $IDEAKey;
  377:     }
  378: }
  379: #------------------------------------------------------------------------------
  380: #
  381: #  SSLConnection
  382: #   Completes the formation of an ssh authenticated connection. The
  383: #   socket is promoted to an ssl socket.  If this promotion and the associated
  384: #   certificate exchange are successful, the IDEA key is generated and sent
  385: #   to the remote peer via the SSL tunnel. The IDEA key is also returned to
  386: #   the caller after the SSL tunnel is torn down.
  387: #
  388: # Parameters:
  389: #   Name              Type             Purpose
  390: #   $Socket          IO::Socket::INET  Plaintext socket.
  391: #
  392: # Returns:
  393: #    IDEA key on success.
  394: #    undef on failure.
  395: #
  396: sub SSLConnection {
  397:     my $Socket   = shift;
  398: 
  399:     Debug("SSLConnection: ");
  400:     my $KeyFile         = lonssl::KeyFile();
  401:     if(!$KeyFile) {
  402: 	my $err = lonssl::LastError();
  403: 	&logthis("<font color=\"red\"> CRITICAL"
  404: 		 ."Can't get key file $err </font>");
  405: 	return undef;
  406:     }
  407:     my ($CACertificate,
  408: 	$Certificate) = lonssl::CertificateFile();
  409: 
  410: 
  411:     # If any of the key, certificate or certificate authority 
  412:     # certificate filenames are not defined, this can't work.
  413: 
  414:     if((!$Certificate) || (!$CACertificate)) {
  415: 	my $err = lonssl::LastError();
  416: 	&logthis("<font color=\"red\"> CRITICAL"
  417: 		 ."Can't get certificates: $err </font>");
  418: 
  419: 	return undef;
  420:     }
  421:     Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
  422: 
  423:     # Indicate to our peer that we can procede with
  424:     # a transition to ssl authentication:
  425: 
  426:     print $Socket "ok:ssl\n";
  427: 
  428:     Debug("Approving promotion -> ssl");
  429:     #  And do so:
  430: 
  431:     my $CRLFile;
  432:     unless ($crlchecked{$clientname}) {
  433:         $CRLFile = lonssl::CRLFile();
  434:         $crlchecked{$clientname} = 1;
  435:     }
  436: 
  437:     my $SSLSocket = lonssl::PromoteServerSocket($Socket,
  438: 						$CACertificate,
  439: 						$Certificate,
  440: 						$KeyFile,
  441: 						$clientname,
  442:                                                 $CRLFile,
  443:                                                 $clientversion);
  444:     if(! ($SSLSocket) ) {	# SSL socket promotion failed.
  445: 	my $err = lonssl::LastError();
  446: 	&logthis("<font color=\"red\"> CRITICAL "
  447: 		 ."SSL Socket promotion failed: $err </font>");
  448: 	return undef;
  449:     }
  450:     Debug("SSL Promotion successful");
  451: 
  452:     # 
  453:     #  The only thing we'll use the socket for is to send the IDEA key
  454:     #  to the peer:
  455: 
  456:     my $Key = lonlocal::CreateCipherKey();
  457:     print $SSLSocket "$Key\n";
  458: 
  459:     lonssl::Close($SSLSocket); 
  460: 
  461:     Debug("Key exchange complete: $Key");
  462: 
  463:     return $Key;
  464: }
  465: #
  466: #     InsecureConnection: 
  467: #        If insecure connections are allowd,
  468: #        exchange a challenge with the client to 'validate' the
  469: #        client (not really, but that's the protocol):
  470: #        We produce a challenge string that's sent to the client.
  471: #        The client must then echo the challenge verbatim to us.
  472: #
  473: #  Parameter:
  474: #      Socket      - Socket open on the client.
  475: #  Returns:
  476: #      1           - success.
  477: #      0           - failure (e.g.mismatch or insecure not allowed).
  478: #
  479: sub InsecureConnection {
  480:     my $Socket  =  shift;
  481: 
  482:     #   Don't even start if insecure connections are not allowed.
  483:     #   return 0 if Insecure connections not allowed.
  484:     #
  485:     if (ref($secureconf{'connfrom'}) eq 'HASH') {
  486:         if ($clientsamedom) {
  487:             if ($secureconf{'connfrom'}{'dom'} eq 'req') {
  488:                 return 0;
  489:             } 
  490:         } elsif ($clientsameinst) {
  491:             if ($secureconf{'connfrom'}{'intdom'} eq 'req') {
  492:                 return 0;
  493:             }
  494:         } else {
  495:             if ($secureconf{'connfrom'}{'other'} eq 'req') {
  496:                 return 0;
  497:             }
  498:         }
  499:     } elsif (!$perlvar{londAllowInsecure}) {
  500: 	return 0;
  501:     }
  502: 
  503:     #   Fabricate a challenge string and send it..
  504: 
  505:     my $challenge = "$$".time;	# pid + time.
  506:     print $Socket "$challenge\n";
  507:     &status("Waiting for challenge reply");
  508: 
  509:     my $answer = <$Socket>;
  510:     $answer    =~s/\W//g;
  511:     if($challenge eq $answer) {
  512: 	return 1;
  513:     } else {
  514: 	logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
  515: 	&status("No challenge reqply");
  516: 	return 0;
  517:     }
  518:     
  519: 
  520: }
  521: #
  522: #   Safely execute a command (as long as it's not a shel command and doesn
  523: #   not require/rely on shell escapes.   The function operates by doing a
  524: #   a pipe based fork and capturing stdout and stderr  from the pipe.
  525: #
  526: # Formal Parameters:
  527: #     $line                    - A line of text to be executed as a command.
  528: # Returns:
  529: #     The output from that command.  If the output is multiline the caller
  530: #     must know how to split up the output.
  531: #
  532: #
  533: sub execute_command {
  534:     my ($line)    = @_;
  535:     my @words     = split(/\s/, $line);	# Bust the command up into words.
  536:     my $output    = "";
  537: 
  538:     my $pid = open(CHILD, "-|");
  539:     
  540:     if($pid) {			# Parent process
  541: 	Debug("In parent process for execute_command");
  542: 	my @data = <CHILD>;	# Read the child's outupt...
  543: 	close CHILD;
  544: 	foreach my $output_line (@data) {
  545: 	    Debug("Adding $output_line");
  546: 	    $output .= $output_line; # Presumably has a \n on it.
  547: 	}
  548: 
  549:     } else {			# Child process
  550: 	close (STDERR);
  551: 	open  (STDERR, ">&STDOUT");# Combine stderr, and stdout...
  552: 	exec(@words);		# won't return.
  553:     }
  554:     return $output;
  555: }
  556: 
  557: 
  558: #   GetCertificate: Given a transaction that requires a certificate,
  559: #   this function will extract the certificate from the transaction
  560: #   request.  Note that at this point, the only concept of a certificate
  561: #   is the hostname to which we are connected.
  562: #
  563: #   Parameter:
  564: #      request   - The request sent by our client (this parameterization may
  565: #                  need to change when we really use a certificate granting
  566: #                  authority.
  567: #
  568: sub GetCertificate {
  569:     my $request = shift;
  570: 
  571:     return $clientip;
  572: }
  573: 
  574: #
  575: #   Return true if client is a manager.
  576: #
  577: sub isManager {
  578:     return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
  579: }
  580: #
  581: #   Return tru if client can do client functions
  582: #
  583: sub isClient {
  584:     return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
  585: }
  586: 
  587: 
  588: #
  589: #   ReadManagerTable: Reads in the current manager table. For now this is
  590: #                     done on each manager authentication because:
  591: #                     - These authentications are not frequent
  592: #                     - This allows dynamic changes to the manager table
  593: #                       without the need to signal to the lond.
  594: #
  595: sub ReadManagerTable {
  596: 
  597:     &Debug("Reading manager table");
  598:     #   Clean out the old table first..
  599: 
  600:    foreach my $key (keys %managers) {
  601:       delete $managers{$key};
  602:    }
  603: 
  604:    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
  605:    if (!open (MANAGERS, $tablename)) {
  606:        my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
  607:        if (&Apache::lonnet::is_LC_dns($hostname)) {
  608:            &logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
  609:        }
  610:        return;
  611:    }
  612:    while(my $host = <MANAGERS>) {
  613:       chomp($host);
  614:       if ($host =~ "^#") {                  # Comment line.
  615:          next;
  616:       }
  617:       if (!defined &Apache::lonnet::get_host_ip($host)) { # This is a non cluster member
  618: 	    #  The entry is of the form:
  619: 	    #    cluname:hostname
  620: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
  621: 	    #            the host key.
  622: 	    #  hostname- The dns name of the host.
  623: 	    #
  624:           my($cluname, $dnsname) = split(/:/, $host);
  625:           
  626:           my $ip = gethostbyname($dnsname);
  627:           if(defined($ip)) {                 # bad names don't deserve entry.
  628:             my $hostip = inet_ntoa($ip);
  629:             $managers{$hostip} = $cluname;
  630:             logthis('<font color="green"> registering manager '.
  631:                     "$dnsname as $cluname with $hostip </font>\n");
  632:          }
  633:       } else {
  634:          logthis('<font color="green"> existing host'." $host</font>\n");
  635:          $managers{&Apache::lonnet::get_host_ip($host)} = $host;  # Use info from cluster tab if cluster memeber
  636:       }
  637:    }
  638: }
  639: 
  640: #
  641: #  ValidManager: Determines if a given certificate represents a valid manager.
  642: #                in this primitive implementation, the 'certificate' is
  643: #                just the connecting loncapa client name.  This is checked
  644: #                against a valid client list in the configuration.
  645: #
  646: #                  
  647: sub ValidManager {
  648:     my $certificate = shift; 
  649: 
  650:     return isManager;
  651: }
  652: #
  653: #  CopyFile:  Called as part of the process of installing a 
  654: #             new configuration file.  This function copies an existing
  655: #             file to a backup file.
  656: # Parameters:
  657: #     oldfile  - Name of the file to backup.
  658: #     newfile  - Name of the backup file.
  659: # Return:
  660: #     0   - Failure (errno has failure reason).
  661: #     1   - Success.
  662: #
  663: sub CopyFile {
  664: 
  665:     my ($oldfile, $newfile) = @_;
  666: 
  667:     if (! copy($oldfile,$newfile)) {
  668:         return 0;
  669:     }
  670:     chmod(0660, $newfile);
  671:     return 1;
  672: }
  673: #
  674: #  Host files are passed out with externally visible host IPs.
  675: #  If, for example, we are behind a fire-wall or NAT host, our 
  676: #  internally visible IP may be different than the externally
  677: #  visible IP.  Therefore, we always adjust the contents of the
  678: #  host file so that the entry for ME is the IP that we believe
  679: #  we have.  At present, this is defined as the entry that
  680: #  DNS has for us.  If by some chance we are not able to get a
  681: #  DNS translation for us, then we assume that the host.tab file
  682: #  is correct.  
  683: #    BUGBUGBUG - in the future, we really should see if we can
  684: #       easily query the interface(s) instead.
  685: # Parameter(s):
  686: #     contents    - The contents of the host.tab to check.
  687: # Returns:
  688: #     newcontents - The adjusted contents.
  689: #
  690: #
  691: sub AdjustHostContents {
  692:     my $contents  = shift;
  693:     my $adjusted;
  694:     my $me        = $perlvar{'lonHostID'};
  695: 
  696:     foreach my $line (split(/\n/,$contents)) {
  697: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/) ||
  698:              ($line =~ /^\s*\^/))) {
  699: 	    chomp($line);
  700: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
  701: 	    if ($id eq $me) {
  702: 		my $ip = gethostbyname($name);
  703: 		my $ipnew = inet_ntoa($ip);
  704: 		$ip = $ipnew;
  705: 		#  Reconstruct the host line and append to adjusted:
  706: 		
  707: 		my $newline = "$id:$domain:$role:$name:$ip";
  708: 		if($maxcon ne "") { # Not all hosts have loncnew tuning params
  709: 		    $newline .= ":$maxcon:$idleto:$mincon";
  710: 		}
  711: 		$adjusted .= $newline."\n";
  712: 		
  713: 	    } else {		# Not me, pass unmodified.
  714: 		$adjusted .= $line."\n";
  715: 	    }
  716: 	} else {                  # Blank or comment never re-written.
  717: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
  718: 	}
  719:     }
  720:     return $adjusted;
  721: }
  722: #
  723: #   InstallFile: Called to install an administrative file:
  724: #       - The file is created int a temp directory called <name>.tmp
  725: #       - lcinstall file is called to install the file.
  726: #         since the web app has no direct write access to the table directory
  727: #
  728: #  Parameters:
  729: #       Name of the file
  730: #       File Contents.
  731: #  Return:
  732: #      nonzero - success.
  733: #      0       - failure and $! has an errno.
  734: # Assumptions:
  735: #    File installtion is a relatively infrequent
  736: #
  737: sub InstallFile {
  738: 
  739:     my ($Filename, $Contents) = @_;
  740: #     my $TempFile = $Filename.".tmp";
  741:     my $exedir = $perlvar{'lonDaemons'};
  742:     my $tmpdir = $exedir.'/tmp/';
  743:     my $TempFile = $tmpdir."TempTableFile.tmp";
  744: 
  745:     #  Open the file for write:
  746: 
  747:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
  748:     if(!(defined $fh)) {
  749: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
  750: 	return 0;
  751:     }
  752:     #  write the contents of the file:
  753: 
  754:     print $fh ($Contents); 
  755:     $fh->close;			# In case we ever have a filesystem w. locking
  756: 
  757:     chmod(0664, $TempFile);	# Everyone can write it.
  758: 
  759:     # Use lcinstall file to put the file in the table directory...
  760: 
  761:     &Debug("Opening pipe to $exedir/lcinstallfile $TempFile $Filename");
  762:     my $pf = IO::File->new("| $exedir/lcinstallfile   $TempFile $Filename > $exedir/logs/lcinstallfile.log");
  763:     close $pf;
  764:     my $err = $?;
  765:     &Debug("Status is $err");
  766:     if ($err != 0) {
  767: 	my $msg = $err;
  768: 	if ($err < @installerrors) {
  769: 	    $msg = $installerrors[$err];
  770: 	}
  771: 	&logthis("Install failed for table file $Filename : $msg");
  772: 	return 0;
  773:     }
  774: 
  775:     # Remove the temp file:
  776: 
  777:     unlink($TempFile);
  778: 
  779:     return 1;
  780: }
  781: 
  782: 
  783: #
  784: #   ConfigFileFromSelector: converts a configuration file selector
  785: #                 into a configuration file pathname.
  786: #                 Supports the following file selectors: 
  787: #                 hosts, domain, dns_hosts, dns_domain  
  788: #
  789: #
  790: #  Parameters:
  791: #      selector  - Configuration file selector.
  792: #  Returns:
  793: #      Full path to the file or undef if the selector is invalid.
  794: #
  795: sub ConfigFileFromSelector {
  796:     my $selector   = shift;
  797:     my $tablefile;
  798: 
  799:     if ($selector eq 'loncapaCAcrl') {
  800:         my $tabledir = $perlvar{'lonCertificateDirectory'};
  801:         if (-d $tabledir) {
  802:             $tablefile =  $tabledir.'/'.$selector.'.pem';
  803:         }
  804:     } else {
  805:         my $tabledir = $perlvar{'lonTabDir'}.'/';
  806:         if (($selector eq "hosts") || ($selector eq "domain") || 
  807:             ($selector eq "dns_hosts") || ($selector eq "dns_domain")) {
  808: 	    $tablefile =  $tabledir.$selector.'.tab';
  809:         }
  810:     }
  811:     return $tablefile;
  812: }
  813: #
  814: #   PushFile:  Called to do an administrative push of a file.
  815: #              - Ensure the file being pushed is one we support.
  816: #              - Backup the old file to <filename.saved>
  817: #              - Separate the contents of the new file out from the
  818: #                rest of the request.
  819: #              - Write the new file.
  820: #  Parameter:
  821: #     Request - The entire user request.  This consists of a : separated
  822: #               string pushfile:tablename:contents.
  823: #     NOTE:  The contents may have :'s in it as well making things a bit
  824: #            more interesting... but not much.
  825: #  Returns:
  826: #     String to send to client ("ok" or "refused" if bad file).
  827: #
  828: sub PushFile {
  829:     my $request = shift;
  830:     my ($command, $filename, $contents) = split(":", $request, 3);
  831:     &Debug("PushFile");
  832:     
  833:     #  At this point in time, pushes for only the following tables and
  834:     #  CRL file are supported:
  835:     #   hosts.tab  ($filename eq host).
  836:     #   domain.tab ($filename eq domain).
  837:     #   dns_hosts.tab ($filename eq dns_host).
  838:     #   dns_domain.tab ($filename eq dns_domain).
  839:     #   loncapaCAcrl.pem ($filename eq loncapaCAcrl).
  840:     # Construct the destination filename or reject the request.
  841:     #
  842:     # lonManage is supposed to ensure this, however this session could be
  843:     # part of some elaborate spoof that managed somehow to authenticate.
  844:     #
  845: 
  846: 
  847:     my $tablefile = ConfigFileFromSelector($filename);
  848:     if(! (defined $tablefile)) {
  849: 	return "refused";
  850:     }
  851: 
  852:     #  If the file being pushed is the host file, we adjust the entry for ourself so that the
  853:     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
  854:     #  to conceive of conditions where we don't have a DNS entry locally.  This is possible in a 
  855:     #  network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
  856:     #  that possibilty.
  857: 
  858:     if($filename eq "host") {
  859: 	$contents = AdjustHostContents($contents);
  860:     } elsif (($filename eq 'dns_host') || ($filename eq 'dns_domain') ||
  861:              ($filename eq 'loncapaCAcrl')) {
  862:         if ($contents eq '') {
  863:             &logthis('<font color="red"> Pushfile: unable to install '
  864:                     .$tablefile." - no data received from push. </font>");
  865:             return 'error: push had no data';
  866:         }
  867:         if (&Apache::lonnet::get_host_ip($clientname)) {
  868:             my $clienthost = &Apache::lonnet::hostname($clientname);
  869:             if ($managers{$clientip} eq $clientname) {
  870:                 my $clientprotocol = $Apache::lonnet::protocol{$clientname};
  871:                 $clientprotocol = 'http' if ($clientprotocol ne 'https');
  872:                 my $url;
  873:                 if ($filename eq 'loncapaCAcrl') {
  874:                     $url = '/adm/dns/loncapaCRL';
  875:                 } else {
  876:                     $url = '/adm/'.$filename;
  877:                     $url =~ s{_}{/};
  878:                 }
  879:                 my $request=new HTTP::Request('GET',"$clientprotocol://$clienthost$url");
  880:                 my $response = LONCAPA::LWPReq::makerequest($clientname,$request,'',\%perlvar,60,0);
  881:                 if ($response->is_error()) {
  882:                     &logthis('<font color="red"> Pushfile: unable to install '
  883:                             .$tablefile." - error attempting to pull data. </font>");
  884:                     return 'error: pull failed';
  885:                 } else {
  886:                     my $result = $response->content;
  887:                     chomp($result);
  888:                     unless ($result eq $contents) {
  889:                         &logthis('<font color="red"> Pushfile: unable to install '
  890:                                 .$tablefile." - pushed data and pulled data differ. </font>");
  891:                         my $pushleng = length($contents);
  892:                         my $pullleng = length($result);
  893:                         if ($pushleng != $pullleng) {
  894:                             return "error: $pushleng vs $pullleng bytes";
  895:                         } else {
  896:                             return "error: mismatch push and pull";
  897:                         }
  898:                     }
  899:                 }
  900:             }
  901:         }
  902:     }
  903: 
  904:     #  Install the new file:
  905: 
  906:     &logthis("Installing new $tablefile contents:\n$contents");
  907:     if(!InstallFile($tablefile, $contents)) {
  908: 	&logthis('<font color="red"> Pushfile: unable to install '
  909: 	 .$tablefile." $! </font>");
  910: 	return "error:$!";
  911:     } else {
  912: 	&logthis('<font color="green"> Installed new '.$tablefile
  913: 		 ." - transaction by: $clientname ($clientip)</font>");
  914:         my $adminmail = $perlvar{'lonAdmEMail'};
  915:         my $admindom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
  916:         if ($admindom ne '') {
  917:             my %domconfig =
  918:                 &Apache::lonnet::get_dom('configuration',['contacts'],$admindom);
  919:             if (ref($domconfig{'contacts'}) eq 'HASH') {
  920:                 if ($domconfig{'contacts'}{'adminemail'} ne '') {
  921:                     $adminmail = $domconfig{'contacts'}{'adminemail'};
  922:                 }
  923:             }
  924:         }
  925:         if ($adminmail =~ /^[^\@]+\@[^\@]+$/) {
  926:             my $msg = new Mail::Send;
  927:             $msg->to($adminmail);
  928:             $msg->subject('LON-CAPA DNS update on '.$perlvar{'lonHostID'});
  929:             $msg->add('Content-type','text/plain; charset=UTF-8');
  930:             if (my $fh = $msg->open()) {
  931:                 print $fh 'Update to '.$tablefile.' from Cluster Manager '.
  932:                           "$clientname ($clientip)\n";
  933:                 $fh->close;
  934:             }
  935:         }
  936:     }
  937: 
  938:     #  Indicate success:
  939:  
  940:     return "ok";
  941: 
  942: }
  943: 
  944: #
  945: #  Called to re-init either lonc or lond.
  946: #
  947: #  Parameters:
  948: #    request   - The full request by the client.  This is of the form
  949: #                reinit:<process>  
  950: #                where <process> is allowed to be either of 
  951: #                lonc or lond
  952: #
  953: #  Returns:
  954: #     The string to be sent back to the client either:
  955: #   ok         - Everything worked just fine.
  956: #   error:why  - There was a failure and why describes the reason.
  957: #
  958: #
  959: sub ReinitProcess {
  960:     my $request = shift;
  961: 
  962: 
  963:     # separate the request (reinit) from the process identifier and
  964:     # validate it producing the name of the .pid file for the process.
  965:     #
  966:     #
  967:     my ($junk, $process) = split(":", $request);
  968:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
  969:     if($process eq 'lonc') {
  970: 	$processpidfile = $processpidfile."lonc.pid";
  971: 	if (!open(PIDFILE, "< $processpidfile")) {
  972: 	    return "error:Open failed for $processpidfile";
  973: 	}
  974: 	my $loncpid = <PIDFILE>;
  975: 	close(PIDFILE);
  976: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
  977: 		."</font>");
  978: 	kill("USR2", $loncpid);
  979:     } elsif ($process eq 'lond') {
  980: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
  981: 	&UpdateHosts;			# Lond is us!!
  982:     } else {
  983: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
  984: 		 ."</font>");
  985: 	return "error:Invalid process identifier $process";
  986:     }
  987:     return 'ok';
  988: }
  989: #   Validate a line in a configuration file edit script:
  990: #   Validation includes:
  991: #     - Ensuring the command is valid.
  992: #     - Ensuring the command has sufficient parameters
  993: #   Parameters:
  994: #     scriptline - A line to validate (\n has been stripped for what it's worth).
  995: #
  996: #   Return:
  997: #      0     - Invalid scriptline.
  998: #      1     - Valid scriptline
  999: #  NOTE:
 1000: #     Only the command syntax is checked, not the executability of the
 1001: #     command.
 1002: #
 1003: sub isValidEditCommand {
 1004:     my $scriptline = shift;
 1005: 
 1006:     #   Line elements are pipe separated:
 1007: 
 1008:     my ($command, $key, $newline)  = split(/\|/, $scriptline);
 1009:     &logthis('<font color="green"> isValideditCommand checking: '.
 1010: 	     "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
 1011:     
 1012:     if ($command eq "delete") {
 1013: 	#
 1014: 	#   key with no newline.
 1015: 	#
 1016: 	if( ($key eq "") || ($newline ne "")) {
 1017: 	    return 0;		# Must have key but no newline.
 1018: 	} else {
 1019: 	    return 1;		# Valid syntax.
 1020: 	}
 1021:     } elsif ($command eq "replace") {
 1022: 	#
 1023: 	#   key and newline:
 1024: 	#
 1025: 	if (($key eq "") || ($newline eq "")) {
 1026: 	    return 0;
 1027: 	} else {
 1028: 	    return 1;
 1029: 	}
 1030:     } elsif ($command eq "append") {
 1031: 	if (($key ne "") && ($newline eq "")) {
 1032: 	    return 1;
 1033: 	} else {
 1034: 	    return 0;
 1035: 	}
 1036:     } else {
 1037: 	return 0;		# Invalid command.
 1038:     }
 1039:     return 0;			# Should not get here!!!
 1040: }
 1041: #
 1042: #   ApplyEdit - Applies an edit command to a line in a configuration 
 1043: #               file.  It is the caller's responsiblity to validate the
 1044: #               edit line.
 1045: #   Parameters:
 1046: #      $directive - A single edit directive to apply.  
 1047: #                   Edit directives are of the form:
 1048: #                  append|newline      - Appends a new line to the file.
 1049: #                  replace|key|newline - Replaces the line with key value 'key'
 1050: #                  delete|key          - Deletes the line with key value 'key'.
 1051: #      $editor   - A config file editor object that contains the
 1052: #                  file being edited.
 1053: #
 1054: sub ApplyEdit {
 1055: 
 1056:     my ($directive, $editor) = @_;
 1057: 
 1058:     # Break the directive down into its command and its parameters
 1059:     # (at most two at this point.  The meaning of the parameters, if in fact
 1060:     #  they exist depends on the command).
 1061: 
 1062:     my ($command, $p1, $p2) = split(/\|/, $directive);
 1063: 
 1064:     if($command eq "append") {
 1065: 	$editor->Append($p1);	          # p1 - key p2 null.
 1066:     } elsif ($command eq "replace") {
 1067: 	$editor->ReplaceLine($p1, $p2);   # p1 - key p2 = newline.
 1068:     } elsif ($command eq "delete") {
 1069: 	$editor->DeleteLine($p1);         # p1 - key p2 null.
 1070:     } else {			          # Should not get here!!!
 1071: 	die "Invalid command given to ApplyEdit $command"
 1072:     }
 1073: }
 1074: #
 1075: # AdjustOurHost:
 1076: #           Adjusts a host file stored in a configuration file editor object
 1077: #           for the true IP address of this host. This is necessary for hosts
 1078: #           that live behind a firewall.
 1079: #           Those hosts have a publicly distributed IP of the firewall, but
 1080: #           internally must use their actual IP.  We assume that a given
 1081: #           host only has a single IP interface for now.
 1082: # Formal Parameters:
 1083: #     editor   - The configuration file editor to adjust.  This
 1084: #                editor is assumed to contain a hosts.tab file.
 1085: # Strategy:
 1086: #    - Figure out our hostname.
 1087: #    - Lookup the entry for this host.
 1088: #    - Modify the line to contain our IP
 1089: #    - Do a replace for this host.
 1090: sub AdjustOurHost {
 1091:     my $editor        = shift;
 1092: 
 1093:     # figure out who I am.
 1094: 
 1095:     my $myHostName    = $perlvar{'lonHostID'}; # LonCAPA hostname.
 1096: 
 1097:     #  Get my host file entry.
 1098: 
 1099:     my $ConfigLine    = $editor->Find($myHostName);
 1100:     if(! (defined $ConfigLine)) {
 1101: 	die "AdjustOurHost - no entry for me in hosts file $myHostName";
 1102:     }
 1103:     # figure out my IP:
 1104:     #   Use the config line to get my hostname.
 1105:     #   Use gethostbyname to translate that into an IP address.
 1106:     #
 1107:     my ($id,$domain,$role,$name,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
 1108:     #
 1109:     #  Reassemble the config line from the elements in the list.
 1110:     #  Note that if the loncnew items were not present before, they will
 1111:     #  be now even if they would be empty
 1112:     #
 1113:     my $newConfigLine = $id;
 1114:     foreach my $item ($domain, $role, $name, $maxcon, $idleto, $mincon) {
 1115: 	$newConfigLine .= ":".$item;
 1116:     }
 1117:     #  Replace the line:
 1118: 
 1119:     $editor->ReplaceLine($id, $newConfigLine);
 1120:     
 1121: }
 1122: #
 1123: #   ReplaceConfigFile:
 1124: #              Replaces a configuration file with the contents of a
 1125: #              configuration file editor object.
 1126: #              This is done by:
 1127: #              - Copying the target file to <filename>.old
 1128: #              - Writing the new file to <filename>.tmp
 1129: #              - Moving <filename.tmp>  -> <filename>
 1130: #              This laborious process ensures that the system is never without
 1131: #              a configuration file that's at least valid (even if the contents
 1132: #              may be dated).
 1133: #   Parameters:
 1134: #        filename   - Name of the file to modify... this is a full path.
 1135: #        editor     - Editor containing the file.
 1136: #
 1137: sub ReplaceConfigFile {
 1138:     
 1139:     my ($filename, $editor) = @_;
 1140: 
 1141:     CopyFile ($filename, $filename.".old");
 1142: 
 1143:     my $contents  = $editor->Get(); # Get the contents of the file.
 1144: 
 1145:     InstallFile($filename, $contents);
 1146: }
 1147: #   
 1148: #
 1149: #   Called to edit a configuration table  file
 1150: #   Parameters:
 1151: #      request           - The entire command/request sent by lonc or lonManage
 1152: #   Return:
 1153: #      The reply to send to the client.
 1154: #
 1155: sub EditFile {
 1156:     my $request = shift;
 1157: 
 1158:     #  Split the command into it's pieces:  edit:filetype:script
 1159: 
 1160:     my ($cmd, $filetype, $script) = split(/:/, $request,3);	# : in script
 1161: 
 1162:     #  Check the pre-coditions for success:
 1163: 
 1164:     if($cmd != "edit") {	# Something is amiss afoot alack.
 1165: 	return "error:edit request detected, but request != 'edit'\n";
 1166:     }
 1167:     if( ($filetype ne "hosts")  &&
 1168: 	($filetype ne "domain")) {
 1169: 	return "error:edit requested with invalid file specifier: $filetype \n";
 1170:     }
 1171: 
 1172:     #   Split the edit script and check it's validity.
 1173: 
 1174:     my @scriptlines = split(/\n/, $script);  # one line per element.
 1175:     my $linecount   = scalar(@scriptlines);
 1176:     for(my $i = 0; $i < $linecount; $i++) {
 1177: 	chomp($scriptlines[$i]);
 1178: 	if(!isValidEditCommand($scriptlines[$i])) {
 1179: 	    return "error:edit with bad script line: '$scriptlines[$i]' \n";
 1180: 	}
 1181:     }
 1182: 
 1183:     #   Execute the edit operation.
 1184:     #   - Create a config file editor for the appropriate file and 
 1185:     #   - execute each command in the script:
 1186:     #
 1187:     my $configfile = ConfigFileFromSelector($filetype);
 1188:     if (!(defined $configfile)) {
 1189: 	return "refused\n";
 1190:     }
 1191:     my $editor = ConfigFileEdit->new($configfile);
 1192: 
 1193:     for (my $i = 0; $i < $linecount; $i++) {
 1194: 	ApplyEdit($scriptlines[$i], $editor);
 1195:     }
 1196:     # If the file is the host file, ensure that our host is
 1197:     # adjusted to have our ip:
 1198:     #
 1199:     if($filetype eq "host") {
 1200: 	AdjustOurHost($editor);
 1201:     }
 1202:     #  Finally replace the current file with our file.
 1203:     #
 1204:     ReplaceConfigFile($configfile, $editor);
 1205: 
 1206:     return "ok\n";
 1207: }
 1208: 
 1209: #   read_profile
 1210: #
 1211: #   Returns a set of specific entries from a user's profile file.
 1212: #   this is a utility function that is used by both get_profile_entry and
 1213: #   get_profile_entry_encrypted.
 1214: #
 1215: # Parameters:
 1216: #    udom       - Domain in which the user exists.
 1217: #    uname      - User's account name (loncapa account)
 1218: #    namespace  - The profile namespace to open.
 1219: #    what       - A set of & separated queries.
 1220: # Returns:
 1221: #    If all ok: - The string that needs to be shipped back to the user.
 1222: #    If failure - A string that starts with error: followed by the failure
 1223: #                 reason.. note that this probabyl gets shipped back to the
 1224: #                 user as well.
 1225: #
 1226: sub read_profile {
 1227:     my ($udom, $uname, $namespace, $what) = @_;
 1228:     
 1229:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 1230: 				 &GDBM_READER());
 1231:     if ($hashref) {
 1232:         my @queries=split(/\&/,$what);
 1233:         if ($namespace eq 'roles') {
 1234:             @queries = map { &unescape($_); } @queries; 
 1235:         }
 1236:         my $qresult='';
 1237: 	
 1238: 	for (my $i=0;$i<=$#queries;$i++) {
 1239: 	    $qresult.="$hashref->{$queries[$i]}&";    # Presumably failure gives empty string.
 1240: 	}
 1241: 	$qresult=~s/\&$//;              # Remove trailing & from last lookup.
 1242: 	if (&untie_user_hash($hashref)) {
 1243: 	    return $qresult;
 1244: 	} else {
 1245: 	    return "error: ".($!+0)." untie (GDBM) Failed";
 1246: 	}
 1247:     } else {
 1248: 	if ($!+0 == 2) {
 1249: 	    return "error:No such file or GDBM reported bad block error";
 1250: 	} else {
 1251: 	    return "error: ".($!+0)." tie (GDBM) Failed";
 1252: 	}
 1253:     }
 1254: 
 1255: }
 1256: #--------------------- Request Handlers --------------------------------------------
 1257: #
 1258: #   By convention each request handler registers itself prior to the sub 
 1259: #   declaration:
 1260: #
 1261: 
 1262: #++
 1263: #
 1264: #  Handles ping requests.
 1265: #  Parameters:
 1266: #      $cmd    - the actual keyword that invoked us.
 1267: #      $tail   - the tail of the request that invoked us.
 1268: #      $replyfd- File descriptor connected to the client
 1269: #  Implicit Inputs:
 1270: #      $currenthostid - Global variable that carries the name of the host we are
 1271: #                       known as.
 1272: #  Returns:
 1273: #      1       - Ok to continue processing.
 1274: #      0       - Program should exit.
 1275: #  Side effects:
 1276: #      Reply information is sent to the client.
 1277: sub ping_handler {
 1278:     my ($cmd, $tail, $client) = @_;
 1279:     Debug("$cmd $tail $client .. $currenthostid:");
 1280:    
 1281:     Reply( $client,\$currenthostid,"$cmd:$tail");
 1282:    
 1283:     return 1;
 1284: }
 1285: &register_handler("ping", \&ping_handler, 0, 1, 1);       # Ping unencoded, client or manager.
 1286: 
 1287: #++
 1288: #
 1289: # Handles pong requests.  Pong replies with our current host id, and
 1290: #                         the results of a ping sent to us via our lonc.
 1291: #
 1292: # Parameters:
 1293: #      $cmd    - the actual keyword that invoked us.
 1294: #      $tail   - the tail of the request that invoked us.
 1295: #      $replyfd- File descriptor connected to the client
 1296: #  Implicit Inputs:
 1297: #      $currenthostid - Global variable that carries the name of the host we are
 1298: #                       connected to.
 1299: #  Returns:
 1300: #      1       - Ok to continue processing.
 1301: #      0       - Program should exit.
 1302: #  Side effects:
 1303: #      Reply information is sent to the client.
 1304: sub pong_handler {
 1305:     my ($cmd, $tail, $replyfd) = @_;
 1306: 
 1307:     my $reply=&Apache::lonnet::reply("ping",$clientname);
 1308:     &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail"); 
 1309:     return 1;
 1310: }
 1311: &register_handler("pong", \&pong_handler, 0, 1, 1);       # Pong unencoded, client or manager
 1312: 
 1313: #++
 1314: #      Called to establish an encrypted session key with the remote client.
 1315: #      Note that with secure lond, in most cases this function is never
 1316: #      invoked.  Instead, the secure session key is established either
 1317: #      via a local file that's locked down tight and only lives for a short
 1318: #      time, or via an ssl tunnel...and is generated from a bunch-o-random
 1319: #      bits from /dev/urandom, rather than the predictable pattern used by
 1320: #      by this sub.  This sub is only used in the old-style insecure
 1321: #      key negotiation.
 1322: # Parameters:
 1323: #      $cmd    - the actual keyword that invoked us.
 1324: #      $tail   - the tail of the request that invoked us.
 1325: #      $replyfd- File descriptor connected to the client
 1326: #  Implicit Inputs:
 1327: #      $currenthostid - Global variable that carries the name of the host
 1328: #                       known as.
 1329: #      $clientname    - Global variable that carries the name of the host we're connected to.
 1330: #  Returns:
 1331: #      1       - Ok to continue processing.
 1332: #      0       - Program should exit.
 1333: #  Implicit Outputs:
 1334: #      Reply information is sent to the client.
 1335: #      $cipher is set with a reference to a new IDEA encryption object.
 1336: #
 1337: sub establish_key_handler {
 1338:     my ($cmd, $tail, $replyfd) = @_;
 1339: 
 1340:     my $buildkey=time.$$.int(rand 100000);
 1341:     $buildkey=~tr/1-6/A-F/;
 1342:     $buildkey=int(rand 100000).$buildkey.int(rand 100000);
 1343:     my $key=$currenthostid.$clientname;
 1344:     $key=~tr/a-z/A-Z/;
 1345:     $key=~tr/G-P/0-9/;
 1346:     $key=~tr/Q-Z/0-9/;
 1347:     $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
 1348:     $key=substr($key,0,32);
 1349:     my $cipherkey=pack("H32",$key);
 1350:     $cipher=new IDEA $cipherkey;
 1351:     &Reply($replyfd, \$buildkey, "$cmd:$tail"); 
 1352:    
 1353:     return 1;
 1354: 
 1355: }
 1356: &register_handler("ekey", \&establish_key_handler, 0, 1,1);
 1357: 
 1358: #     Handler for the load command.  Returns the current system load average
 1359: #     to the requestor.
 1360: #
 1361: # Parameters:
 1362: #      $cmd    - the actual keyword that invoked us.
 1363: #      $tail   - the tail of the request that invoked us.
 1364: #      $replyfd- File descriptor connected to the client
 1365: #  Implicit Inputs:
 1366: #      $currenthostid - Global variable that carries the name of the host
 1367: #                       known as.
 1368: #      $clientname    - Global variable that carries the name of the host we're connected to.
 1369: #  Returns:
 1370: #      1       - Ok to continue processing.
 1371: #      0       - Program should exit.
 1372: #  Side effects:
 1373: #      Reply information is sent to the client.
 1374: sub load_handler {
 1375:     my ($cmd, $tail, $replyfd) = @_;
 1376: 
 1377: 
 1378: 
 1379:    # Get the load average from /proc/loadavg and calculate it as a percentage of
 1380:    # the allowed load limit as set by the perl global variable lonLoadLim
 1381: 
 1382:     my $loadavg;
 1383:     my $loadfile=IO::File->new('/proc/loadavg');
 1384:    
 1385:     $loadavg=<$loadfile>;
 1386:     $loadavg =~ s/\s.*//g;                      # Extract the first field only.
 1387:    
 1388:     my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
 1389: 
 1390:     &Reply( $replyfd, \$loadpercent, "$cmd:$tail");
 1391:    
 1392:     return 1;
 1393: }
 1394: &register_handler("load", \&load_handler, 0, 1, 0);
 1395: 
 1396: #
 1397: #   Process the userload request.  This sub returns to the client the current
 1398: #  user load average.  It can be invoked either by clients or managers.
 1399: #
 1400: # Parameters:
 1401: #      $cmd    - the actual keyword that invoked us.
 1402: #      $tail   - the tail of the request that invoked us.
 1403: #      $replyfd- File descriptor connected to the client
 1404: #  Implicit Inputs:
 1405: #      $currenthostid - Global variable that carries the name of the host
 1406: #                       known as.
 1407: #      $clientname    - Global variable that carries the name of the host we're connected to.
 1408: #  Returns:
 1409: #      1       - Ok to continue processing.
 1410: #      0       - Program should exit
 1411: # Implicit inputs:
 1412: #     whatever the userload() function requires.
 1413: #  Implicit outputs:
 1414: #     the reply is written to the client.
 1415: #
 1416: sub user_load_handler {
 1417:     my ($cmd, $tail, $replyfd) = @_;
 1418: 
 1419:     my $userloadpercent=&Apache::lonnet::userload();
 1420:     &Reply($replyfd, \$userloadpercent, "$cmd:$tail");
 1421:     
 1422:     return 1;
 1423: }
 1424: &register_handler("userload", \&user_load_handler, 0, 1, 0);
 1425: 
 1426: #   Process a request for the authorization type of a user:
 1427: #   (userauth).
 1428: #
 1429: # Parameters:
 1430: #      $cmd    - the actual keyword that invoked us.
 1431: #      $tail   - the tail of the request that invoked us.
 1432: #      $replyfd- File descriptor connected to the client
 1433: #  Returns:
 1434: #      1       - Ok to continue processing.
 1435: #      0       - Program should exit
 1436: # Implicit outputs:
 1437: #    The user authorization type is written to the client.
 1438: #
 1439: sub user_authorization_type {
 1440:     my ($cmd, $tail, $replyfd) = @_;
 1441:    
 1442:     my $userinput = "$cmd:$tail";
 1443:    
 1444:     #  Pull the domain and username out of the command tail.
 1445:     # and call get_auth_type to determine the authentication type.
 1446:    
 1447:     my ($udom,$uname)=split(/:/,$tail);
 1448:     my $result = &get_auth_type($udom, $uname);
 1449:     if($result eq "nouser") {
 1450: 	&Failure( $replyfd, "unknown_user\n", $userinput);
 1451:     } else {
 1452: 	#
 1453: 	# We only want to pass the second field from get_auth_type
 1454: 	# for ^krb.. otherwise we'll be handing out the encrypted
 1455: 	# password for internals e.g.
 1456: 	#
 1457: 	my ($type,$otherinfo) = split(/:/,$result);
 1458: 	if($type =~ /^krb/) {
 1459: 	    $type = $result;
 1460: 	} else {
 1461:             $type .= ':';
 1462:         }
 1463: 	&Reply( $replyfd, \$type, $userinput);
 1464:     }
 1465:   
 1466:     return 1;
 1467: }
 1468: &register_handler("currentauth", \&user_authorization_type, 1, 1, 0);
 1469: 
 1470: #   Process a request by a manager to push a hosts or domain table 
 1471: #   to us.  We pick apart the command and pass it on to the subs
 1472: #   that already exist to do this.
 1473: #
 1474: # Parameters:
 1475: #      $cmd    - the actual keyword that invoked us.
 1476: #      $tail   - the tail of the request that invoked us.
 1477: #      $client - File descriptor connected to the client
 1478: #  Returns:
 1479: #      1       - Ok to continue processing.
 1480: #      0       - Program should exit
 1481: # Implicit Output:
 1482: #    a reply is written to the client.
 1483: sub push_file_handler {
 1484:     my ($cmd, $tail, $client) = @_;
 1485:     &Debug("In push file handler");
 1486:     my $userinput = "$cmd:$tail";
 1487: 
 1488:     # At this time we only know that the IP of our partner is a valid manager
 1489:     # the code below is a hook to do further authentication (e.g. to resolve
 1490:     # spoofing).
 1491: 
 1492:     my $cert = &GetCertificate($userinput);
 1493:     if(&ValidManager($cert)) {
 1494: 	&Debug("Valid manager: $client");
 1495: 
 1496: 	# Now presumably we have the bona fides of both the peer host and the
 1497: 	# process making the request.
 1498:       
 1499: 	my $reply = &PushFile($userinput);
 1500: 	&Reply($client, \$reply, $userinput);
 1501: 
 1502:     } else {
 1503: 	&logthis("push_file_handler $client is not valid");
 1504: 	&Failure( $client, "refused\n", $userinput);
 1505:     } 
 1506:     return 1;
 1507: }
 1508: &register_handler("pushfile", \&push_file_handler, 1, 0, 1);
 1509: 
 1510: # The du_handler routine should be considered obsolete and is retained
 1511: # for communication with legacy servers.  Please see the du2_handler.
 1512: #
 1513: #   du  - list the disk usage of a directory recursively. 
 1514: #    
 1515: #   note: stolen code from the ls file handler
 1516: #   under construction by Rick Banghart 
 1517: #    .
 1518: # Parameters:
 1519: #    $cmd        - The command that dispatched us (du).
 1520: #    $ududir     - The directory path to list... I'm not sure what this
 1521: #                  is relative as things like ls:. return e.g.
 1522: #                  no_such_dir.
 1523: #    $client     - Socket open on the client.
 1524: # Returns:
 1525: #     1 - indicating that the daemon should not disconnect.
 1526: # Side Effects:
 1527: #   The reply is written to  $client.
 1528: #
 1529: sub du_handler {
 1530:     my ($cmd, $ududir, $client) = @_;
 1531:     ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
 1532:     my $userinput = "$cmd:$ududir";
 1533: 
 1534:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
 1535: 	&Failure($client,"refused\n","$cmd:$ududir");
 1536: 	return 1;
 1537:     }
 1538:     #  Since $ududir could have some nasties in it,
 1539:     #  we will require that ududir is a valid
 1540:     #  directory.  Just in case someone tries to
 1541:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
 1542:     #  etc.
 1543:     #
 1544:     if (-d $ududir) {
 1545: 	my $total_size=0;
 1546: 	my $code=sub { 
 1547: 	    if ($_=~/\.\d+\./) { return;} 
 1548: 	    if ($_=~/\.meta$/) { return;}
 1549: 	    if (-d $_)         { return;}
 1550: 	    $total_size+=(stat($_))[7];
 1551: 	};
 1552: 	chdir($ududir);
 1553: 	find($code,$ududir);
 1554: 	$total_size=int($total_size/1024);
 1555: 	&Reply($client,\$total_size,"$cmd:$ududir");
 1556:     } else {
 1557: 	&Failure($client, "bad_directory:$ududir\n","$cmd:$ududir"); 
 1558:     }
 1559:     return 1;
 1560: }
 1561: &register_handler("du", \&du_handler, 0, 1, 0);
 1562: 
 1563: # Please also see the du_handler, which is obsoleted by du2. 
 1564: # du2_handler differs from du_handler in that required path to directory
 1565: # provided by &propath() is prepended in the handler instead of on the 
 1566: # client side.
 1567: #
 1568: #   du2  - list the disk usage of a directory recursively.
 1569: #
 1570: # Parameters:
 1571: #    $cmd        - The command that dispatched us (du).
 1572: #    $tail       - The tail of the request that invoked us.
 1573: #                  $tail is a : separated list of the following:
 1574: #                   - $ududir - directory path to list (before prepending)
 1575: #                   - $getpropath = 1 if &propath() should prepend
 1576: #                   - $uname - username to use for &propath or user dir
 1577: #                   - $udom - domain to use for &propath or user dir
 1578: #                   All are escaped.
 1579: #    $client     - Socket open on the client.
 1580: # Returns:
 1581: #     1 - indicating that the daemon should not disconnect.
 1582: # Side Effects:
 1583: #   The reply is written to $client.
 1584: #
 1585: 
 1586: sub du2_handler {
 1587:     my ($cmd, $tail, $client) = @_;
 1588:     my ($ududir,$getpropath,$uname,$udom) = map { &unescape($_) } (split(/:/, $tail));
 1589:     my $userinput = "$cmd:$tail";
 1590:     if (($ududir=~/\.\./) || (($ududir!~m|^/home/httpd/|) && (!$getpropath))) {
 1591:         &Failure($client,"refused\n","$cmd:$tail");
 1592:         return 1;
 1593:     }
 1594:     if ($getpropath) {
 1595:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
 1596:             $ududir = &propath($udom,$uname).'/'.$ududir;
 1597:         } else {
 1598:             &Failure($client,"refused\n","$cmd:$tail");
 1599:             return 1;
 1600:         }
 1601:     }
 1602:     #  Since $ududir could have some nasties in it,
 1603:     #  we will require that ududir is a valid
 1604:     #  directory.  Just in case someone tries to
 1605:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
 1606:     #  etc.
 1607:     #
 1608:     if (-d $ududir) {
 1609:         my $total_size=0;
 1610:         my $code=sub {
 1611:             if ($_=~/\.\d+\./) { return;}
 1612:             if ($_=~/\.meta$/) { return;}
 1613:             if (-d $_)         { return;}
 1614:             $total_size+=(stat($_))[7];
 1615:         };
 1616:         chdir($ududir);
 1617:         find($code,$ududir);
 1618:         $total_size=int($total_size/1024);
 1619:         &Reply($client,\$total_size,"$cmd:$ududir");
 1620:     } else {
 1621:         &Failure($client, "bad_directory:$ududir\n","$cmd:$tail");
 1622:     }
 1623:     return 1;
 1624: }
 1625: &register_handler("du2", \&du2_handler, 0, 1, 0);
 1626: 
 1627: #
 1628: # The ls_handler routine should be considered obsolete and is retained
 1629: # for communication with legacy servers.  Please see the ls3_handler.
 1630: #
 1631: #   ls  - list the contents of a directory.  For each file in the
 1632: #    selected directory the filename followed by the full output of
 1633: #    the stat function is returned.  The returned info for each
 1634: #    file are separated by ':'.  The stat fields are separated by &'s.
 1635: #
 1636: #    If the requested path contains /../ or is:
 1637: #
 1638: #    1. for a directory, and the path does not begin with one of:
 1639: #        (a) /home/httpd/html/res/<domain>
 1640: #        (b) /home/httpd/html/userfiles/
 1641: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
 1642: #    or is:
 1643: #
 1644: #    2. for a file, and the path (after prepending) does not begin with one of:
 1645: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
 1646: #        (b) /home/httpd/html/res/<domain>/<username>/
 1647: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
 1648: #
 1649: #    the response will be "refused".
 1650: #
 1651: # Parameters:
 1652: #    $cmd        - The command that dispatched us (ls).
 1653: #    $ulsdir     - The directory path to list... I'm not sure what this
 1654: #                  is relative as things like ls:. return e.g.
 1655: #                  no_such_dir.
 1656: #    $client     - Socket open on the client.
 1657: # Returns:
 1658: #     1 - indicating that the daemon should not disconnect.
 1659: # Side Effects:
 1660: #   The reply is written to  $client.
 1661: #
 1662: sub ls_handler {
 1663:     # obsoleted by ls2_handler
 1664:     my ($cmd, $ulsdir, $client) = @_;
 1665: 
 1666:     my $userinput = "$cmd:$ulsdir";
 1667: 
 1668:     my $obs;
 1669:     my $rights;
 1670:     my $ulsout='';
 1671:     my $ulsfn;
 1672:     if ($ulsdir =~m{/\.\./}) {
 1673:         &Failure($client,"refused\n",$userinput);
 1674:         return 1;
 1675:     }
 1676:     if (-e $ulsdir) {
 1677: 	if(-d $ulsdir) {
 1678:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
 1679:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
 1680:                 &Failure($client,"refused\n",$userinput);
 1681:                 return 1;
 1682:             }
 1683: 	    if (opendir(LSDIR,$ulsdir)) {
 1684: 		while ($ulsfn=readdir(LSDIR)) {
 1685: 		    undef($obs);
 1686: 		    undef($rights); 
 1687: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1688: 		    #We do some obsolete checking here
 1689: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
 1690: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
 1691: 			my @obsolete=<FILE>;
 1692: 			foreach my $obsolete (@obsolete) {
 1693: 			    if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
 1694: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
 1695: 			}
 1696: 		    }
 1697: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
 1698: 		    if($obs eq '1') { $ulsout.="&1"; }
 1699: 		    else { $ulsout.="&0"; }
 1700: 		    if($rights eq '1') { $ulsout.="&1:"; }
 1701: 		    else { $ulsout.="&0:"; }
 1702: 		}
 1703: 		closedir(LSDIR);
 1704: 	    }
 1705: 	} else {
 1706:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
 1707:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
 1708:                 &Failure($client,"refused\n",$userinput);
 1709:                 return 1;
 1710:             }
 1711: 	    my @ulsstats=stat($ulsdir);
 1712: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1713: 	}
 1714:     } else {
 1715: 	$ulsout='no_such_dir';
 1716:     }
 1717:     if ($ulsout eq '') { $ulsout='empty'; }
 1718:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
 1719:     
 1720:     return 1;
 1721: 
 1722: }
 1723: &register_handler("ls", \&ls_handler, 0, 1, 0);
 1724: 
 1725: # The ls2_handler routine should be considered obsolete and is retained
 1726: # for communication with legacy servers.  Please see the ls3_handler.
 1727: # Please also see the ls_handler, which was itself obsoleted by ls2.
 1728: # ls2_handler differs from ls_handler in that it escapes its return 
 1729: # values before concatenating them together with ':'s.
 1730: #
 1731: #   ls2  - list the contents of a directory.  For each file in the
 1732: #    selected directory the filename followed by the full output of
 1733: #    the stat function is returned.  The returned info for each
 1734: #    file are separated by ':'.  The stat fields are separated by &'s.
 1735: #
 1736: #    If the requested path contains /../ or is:
 1737: #
 1738: #    1. for a directory, and the path does not begin with one of:
 1739: #        (a) /home/httpd/html/res/<domain>
 1740: #        (b) /home/httpd/html/userfiles/
 1741: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
 1742: #    or is:
 1743: #
 1744: #    2. for a file, and the path (after prepending) does not begin with one of:
 1745: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
 1746: #        (b) /home/httpd/html/res/<domain>/<username>/
 1747: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
 1748: #
 1749: #    the response will be "refused".
 1750: #
 1751: # Parameters:
 1752: #    $cmd        - The command that dispatched us (ls).
 1753: #    $ulsdir     - The directory path to list... I'm not sure what this
 1754: #                  is relative as things like ls:. return e.g.
 1755: #                  no_such_dir.
 1756: #    $client     - Socket open on the client.
 1757: # Returns:
 1758: #     1 - indicating that the daemon should not disconnect.
 1759: # Side Effects:
 1760: #   The reply is written to  $client.
 1761: #
 1762: sub ls2_handler {
 1763:     my ($cmd, $ulsdir, $client) = @_;
 1764: 
 1765:     my $userinput = "$cmd:$ulsdir";
 1766: 
 1767:     my $obs;
 1768:     my $rights;
 1769:     my $ulsout='';
 1770:     my $ulsfn;
 1771:     if ($ulsdir =~m{/\.\./}) {
 1772:         &Failure($client,"refused\n",$userinput);
 1773:         return 1;
 1774:     }
 1775:     if (-e $ulsdir) {
 1776:         if(-d $ulsdir) {
 1777:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
 1778:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
 1779:                 &Failure($client,"refused\n","$userinput");
 1780:                 return 1;
 1781:             }
 1782:             if (opendir(LSDIR,$ulsdir)) {
 1783:                 while ($ulsfn=readdir(LSDIR)) {
 1784:                     undef($obs);
 1785: 		    undef($rights); 
 1786:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1787:                     #We do some obsolete checking here
 1788:                     if(-e $ulsdir.'/'.$ulsfn.".meta") { 
 1789:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
 1790:                         my @obsolete=<FILE>;
 1791:                         foreach my $obsolete (@obsolete) {
 1792:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
 1793:                             if($obsolete =~ m|(<copyright>)(default)|) {
 1794:                                 $rights = 1;
 1795:                             }
 1796:                         }
 1797:                     }
 1798:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
 1799:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1800:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1801:                     $ulsout.= &escape($tmp).':';
 1802:                 }
 1803:                 closedir(LSDIR);
 1804:             }
 1805:         } else {
 1806:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
 1807:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
 1808:                 &Failure($client,"refused\n",$userinput);
 1809:                 return 1;
 1810:             }
 1811:             my @ulsstats=stat($ulsdir);
 1812:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1813:         }
 1814:     } else {
 1815:         $ulsout='no_such_dir';
 1816:    }
 1817:    if ($ulsout eq '') { $ulsout='empty'; }
 1818:    &Reply($client, \$ulsout, $userinput); # This supports debug logging.
 1819:    return 1;
 1820: }
 1821: &register_handler("ls2", \&ls2_handler, 0, 1, 0);
 1822: #
 1823: #   ls3  - list the contents of a directory.  For each file in the
 1824: #    selected directory the filename followed by the full output of
 1825: #    the stat function is returned.  The returned info for each
 1826: #    file are separated by ':'.  The stat fields are separated by &'s.
 1827: #
 1828: #    If the requested path (after prepending) contains /../ or is:
 1829: #
 1830: #    1. for a directory, and the path does not begin with one of:
 1831: #        (a) /home/httpd/html/res/<domain>
 1832: #        (b) /home/httpd/html/userfiles/
 1833: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
 1834: #        (d) /home/httpd/html/priv/<domain> and client is the homeserver
 1835: #
 1836: #    or is:
 1837: #
 1838: #    2. for a file, and the path (after prepending) does not begin with one of:
 1839: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
 1840: #        (b) /home/httpd/html/res/<domain>/<username>/
 1841: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
 1842: #        (d) /home/httpd/html/priv/<domain>/<username>/ and client is the homeserver
 1843: #
 1844: #    the response will be "refused".
 1845: #
 1846: # Parameters:
 1847: #    $cmd        - The command that dispatched us (ls).
 1848: #    $tail       - The tail of the request that invoked us.
 1849: #                  $tail is a : separated list of the following:
 1850: #                   - $ulsdir - directory path to list (before prepending)
 1851: #                   - $getpropath = 1 if &propath() should prepend
 1852: #                   - $getuserdir = 1 if path to user dir in lonUsers should
 1853: #                                     prepend
 1854: #                   - $alternate_root - path to prepend
 1855: #                   - $uname - username to use for &propath or user dir
 1856: #                   - $udom - domain to use for &propath or user dir
 1857: #            All of these except $getpropath and &getuserdir are escaped.    
 1858: #                  no_such_dir.
 1859: #    $client     - Socket open on the client.
 1860: # Returns:
 1861: #     1 - indicating that the daemon should not disconnect.
 1862: # Side Effects:
 1863: #   The reply is written to $client.
 1864: #
 1865: 
 1866: sub ls3_handler {
 1867:     my ($cmd, $tail, $client) = @_;
 1868:     my $userinput = "$cmd:$tail";
 1869:     my ($ulsdir,$getpropath,$getuserdir,$alternate_root,$uname,$udom) =
 1870:         split(/:/,$tail);
 1871:     if (defined($ulsdir)) {
 1872:         $ulsdir = &unescape($ulsdir);
 1873:     }
 1874:     if (defined($alternate_root)) {
 1875:         $alternate_root = &unescape($alternate_root);
 1876:     }
 1877:     if (defined($uname)) {
 1878:         $uname = &unescape($uname);
 1879:     }
 1880:     if (defined($udom)) {
 1881:         $udom = &unescape($udom);
 1882:     }
 1883: 
 1884:     my $dir_root = $perlvar{'lonDocRoot'};
 1885:     if (($getpropath) || ($getuserdir)) {
 1886:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
 1887:             $dir_root = &propath($udom,$uname);
 1888:             $dir_root =~ s/\/$//;
 1889:         } else {
 1890:             &Failure($client,"refused\n",$userinput);
 1891:             return 1;
 1892:         }
 1893:     } elsif ($alternate_root ne '') {
 1894:         $dir_root = $alternate_root;
 1895:     }
 1896:     if (($dir_root ne '') && ($dir_root ne '/')) {
 1897:         if ($ulsdir =~ /^\//) {
 1898:             $ulsdir = $dir_root.$ulsdir;
 1899:         } else {
 1900:             $ulsdir = $dir_root.'/'.$ulsdir;
 1901:         }
 1902:     }
 1903:     if ($ulsdir =~m{/\.\./}) {
 1904:         &Failure($client,"refused\n",$userinput);
 1905:         return 1;
 1906:     }
 1907:     my $islocal;
 1908:     my @machine_ids = &Apache::lonnet::current_machine_ids();
 1909:     if (grep(/^\Q$clientname\E$/,@machine_ids)) {
 1910:         $islocal = 1;
 1911:     }
 1912:     my $obs;
 1913:     my $rights;
 1914:     my $ulsout='';
 1915:     my $ulsfn;
 1916: 
 1917:     my ($crscheck,$toplevel,$currdom,$currnum,$skip);
 1918:     unless ($islocal) {
 1919:         my ($major,$minor) = split(/\./,$clientversion);
 1920:         if (($major < 2) || ($major == 2 && $minor < 12)) {
 1921:             $crscheck = 1;
 1922:         }
 1923:     }
 1924:     if (-e $ulsdir) {
 1925:         if(-d $ulsdir) {
 1926:             unless (($getpropath) || ($getuserdir) ||
 1927:                     ($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
 1928:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles}) ||
 1929:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain}) && ($islocal))) {
 1930:                 &Failure($client,"refused\n",$userinput);
 1931:                 return 1;
 1932:             }
 1933:             if (($crscheck) &&
 1934:                 ($ulsdir =~ m{^/home/httpd/html/res/($LONCAPA::match_domain)(/?$|/$LONCAPA::match_courseid)})) {
 1935:                 ($currdom,my $posscnum) = ($1,$2);
 1936:                 if (($posscnum eq '') || ($posscnum eq '/')) {
 1937:                     $toplevel = 1;
 1938:                 } else {
 1939:                     $posscnum =~ s{^/+}{};
 1940:                     if (&LONCAPA::Lond::is_course($currdom,$posscnum)) {
 1941:                         $skip = 1;
 1942:                     }
 1943:                 }
 1944:             }
 1945:             if ((!$skip) && (opendir(LSDIR,$ulsdir))) {
 1946:                 while ($ulsfn=readdir(LSDIR)) {
 1947:                     if (($crscheck) && ($toplevel) && ($currdom ne '') &&
 1948:                         ($ulsfn =~ /^$LONCAPA::match_courseid$/) && (-d "$ulsdir/$ulsfn")) {
 1949:                         if (&LONCAPA::Lond::is_course($currdom,$ulsfn)) {
 1950:                             next;
 1951:                         }
 1952:                     }
 1953:                     undef($obs);
 1954:                     undef($rights);
 1955:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1956:                     #We do some obsolete checking here
 1957:                     if(-e $ulsdir.'/'.$ulsfn.".meta") {
 1958:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
 1959:                         my @obsolete=<FILE>;
 1960:                         foreach my $obsolete (@obsolete) {
 1961:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
 1962:                             if($obsolete =~ m|(<copyright>)(default)|) {
 1963:                                 $rights = 1;
 1964:                             }
 1965:                         }
 1966:                     }
 1967:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
 1968:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1969:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1970:                     $ulsout.= &escape($tmp).':';
 1971:                 }
 1972:                 closedir(LSDIR);
 1973:             }
 1974:         } else {
 1975:             unless (($getpropath) || ($getuserdir) ||
 1976:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
 1977:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/}) ||
 1978:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain/$LONCAPA::match_name/}) && ($islocal))) {
 1979:                 &Failure($client,"refused\n",$userinput);
 1980:                 return 1;
 1981:             }
 1982:             my @ulsstats=stat($ulsdir);
 1983:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1984:         }
 1985:     } else {
 1986:         $ulsout='no_such_dir';
 1987:     }
 1988:     if ($ulsout eq '') { $ulsout='empty'; }
 1989:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
 1990:     return 1;
 1991: }
 1992: &register_handler("ls3", \&ls3_handler, 0, 1, 0);
 1993: 
 1994: sub read_lonnet_global {
 1995:     my ($cmd,$tail,$client) = @_;
 1996:     my $userinput = "$cmd:$tail";
 1997:     my $requested = &Apache::lonnet::thaw_unescape($tail);
 1998:     my $result;
 1999:     my %packagevars = (
 2000:                         spareid => \%Apache::lonnet::spareid,
 2001:                         perlvar => \%Apache::lonnet::perlvar,
 2002:                       );
 2003:     my %limit_to = (
 2004:                     perlvar => {
 2005:                                  lonOtherAuthen  => 1,
 2006:                                  lonBalancer     => 1,
 2007:                                  lonVersion      => 1,
 2008:                                  lonAdmEMail     => 1,
 2009:                                  lonSupportEMail => 1,  
 2010:                                  lonSysEMail     => 1,
 2011:                                  lonHostID       => 1,
 2012:                                  lonRole         => 1,
 2013:                                  lonDefDomain    => 1,
 2014:                                  lonLoadLim      => 1,
 2015:                                  lonUserLoadLim  => 1,
 2016:                                }
 2017:                   );
 2018:     if (ref($requested) eq 'HASH') {
 2019:         foreach my $what (keys(%{$requested})) {
 2020:             my $response;
 2021:             my $items = {};
 2022:             if (exists($packagevars{$what})) {
 2023:                 if (ref($limit_to{$what}) eq 'HASH') {
 2024:                     foreach my $varname (keys(%{$packagevars{$what}})) {
 2025:                         if ($limit_to{$what}{$varname}) {
 2026:                             $items->{$varname} = $packagevars{$what}{$varname};
 2027:                         }
 2028:                     }
 2029:                 } else {
 2030:                     $items = $packagevars{$what};
 2031:                 }
 2032:                 if ($what eq 'perlvar') {
 2033:                     if (!exists($packagevars{$what}{'lonBalancer'})) {
 2034:                         if ($dist =~ /^(centos|rhes|fedora|scientific|oracle)/) {
 2035:                             my $othervarref=LONCAPA::Configuration::read_conf('httpd.conf');
 2036:                             if (ref($othervarref) eq 'HASH') {
 2037:                                 $items->{'lonBalancer'} = $othervarref->{'lonBalancer'};
 2038:                             }
 2039:                         }
 2040:                     }
 2041:                 }
 2042:                 $response = &Apache::lonnet::freeze_escape($items);
 2043:             }
 2044:             $result .= &escape($what).'='.$response.'&';
 2045:         }
 2046:     }
 2047:     $result =~ s/\&$//;
 2048:     &Reply($client,\$result,$userinput);
 2049:     return 1;
 2050: }
 2051: &register_handler("readlonnetglobal", \&read_lonnet_global, 0, 1, 0);
 2052: 
 2053: sub server_devalidatecache_handler {
 2054:     my ($cmd,$tail,$client) = @_;
 2055:     my $userinput = "$cmd:$tail";
 2056:     my $items = &unescape($tail);
 2057:     my @cached = split(/\&/,$items);
 2058:     foreach my $key (@cached) {
 2059:         if ($key =~ /:/) {
 2060:             my ($name,$id) = map { &unescape($_); } split(/:/,$key);
 2061:             &Apache::lonnet::devalidate_cache_new($name,$id);
 2062:         }
 2063:     }
 2064:     my $result = 'ok';
 2065:     &Reply($client,\$result,$userinput);
 2066:     return 1;
 2067: }
 2068: &register_handler("devalidatecache", \&server_devalidatecache_handler, 0, 1, 0);
 2069: 
 2070: sub server_timezone_handler {
 2071:     my ($cmd,$tail,$client) = @_;
 2072:     my $userinput = "$cmd:$tail";
 2073:     my $timezone;
 2074:     my $clockfile = '/etc/sysconfig/clock'; # Fedora/CentOS/SuSE
 2075:     my $tzfile = '/etc/timezone'; # Debian/Ubuntu
 2076:     if (-e $clockfile) {
 2077:         if (open(my $fh,"<$clockfile")) {
 2078:             while (<$fh>) {
 2079:                 next if (/^[\#\s]/);
 2080:                 if (/^(?:TIME)?ZONE\s*=\s*['"]?\s*([\w\/]+)/) {
 2081:                     $timezone = $1;
 2082:                     last;
 2083:                 }
 2084:             }
 2085:             close($fh);
 2086:         }
 2087:     } elsif (-e $tzfile) {
 2088:         if (open(my $fh,"<$tzfile")) {
 2089:             $timezone = <$fh>;
 2090:             close($fh);
 2091:             chomp($timezone);
 2092:             if ($timezone =~ m{^Etc/(\w+)$}) {
 2093:                 $timezone = $1;
 2094:             }
 2095:         }
 2096:     }
 2097:     &Reply($client,\$timezone,$userinput); # This supports debug logging.
 2098:     return 1;
 2099: }
 2100: &register_handler("servertimezone", \&server_timezone_handler, 0, 1, 0);
 2101: 
 2102: sub server_loncaparev_handler {
 2103:     my ($cmd,$tail,$client) = @_;
 2104:     my $userinput = "$cmd:$tail";
 2105:     &Reply($client,\$perlvar{'lonVersion'},$userinput);
 2106:     return 1;
 2107: }
 2108: &register_handler("serverloncaparev", \&server_loncaparev_handler, 0, 1, 0);
 2109: 
 2110: sub server_homeID_handler {
 2111:     my ($cmd,$tail,$client) = @_;
 2112:     my $userinput = "$cmd:$tail";
 2113:     &Reply($client,\$perlvar{'lonHostID'},$userinput);
 2114:     return 1;
 2115: }
 2116: &register_handler("serverhomeID", \&server_homeID_handler, 0, 1, 0);
 2117: 
 2118: sub server_distarch_handler {
 2119:     my ($cmd,$tail,$client) = @_;
 2120:     my $userinput = "$cmd:$tail";
 2121:     my $reply = &distro_and_arch();
 2122:     &Reply($client,\$reply,$userinput);
 2123:     return 1;
 2124: }
 2125: &register_handler("serverdistarch", \&server_distarch_handler, 0, 1, 0);
 2126: 
 2127: sub server_certs_handler {
 2128:     my ($cmd,$tail,$client) = @_;
 2129:     my $userinput = "$cmd:$tail";
 2130:     my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
 2131:     my $result = &LONCAPA::Lond::server_certs(\%perlvar,$perlvar{'lonHostID'},$hostname);
 2132:     &Reply($client,\$result,$userinput);
 2133:     return;
 2134: }
 2135: &register_handler("servercerts", \&server_certs_handler, 0, 1, 0);
 2136: 
 2137: #   Process a reinit request.  Reinit requests that either
 2138: #   lonc or lond be reinitialized so that an updated 
 2139: #   host.tab or domain.tab can be processed.
 2140: #
 2141: # Parameters:
 2142: #      $cmd    - the actual keyword that invoked us.
 2143: #      $tail   - the tail of the request that invoked us.
 2144: #      $client - File descriptor connected to the client
 2145: #  Returns:
 2146: #      1       - Ok to continue processing.
 2147: #      0       - Program should exit
 2148: #  Implicit output:
 2149: #     a reply is sent to the client.
 2150: #
 2151: sub reinit_process_handler {
 2152:     my ($cmd, $tail, $client) = @_;
 2153:    
 2154:     my $userinput = "$cmd:$tail";
 2155:    
 2156:     my $cert = &GetCertificate($userinput);
 2157:     if(&ValidManager($cert)) {
 2158: 	chomp($userinput);
 2159: 	my $reply = &ReinitProcess($userinput);
 2160: 	&Reply( $client,  \$reply, $userinput);
 2161:     } else {
 2162: 	&Failure( $client, "refused\n", $userinput);
 2163:     }
 2164:     return 1;
 2165: }
 2166: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
 2167: 
 2168: #  Process the editing script for a table edit operation.
 2169: #  the editing operation must be encrypted and requested by
 2170: #  a manager host.
 2171: #
 2172: # Parameters:
 2173: #      $cmd    - the actual keyword that invoked us.
 2174: #      $tail   - the tail of the request that invoked us.
 2175: #      $client - File descriptor connected to the client
 2176: #  Returns:
 2177: #      1       - Ok to continue processing.
 2178: #      0       - Program should exit
 2179: #  Implicit output:
 2180: #     a reply is sent to the client.
 2181: #
 2182: sub edit_table_handler {
 2183:     my ($command, $tail, $client) = @_;
 2184:    
 2185:     my $userinput = "$command:$tail";
 2186: 
 2187:     my $cert = &GetCertificate($userinput);
 2188:     if(&ValidManager($cert)) {
 2189: 	my($filetype, $script) = split(/:/, $tail);
 2190: 	if (($filetype eq "hosts") || 
 2191: 	    ($filetype eq "domain")) {
 2192: 	    if($script ne "") {
 2193: 		&Reply($client,              # BUGBUG - EditFile
 2194: 		      &EditFile($userinput), #   could fail.
 2195: 		      $userinput);
 2196: 	    } else {
 2197: 		&Failure($client,"refused\n",$userinput);
 2198: 	    }
 2199: 	} else {
 2200: 	    &Failure($client,"refused\n",$userinput);
 2201: 	}
 2202:     } else {
 2203: 	&Failure($client,"refused\n",$userinput);
 2204:     }
 2205:     return 1;
 2206: }
 2207: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
 2208: 
 2209: #
 2210: #   Authenticate a user against the LonCAPA authentication
 2211: #   database.  Note that there are several authentication
 2212: #   possibilities:
 2213: #   - unix     - The user can be authenticated against the unix
 2214: #                password file.
 2215: #   - internal - The user can be authenticated against a purely 
 2216: #                internal per user password file.
 2217: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
 2218: #                ticket granting authority.
 2219: #   - user     - The person tailoring LonCAPA can supply a user authentication
 2220: #                mechanism that is per system.
 2221: #
 2222: # Parameters:
 2223: #    $cmd      - The command that got us here.
 2224: #    $tail     - Tail of the command (remaining parameters).
 2225: #    $client   - File descriptor connected to client.
 2226: # Returns
 2227: #     0        - Requested to exit, caller should shut down.
 2228: #     1        - Continue processing.
 2229: # Implicit inputs:
 2230: #    The authentication systems describe above have their own forms of implicit
 2231: #    input into the authentication process that are described above.
 2232: #
 2233: sub authenticate_handler {
 2234:     my ($cmd, $tail, $client) = @_;
 2235: 
 2236:     
 2237:     #  Regenerate the full input line 
 2238:     
 2239:     my $userinput  = $cmd.":".$tail;
 2240:     
 2241:     #  udom    - User's domain.
 2242:     #  uname   - Username.
 2243:     #  upass   - User's password.
 2244:     #  checkdefauth - Pass to validate_user() to try authentication
 2245:     #                 with default auth type(s) if no user account.
 2246:     #  clientcancheckhost - Passed by clients with functionality in lonauth.pm
 2247:     #                       to check if session can be hosted.
 2248:     
 2249:     my ($udom, $uname, $upass, $checkdefauth, $clientcancheckhost)=split(/:/,$tail);
 2250:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass,  checkdefauth = $checkdefauth");
 2251:     chomp($upass);
 2252:     $upass=&unescape($upass);
 2253: 
 2254:     my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
 2255:     if($pwdcorrect) {
 2256:         my $canhost = 1;
 2257:         unless ($clientcancheckhost) {
 2258:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 2259:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 2260:             my @intdoms;
 2261:             my $internet_names = &Apache::lonnet::get_internet_names($clientname);
 2262:             if (ref($internet_names) eq 'ARRAY') {
 2263:                 @intdoms = @{$internet_names};
 2264:             }
 2265:             unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
 2266:                 my ($remote,$hosted);
 2267:                 my $remotesession = &get_usersession_config($udom,'remotesession');
 2268:                 if (ref($remotesession) eq 'HASH') {
 2269:                     $remote = $remotesession->{'remote'};
 2270:                 }
 2271:                 my $hostedsession = &get_usersession_config($clienthomedom,'hostedsession');
 2272:                 if (ref($hostedsession) eq 'HASH') {
 2273:                     $hosted = $hostedsession->{'hosted'};
 2274:                 }
 2275:                 $canhost = &Apache::lonnet::can_host_session($udom,$clientname,
 2276:                                                              $clientversion,
 2277:                                                              $remote,$hosted);
 2278:             }
 2279:         }
 2280:         if ($canhost) {               
 2281:             &Reply( $client, "authorized\n", $userinput);
 2282:         } else {
 2283:             &Reply( $client, "not_allowed_to_host\n", $userinput);
 2284:         }
 2285: 	#
 2286: 	#  Bad credentials: Failed to authorize
 2287: 	#
 2288:     } else {
 2289: 	&Failure( $client, "non_authorized\n", $userinput);
 2290:     }
 2291: 
 2292:     return 1;
 2293: }
 2294: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
 2295: 
 2296: #
 2297: #   Change a user's password.  Note that this function is complicated by
 2298: #   the fact that a user may be authenticated in more than one way:
 2299: #   At present, we are not able to change the password for all types of
 2300: #   authentication methods.  Only for:
 2301: #      unix    - unix password or shadow passoword style authentication.
 2302: #      local   - Locally written authentication mechanism.
 2303: #   For now, kerb4 and kerb5 password changes are not supported and result
 2304: #   in an error.
 2305: # FUTURE WORK:
 2306: #    Support kerberos passwd changes?
 2307: # Parameters:
 2308: #    $cmd      - The command that got us here.
 2309: #    $tail     - Tail of the command (remaining parameters).
 2310: #    $client   - File descriptor connected to client.
 2311: # Returns
 2312: #     0        - Requested to exit, caller should shut down.
 2313: #     1        - Continue processing.
 2314: # Implicit inputs:
 2315: #    The authentication systems describe above have their own forms of implicit
 2316: #    input into the authentication process that are described above.
 2317: sub change_password_handler {
 2318:     my ($cmd, $tail, $client) = @_;
 2319: 
 2320:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
 2321: 
 2322:     #
 2323:     #  udom  - user's domain.
 2324:     #  uname - Username.
 2325:     #  upass - Current password.
 2326:     #  npass - New password.
 2327:     #  context - Context in which this was called 
 2328:     #            (preferences or reset_by_email).
 2329:     #  lonhost - HostID of server where request originated 
 2330:    
 2331:     my ($udom,$uname,$upass,$npass,$context,$lonhost)=split(/:/,$tail);
 2332: 
 2333:     $upass=&unescape($upass);
 2334:     $npass=&unescape($npass);
 2335:     &Debug("Trying to change password for $uname");
 2336: 
 2337:     # First require that the user can be authenticated with their
 2338:     # old password unless context was 'reset_by_email':
 2339:     
 2340:     my ($validated,$failure);
 2341:     if ($context eq 'reset_by_email') {
 2342:         if ($lonhost eq '') {
 2343:             $failure = 'invalid_client';
 2344:         } else {
 2345:             $validated = 1;
 2346:         }
 2347:     } else {
 2348:         $validated = &validate_user($udom, $uname, $upass);
 2349:     }
 2350:     if($validated) {
 2351: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
 2352: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
 2353:         my $notunique;
 2354: 	if ($howpwd eq 'internal') {
 2355: 	    &Debug("internal auth");
 2356:             my $ncpass = &hash_passwd($udom,$npass);
 2357:             my (undef,$method,@rest) = split(/!/,$contentpwd);
 2358:             if ($method eq 'bcrypt') {
 2359:                 my %passwdconf = &Apache::lonnet::get_passwdconf($udom);
 2360:                 if (($passwdconf{'numsaved'}) && ($passwdconf{'numsaved'} =~ /^\d+$/)) {
 2361:                     my @oldpasswds;
 2362:                     my $userpath = &propath($udom,$uname);
 2363:                     my $fullpath = $userpath.'/oldpasswds';
 2364:                     if (-d $userpath) {
 2365:                         my @oldfiles;
 2366:                         if (-e $fullpath) {
 2367:                             if (opendir(my $dir,$fullpath)) {
 2368:                                 (@oldfiles) = grep(/^\d+$/,readdir($dir));
 2369:                                 closedir($dir);
 2370:                             }
 2371:                             if (@oldfiles) {
 2372:                                 @oldfiles = sort { $b <=> $a } (@oldfiles);
 2373:                                 my $numremoved = 0;
 2374:                                 for (my $i=0; $i<@oldfiles; $i++) {
 2375:                                     if ($i>=$passwdconf{'numsaved'}) {
 2376:                                         if (-f "$fullpath/$oldfiles[$i]") {
 2377:                                             if (unlink("$fullpath/$oldfiles[$i]")) {
 2378:                                                 $numremoved ++;
 2379:                                             }
 2380:                                         }
 2381:                                     } elsif (open(my $fh,'<',"$fullpath/$oldfiles[$i]")) {
 2382:                                         while (my $line = <$fh>) {
 2383:                                             push(@oldpasswds,$line);
 2384:                                         }
 2385:                                         close($fh);
 2386:                                     }
 2387:                                 }
 2388:                                 if ($numremoved) {
 2389:                                     &logthis("unlinked $numremoved old password files for $uname:$udom");
 2390:                                 }
 2391:                             }
 2392:                         }
 2393:                         push(@oldpasswds,$contentpwd);
 2394:                         foreach my $item (@oldpasswds) {
 2395:                             my (undef,$method,@rest) = split(/!/,$item);
 2396:                             if ($method eq 'bcrypt') {
 2397:                                 my $result = &hash_passwd($udom,$npass,@rest);
 2398:                                 if ($result eq $item) {
 2399:                                     $notunique = 1;
 2400:                                     last;
 2401:                                 }
 2402:                             }
 2403:                         }
 2404:                         unless ($notunique) {
 2405:                             unless (-e $fullpath) {
 2406:                                 if (&mkpath("$fullpath/")) {
 2407:                                     chmod(0700,$fullpath);
 2408:                                 }
 2409:                             }
 2410:                             if (-d $fullpath) {
 2411:                                 my $now = time;
 2412:                                 if (open(my $fh,'>',"$fullpath/$now")) {
 2413:                                     print $fh $contentpwd;
 2414:                                     close($fh);
 2415:                                     chmod(0400,"$fullpath/$now");
 2416:                                 }
 2417:                             }
 2418:                         }
 2419:                     }
 2420:                 }
 2421:             }
 2422:             if ($notunique) {
 2423:                 my $msg="Result of password change for $uname:$udom - password matches one used before";
 2424:                 if ($lonhost) {
 2425:                     $msg .= " - request originated from: $lonhost";
 2426:                 }
 2427:                 &logthis($msg);
 2428:                 &Reply($client, "prioruse\n", $userinput);
 2429: 	    } elsif (&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
 2430: 		my $msg="Result of password change for $uname: pwchange_success";
 2431:                 if ($lonhost) {
 2432:                     $msg .= " - request originated from: $lonhost";
 2433:                 }
 2434:                 &logthis($msg);
 2435:                 &update_passwd_history($uname,$udom,$howpwd,$context);
 2436: 		&Reply($client, "ok\n", $userinput);
 2437: 	    } else {
 2438: 		&logthis("Unable to open $uname passwd "               
 2439: 			 ."to change password");
 2440: 		&Failure( $client, "non_authorized\n",$userinput);
 2441: 	    }
 2442: 	} elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
 2443: 	    my $result = &change_unix_password($uname, $npass);
 2444:             if ($result eq 'ok') {
 2445:                 &update_passwd_history($uname,$udom,$howpwd,$context);
 2446:              }
 2447: 	    &logthis("Result of password change for $uname: ".
 2448: 		     $result);
 2449: 	    &Reply($client, \$result, $userinput);
 2450: 	} else {
 2451: 	    # this just means that the current password mode is not
 2452: 	    # one we know how to change (e.g the kerberos auth modes or
 2453: 	    # locally written auth handler).
 2454: 	    #
 2455: 	    &Failure( $client, "auth_mode_error\n", $userinput);
 2456: 	}  
 2457:     } else {
 2458: 	if ($failure eq '') {
 2459: 	    $failure = 'non_authorized';
 2460: 	}
 2461: 	&Failure( $client, "$failure\n", $userinput);
 2462:     }
 2463: 
 2464:     return 1;
 2465: }
 2466: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
 2467: 
 2468: sub hash_passwd {
 2469:     my ($domain,$plainpass,@rest) = @_;
 2470:     my ($salt,$cost);
 2471:     if (@rest) {
 2472:         $cost = $rest[0];
 2473:         # salt is first 22 characters, base-64 encoded by bcrypt
 2474:         my $plainsalt = substr($rest[1],0,22);
 2475:         $salt = Crypt::Eksblowfish::Bcrypt::de_base64($plainsalt);
 2476:     } else {
 2477:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2478:         my $defaultcost = $domdefaults{'intauth_cost'};
 2479:         if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
 2480:             $cost = 10;
 2481:         } else {
 2482:             $cost = $defaultcost;
 2483:         }
 2484:         # Generate random 16-octet base64 salt
 2485:         $salt = "";
 2486:         $salt .= pack("C", int rand(256)) for 1..16;
 2487:     }
 2488:     my $hash = &Crypt::Eksblowfish::Bcrypt::bcrypt_hash({
 2489:         key_nul => 1,
 2490:         cost    => $cost,
 2491:         salt    => $salt,
 2492:     }, Digest::SHA::sha512(Encode::encode('UTF-8',$plainpass)));
 2493: 
 2494:     my $result = join("!", "", "bcrypt", sprintf("%02d",$cost),
 2495:                 &Crypt::Eksblowfish::Bcrypt::en_base64($salt).
 2496:                 &Crypt::Eksblowfish::Bcrypt::en_base64($hash));
 2497:     return $result;
 2498: }
 2499: 
 2500: #
 2501: #   Create a new user.  User in this case means a lon-capa user.
 2502: #   The user must either already exist in some authentication realm
 2503: #   like kerberos or the /etc/passwd.  If not, a user completely local to
 2504: #   this loncapa system is created.
 2505: #
 2506: # Parameters:
 2507: #    $cmd      - The command that got us here.
 2508: #    $tail     - Tail of the command (remaining parameters).
 2509: #    $client   - File descriptor connected to client.
 2510: # Returns
 2511: #     0        - Requested to exit, caller should shut down.
 2512: #     1        - Continue processing.
 2513: # Implicit inputs:
 2514: #    The authentication systems describe above have their own forms of implicit
 2515: #    input into the authentication process that are described above.
 2516: sub add_user_handler {
 2517: 
 2518:     my ($cmd, $tail, $client) = @_;
 2519: 
 2520: 
 2521:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
 2522:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
 2523: 
 2524:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
 2525: 
 2526: 
 2527:     if($udom eq $currentdomainid) { # Reject new users for other domains...
 2528: 	
 2529: 	my $oldumask=umask(0077);
 2530: 	chomp($npass);
 2531: 	$npass=&unescape($npass);
 2532: 	my $passfilename  = &password_path($udom, $uname);
 2533: 	&Debug("Password file created will be:".$passfilename);
 2534: 	if (-e $passfilename) {
 2535: 	    &Failure( $client, "already_exists\n", $userinput);
 2536: 	} else {
 2537: 	    my $fperror='';
 2538: 	    if (!&mkpath($passfilename)) {
 2539: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
 2540: 		    ."makeuser";
 2541: 	    }
 2542: 	    unless ($fperror) {
 2543: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
 2544:                                              $passfilename,'makeuser');
 2545: 		&Reply($client,\$result, $userinput);     #BUGBUG - could be fail
 2546: 	    } else {
 2547: 		&Failure($client, \$fperror, $userinput);
 2548: 	    }
 2549: 	}
 2550: 	umask($oldumask);
 2551:     }  else {
 2552: 	&Failure($client, "not_right_domain\n",
 2553: 		$userinput);	# Even if we are multihomed.
 2554:     
 2555:     }
 2556:     return 1;
 2557: 
 2558: }
 2559: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
 2560: 
 2561: #
 2562: #   Change the authentication method of a user.  Note that this may
 2563: #   also implicitly change the user's password if, for example, the user is
 2564: #   joining an existing authentication realm.  Known authentication realms at
 2565: #   this time are:
 2566: #    internal   - Purely internal password file (only loncapa knows this user)
 2567: #    local      - Institutionally written authentication module.
 2568: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
 2569: #    kerb4      - kerberos version 4
 2570: #    kerb5      - kerberos version 5
 2571: #
 2572: # Parameters:
 2573: #    $cmd      - The command that got us here.
 2574: #    $tail     - Tail of the command (remaining parameters).
 2575: #    $client   - File descriptor connected to client.
 2576: # Returns
 2577: #     0        - Requested to exit, caller should shut down.
 2578: #     1        - Continue processing.
 2579: # Implicit inputs:
 2580: #    The authentication systems describe above have their own forms of implicit
 2581: #    input into the authentication process that are described above.
 2582: # NOTE:
 2583: #   This is also used to change the authentication credential values (e.g. passwd).
 2584: #   
 2585: #
 2586: sub change_authentication_handler {
 2587: 
 2588:     my ($cmd, $tail, $client) = @_;
 2589:    
 2590:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
 2591: 
 2592:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
 2593:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
 2594:     if ($udom ne $currentdomainid) {
 2595: 	&Failure( $client, "not_right_domain\n", $client);
 2596:     } else {
 2597: 	
 2598: 	chomp($npass);
 2599: 	
 2600: 	$npass=&unescape($npass);
 2601: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
 2602: 	my $passfilename = &password_path($udom, $uname);
 2603: 	if ($passfilename) {	# Not allowed to create a new user!!
 2604: 	    # If just changing the unix passwd. need to arrange to run
 2605: 	    # passwd since otherwise make_passwd_file will fail as 
 2606: 	    # creation of unix authenticated users is no longer supported
 2607:             # except from the command line, when running make_domain_coordinator.pl
 2608: 
 2609: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
 2610: 		my $result = &change_unix_password($uname, $npass);
 2611: 		&logthis("Result of password change for $uname: ".$result);
 2612: 		if ($result eq "ok") {
 2613:                     &update_passwd_history($uname,$udom,$umode,'changeuserauth'); 
 2614: 		    &Reply($client, \$result);
 2615: 		} else {
 2616: 		    &Failure($client, \$result);
 2617: 		}
 2618: 	    } else {
 2619: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
 2620:                                              $passfilename,'changeuserauth');
 2621: 		#
 2622: 		#  If the current auth mode is internal, and the old auth mode was
 2623: 		#  unix, or krb*,  and the user is an author for this domain,
 2624: 		#  re-run manage_permissions for that role in order to be able
 2625: 		#  to take ownership of the construction space back to www:www
 2626: 		#
 2627: 
 2628: 
 2629: 		&Reply($client, \$result, $userinput);
 2630: 	    }
 2631: 	       
 2632: 
 2633: 	} else {	       
 2634: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
 2635: 	}
 2636:     }
 2637:     return 1;
 2638: }
 2639: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
 2640: 
 2641: sub update_passwd_history {
 2642:     my ($uname,$udom,$umode,$context) = @_;
 2643:     my $proname=&propath($udom,$uname);
 2644:     my $now = time;
 2645:     if (open(my $fh,">>$proname/passwd.log")) {
 2646:         print $fh "$now:$umode:$context\n";
 2647:         close($fh);
 2648:     }
 2649:     return;
 2650: }
 2651: 
 2652: #
 2653: #   Determines if this is the home server for a user.  The home server
 2654: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
 2655: #   to do is determine if this file exists.
 2656: #
 2657: # Parameters:
 2658: #    $cmd      - The command that got us here.
 2659: #    $tail     - Tail of the command (remaining parameters).
 2660: #    $client   - File descriptor connected to client.
 2661: # Returns
 2662: #     0        - Requested to exit, caller should shut down.
 2663: #     1        - Continue processing.
 2664: # Implicit inputs:
 2665: #    The authentication systems describe above have their own forms of implicit
 2666: #    input into the authentication process that are described above.
 2667: #
 2668: sub is_home_handler {
 2669:     my ($cmd, $tail, $client) = @_;
 2670:    
 2671:     my $userinput  = "$cmd:$tail";
 2672:    
 2673:     my ($udom,$uname)=split(/:/,$tail);
 2674:     chomp($uname);
 2675:     my $passfile = &password_filename($udom, $uname);
 2676:     if($passfile) {
 2677: 	&Reply( $client, "found\n", $userinput);
 2678:     } else {
 2679: 	&Failure($client, "not_found\n", $userinput);
 2680:     }
 2681:     return 1;
 2682: }
 2683: &register_handler("home", \&is_home_handler, 0,1,0);
 2684: 
 2685: #
 2686: #   Process an update request for a resource.
 2687: #   A resource has been modified that we hold a subscription to.
 2688: #   If the resource is not local, then we must update, or at least invalidate our
 2689: #   cached copy of the resource. 
 2690: # Parameters:
 2691: #    $cmd      - The command that got us here.
 2692: #    $tail     - Tail of the command (remaining parameters).
 2693: #    $client   - File descriptor connected to client.
 2694: # Returns
 2695: #     0        - Requested to exit, caller should shut down.
 2696: #     1        - Continue processing.
 2697: # Implicit inputs:
 2698: #    The authentication systems describe above have their own forms of implicit
 2699: #    input into the authentication process that are described above.
 2700: #
 2701: sub update_resource_handler {
 2702: 
 2703:     my ($cmd, $tail, $client) = @_;
 2704:    
 2705:     my $userinput = "$cmd:$tail";
 2706:    
 2707:     my $fname= $tail;		# This allows interactive testing
 2708: 
 2709: 
 2710:     my $ownership=ishome($fname);
 2711:     if ($ownership eq 'not_owner') {
 2712: 	if (-e $fname) {
 2713:             # Delete preview file, if exists
 2714:             unlink("$fname.tmp");
 2715:             # Get usage stats
 2716: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
 2717: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
 2718: 	    my $now=time;
 2719: 	    my $since=$now-$atime;
 2720:             # If the file has not been used within lonExpire seconds,
 2721:             # unsubscribe from it and delete local copy
 2722: 	    if ($since>$perlvar{'lonExpire'}) {
 2723: 		my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
 2724: 		&devalidate_meta_cache($fname);
 2725: 		unlink("$fname");
 2726: 		unlink("$fname.meta");
 2727: 	    } else {
 2728:             # Yes, this is in active use. Get a fresh copy. Since it might be in
 2729:             # very active use and huge (like a movie), copy it to "in.transfer" filename first.
 2730: 		my $transname="$fname.in.transfer";
 2731: 		my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
 2732: 		my $response;
 2733: # FIXME: cannot replicate files that take more than two minutes to transfer -- needs checking now 1200s timeout used
 2734: # for LWP request.
 2735: 		my $request=new HTTP::Request('GET',"$remoteurl");
 2736:                 $response=&LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,0,1);
 2737: 		if ($response->is_error()) {
 2738:                     my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
 2739:                     &devalidate_meta_cache($fname);
 2740:                     if (-e $transname) {
 2741:                         unlink($transname);
 2742:                     }
 2743:                     unlink($fname);
 2744: 		    my $message=$response->status_line;
 2745: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
 2746: 		} else {
 2747: 		    if ($remoteurl!~/\.meta$/) {
 2748: 			my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2749:                         my $mresponse = &LONCAPA::LWPReq::makerequest($clientname,$mrequest,$fname.'.meta',\%perlvar,120,0,1);
 2750: 			if ($mresponse->is_error()) {
 2751: 			    unlink($fname.'.meta');
 2752: 			}
 2753: 		    }
 2754:                     # we successfully transfered, copy file over to real name
 2755: 		    rename($transname,$fname);
 2756: 		    &devalidate_meta_cache($fname);
 2757: 		}
 2758: 	    }
 2759: 	    &Reply( $client, "ok\n", $userinput);
 2760: 	} else {
 2761: 	    &Failure($client, "not_found\n", $userinput);
 2762: 	}
 2763:     } else {
 2764: 	&Failure($client, "rejected\n", $userinput);
 2765:     }
 2766:     return 1;
 2767: }
 2768: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
 2769: 
 2770: sub devalidate_meta_cache {
 2771:     my ($url) = @_;
 2772:     use Cache::Memcached;
 2773:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
 2774:     $url = &Apache::lonnet::declutter($url);
 2775:     $url =~ s-\.meta$--;
 2776:     my $id = &escape('meta:'.$url);
 2777:     $memcache->delete($id);
 2778: }
 2779: 
 2780: #
 2781: #   Fetch a user file from a remote server to the user's home directory
 2782: #   userfiles subdir.
 2783: # Parameters:
 2784: #    $cmd      - The command that got us here.
 2785: #    $tail     - Tail of the command (remaining parameters).
 2786: #    $client   - File descriptor connected to client.
 2787: # Returns
 2788: #     0        - Requested to exit, caller should shut down.
 2789: #     1        - Continue processing.
 2790: #
 2791: sub fetch_user_file_handler {
 2792: 
 2793:     my ($cmd, $tail, $client) = @_;
 2794: 
 2795:     my $userinput = "$cmd:$tail";
 2796:     my $fname           = $tail;
 2797:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
 2798:     my $udir=&propath($udom,$uname).'/userfiles';
 2799:     unless (-e $udir) {
 2800: 	mkdir($udir,0770); 
 2801:     }
 2802:     Debug("fetch user file for $fname");
 2803:     if (-e $udir) {
 2804: 	$ufile=~s/^[\.\~]+//;
 2805: 
 2806: 	# IF necessary, create the path right down to the file.
 2807: 	# Note that any regular files in the way of this path are
 2808: 	# wiped out to deal with some earlier folly of mine.
 2809: 
 2810: 	if (!&mkpath($udir.'/'.$ufile)) {
 2811: 	    &Failure($client, "unable_to_create\n", $userinput);	    
 2812: 	}
 2813: 
 2814: 	my $destname=$udir.'/'.$ufile;
 2815: 	my $transname=$udir.'/'.$ufile.'.in.transit';
 2816:         my $clientprotocol=$Apache::lonnet::protocol{$clientname};
 2817:         $clientprotocol = 'http' if ($clientprotocol ne 'https');
 2818: 	my $clienthost = &Apache::lonnet::hostname($clientname);
 2819: 	my $remoteurl=$clientprotocol.'://'.$clienthost.'/userfiles/'.$fname;
 2820: 	my $response;
 2821: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
 2822: 	my $request=new HTTP::Request('GET',"$remoteurl");
 2823:         my $verifycert = 1;
 2824:         my @machine_ids = &Apache::lonnet::current_machine_ids();
 2825:         if (grep(/^\Q$clientname\E$/,@machine_ids)) {
 2826:             $verifycert = 0;
 2827:         }
 2828:         $response = &LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,$verifycert);
 2829: 	if ($response->is_error()) {
 2830: 	    unlink($transname);
 2831: 	    my $message=$response->status_line;
 2832: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
 2833: 	    &Failure($client, "failed\n", $userinput);
 2834: 	} else {
 2835: 	    Debug("Renaming $transname to $destname");
 2836: 	    if (!rename($transname,$destname)) {
 2837: 		&logthis("Unable to move $transname to $destname");
 2838: 		unlink($transname);
 2839: 		&Failure($client, "failed\n", $userinput);
 2840: 	    } else {
 2841:                 if ($fname =~ /^default.+\.(page|sequence)$/) {
 2842:                     my ($major,$minor) = split(/\./,$clientversion);
 2843:                     if (($major < 2) || ($major == 2 && $minor < 11)) {
 2844:                         my $now = time;
 2845:                         &Apache::lonnet::do_cache_new('crschange',$udom.'_'.$uname,$now,600);
 2846:                         my $key = &escape('internal.contentchange');
 2847:                         my $what = "$key=$now";
 2848:                         my $hashref = &tie_user_hash($udom,$uname,'environment',
 2849:                                                      &GDBM_WRCREAT(),"P",$what);
 2850:                         if ($hashref) {
 2851:                             $hashref->{$key}=$now;
 2852:                             if (!&untie_user_hash($hashref)) {
 2853:                                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
 2854:                                          "when updating internal.contentchange");
 2855:                             }
 2856:                         }
 2857:                     }
 2858:                 }
 2859: 		&Reply($client, "ok\n", $userinput);
 2860: 	    }
 2861: 	}   
 2862:     } else {
 2863: 	&Failure($client, "not_home\n", $userinput);
 2864:     }
 2865:     return 1;
 2866: }
 2867: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
 2868: 
 2869: #
 2870: #   Remove a file from a user's home directory userfiles subdirectory.
 2871: # Parameters:
 2872: #    cmd   - the Lond request keyword that got us here.
 2873: #    tail  - the part of the command past the keyword.
 2874: #    client- File descriptor connected with the client.
 2875: #
 2876: # Returns:
 2877: #    1    - Continue processing.
 2878: sub remove_user_file_handler {
 2879:     my ($cmd, $tail, $client) = @_;
 2880: 
 2881:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
 2882: 
 2883:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
 2884:     if ($ufile =~m|/\.\./|) {
 2885: 	# any files paths with /../ in them refuse 
 2886: 	# to deal with
 2887: 	&Failure($client, "refused\n", "$cmd:$tail");
 2888:     } else {
 2889: 	my $udir = &propath($udom,$uname);
 2890: 	if (-e $udir) {
 2891: 	    my $file=$udir.'/userfiles/'.$ufile;
 2892: 	    if (-e $file) {
 2893: 		#
 2894: 		#   If the file is a regular file unlink is fine...
 2895: 		#   However it's possible the client wants a dir 
 2896: 		#   removed, in which case rmdir is more appropriate.
 2897: 		#   Note: rmdir will only remove an empty directory.
 2898: 		#
 2899: 	        if (-f $file){
 2900: 		    unlink($file);
 2901:                     # for html files remove the associated .bak file 
 2902:                     # which may have been created by the editor.
 2903:                     if ($ufile =~ m{^((docs|supplemental)/(?:\d+|default)/\d+(?:|/.+)/)[^/]+\.x?html?$}i) {
 2904:                         my $path = $1;
 2905:                         if (-e $file.'.bak') {
 2906:                             unlink($file.'.bak');
 2907:                         }
 2908:                     }
 2909: 		} elsif(-d $file) {
 2910: 		    rmdir($file);
 2911: 		}
 2912: 		if (-e $file) {
 2913: 		    #  File is still there after we deleted it ?!?
 2914: 
 2915: 		    &Failure($client, "failed\n", "$cmd:$tail");
 2916: 		} else {
 2917: 		    &Reply($client, "ok\n", "$cmd:$tail");
 2918: 		}
 2919: 	    } else {
 2920: 		&Failure($client, "not_found\n", "$cmd:$tail");
 2921: 	    }
 2922: 	} else {
 2923: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 2924: 	}
 2925:     }
 2926:     return 1;
 2927: }
 2928: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
 2929: 
 2930: #
 2931: #   make a directory in a user's home directory userfiles subdirectory.
 2932: # Parameters:
 2933: #    cmd   - the Lond request keyword that got us here.
 2934: #    tail  - the part of the command past the keyword.
 2935: #    client- File descriptor connected with the client.
 2936: #
 2937: # Returns:
 2938: #    1    - Continue processing.
 2939: sub mkdir_user_file_handler {
 2940:     my ($cmd, $tail, $client) = @_;
 2941: 
 2942:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
 2943:     $dir=&unescape($dir);
 2944:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
 2945:     if ($ufile =~m|/\.\./|) {
 2946: 	# any files paths with /../ in them refuse 
 2947: 	# to deal with
 2948: 	&Failure($client, "refused\n", "$cmd:$tail");
 2949:     } else {
 2950: 	my $udir = &propath($udom,$uname);
 2951: 	if (-e $udir) {
 2952: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
 2953: 	    if (!&mkpath($newdir)) {
 2954: 		&Failure($client, "failed\n", "$cmd:$tail");
 2955: 	    }
 2956: 	    &Reply($client, "ok\n", "$cmd:$tail");
 2957: 	} else {
 2958: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 2959: 	}
 2960:     }
 2961:     return 1;
 2962: }
 2963: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
 2964: 
 2965: #
 2966: #   rename a file in a user's home directory userfiles subdirectory.
 2967: # Parameters:
 2968: #    cmd   - the Lond request keyword that got us here.
 2969: #    tail  - the part of the command past the keyword.
 2970: #    client- File descriptor connected with the client.
 2971: #
 2972: # Returns:
 2973: #    1    - Continue processing.
 2974: sub rename_user_file_handler {
 2975:     my ($cmd, $tail, $client) = @_;
 2976: 
 2977:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
 2978:     $old=&unescape($old);
 2979:     $new=&unescape($new);
 2980:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
 2981: 	# any files paths with /../ in them refuse to deal with
 2982: 	&Failure($client, "refused\n", "$cmd:$tail");
 2983:     } else {
 2984: 	my $udir = &propath($udom,$uname);
 2985: 	if (-e $udir) {
 2986: 	    my $oldfile=$udir.'/userfiles/'.$old;
 2987: 	    my $newfile=$udir.'/userfiles/'.$new;
 2988: 	    if (-e $newfile) {
 2989: 		&Failure($client, "exists\n", "$cmd:$tail");
 2990: 	    } elsif (! -e $oldfile) {
 2991: 		&Failure($client, "not_found\n", "$cmd:$tail");
 2992: 	    } else {
 2993: 		if (!rename($oldfile,$newfile)) {
 2994: 		    &Failure($client, "failed\n", "$cmd:$tail");
 2995: 		} else {
 2996: 		    &Reply($client, "ok\n", "$cmd:$tail");
 2997: 		}
 2998: 	    }
 2999: 	} else {
 3000: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 3001: 	}
 3002:     }
 3003:     return 1;
 3004: }
 3005: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
 3006: 
 3007: #
 3008: #  Checks if the specified user has an active session on the server
 3009: #  return ok if so, not_found if not
 3010: #
 3011: # Parameters:
 3012: #   cmd      - The request keyword that dispatched to tus.
 3013: #   tail     - The tail of the request (colon separated parameters).
 3014: #   client   - Filehandle open on the client.
 3015: # Return:
 3016: #    1.
 3017: sub user_has_session_handler {
 3018:     my ($cmd, $tail, $client) = @_;
 3019: 
 3020:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
 3021:     
 3022:     opendir(DIR,$perlvar{'lonIDsDir'});
 3023:     my $filename;
 3024:     while ($filename=readdir(DIR)) {
 3025: 	last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
 3026:     }
 3027:     if ($filename) {
 3028: 	&Reply($client, "ok\n", "$cmd:$tail");
 3029:     } else {
 3030: 	&Failure($client, "not_found\n", "$cmd:$tail");
 3031:     }
 3032:     return 1;
 3033: 
 3034: }
 3035: &register_handler("userhassession", \&user_has_session_handler, 0,1,0);
 3036: 
 3037: sub del_usersession_handler {
 3038:     my ($cmd, $tail, $client) = @_;
 3039: 
 3040:     my $result;
 3041:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
 3042:     if (($udom =~ /^$LONCAPA::match_domain$/) && ($uname =~ /^$LONCAPA::match_username$/)) {
 3043:         my $lonidsdir = $perlvar{'lonIDsDir'};
 3044:         if (-d $lonidsdir) {
 3045:             if (opendir(DIR,$lonidsdir)) {
 3046:                 my $filename;
 3047:                 while ($filename=readdir(DIR)) {
 3048:                     if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/) {
 3049:                         if (tie(my %oldenv,'GDBM_File',"$lonidsdir/$filename",
 3050:                                 &GDBM_READER(),0640)) {
 3051:                             my $linkedfile;
 3052:                             if (exists($oldenv{'user.linkedenv'})) {
 3053:                                 $linkedfile = $oldenv{'user.linkedenv'};
 3054:                             }
 3055:                             untie(%oldenv);
 3056:                             $result = unlink("$lonidsdir/$filename");
 3057:                             if ($result) {
 3058:                                 if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
 3059:                                     if (-l "$lonidsdir/$linkedfile.id") {
 3060:                                         unlink("$lonidsdir/$linkedfile.id");
 3061:                                     }
 3062:                                 }
 3063:                             }
 3064:                         } else {
 3065:                             $result = unlink("$lonidsdir/$filename");
 3066:                         }
 3067:                         last;
 3068:                     }
 3069:                 }
 3070:             }
 3071:         }
 3072:         if ($result == 1) {
 3073:             &Reply($client, "$result\n", "$cmd:$tail");
 3074:         } else {
 3075:             &Reply($client, "not_found\n", "$cmd:$tail");
 3076:         }
 3077:     } else {
 3078:         &Failure($client, "invalid_user\n", "$cmd:$tail");
 3079:     }
 3080:     return 1;
 3081: }
 3082: 
 3083: &register_handler("delusersession", \&del_usersession_handler, 0,1,0);
 3084: 
 3085: #
 3086: #  Authenticate access to a user file by checking that the token the user's 
 3087: #  passed also exists in their session file
 3088: #
 3089: # Parameters:
 3090: #   cmd      - The request keyword that dispatched to tus.
 3091: #   tail     - The tail of the request (colon separated parameters).
 3092: #   client   - Filehandle open on the client.
 3093: # Return:
 3094: #    1.
 3095: sub token_auth_user_file_handler {
 3096:     my ($cmd, $tail, $client) = @_;
 3097: 
 3098:     my ($fname, $session) = split(/:/, $tail);
 3099:     
 3100:     chomp($session);
 3101:     my $reply="non_auth";
 3102:     my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
 3103:     if (open(ENVIN,"$file")) {
 3104: 	flock(ENVIN,LOCK_SH);
 3105: 	tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
 3106: 	if (exists($disk_env{"userfile.$fname"})) {
 3107: 	    $reply="ok";
 3108: 	} else {
 3109: 	    foreach my $envname (keys(%disk_env)) {
 3110: 		if ($envname=~ m|^userfile\.\Q$fname\E|) {
 3111: 		    $reply="ok";
 3112: 		    last;
 3113: 		}
 3114: 	    }
 3115: 	}
 3116: 	untie(%disk_env);
 3117: 	close(ENVIN);
 3118: 	&Reply($client, \$reply, "$cmd:$tail");
 3119:     } else {
 3120: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
 3121:     }
 3122:     return 1;
 3123: 
 3124: }
 3125: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
 3126: 
 3127: #
 3128: #   Unsubscribe from a resource.
 3129: #
 3130: # Parameters:
 3131: #    $cmd      - The command that got us here.
 3132: #    $tail     - Tail of the command (remaining parameters).
 3133: #    $client   - File descriptor connected to client.
 3134: # Returns
 3135: #     0        - Requested to exit, caller should shut down.
 3136: #     1        - Continue processing.
 3137: #
 3138: sub unsubscribe_handler {
 3139:     my ($cmd, $tail, $client) = @_;
 3140: 
 3141:     my $userinput= "$cmd:$tail";
 3142:     
 3143:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
 3144: 
 3145:     &Debug("Unsubscribing $fname");
 3146:     if (-e $fname) {
 3147: 	&Debug("Exists");
 3148: 	&Reply($client, &unsub($fname,$clientip), $userinput);
 3149:     } else {
 3150: 	&Failure($client, "not_found\n", $userinput);
 3151:     }
 3152:     return 1;
 3153: }
 3154: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
 3155: 
 3156: #   Subscribe to a resource
 3157: #
 3158: # Parameters:
 3159: #    $cmd      - The command that got us here.
 3160: #    $tail     - Tail of the command (remaining parameters).
 3161: #    $client   - File descriptor connected to client.
 3162: # Returns
 3163: #     0        - Requested to exit, caller should shut down.
 3164: #     1        - Continue processing.
 3165: #
 3166: sub subscribe_handler {
 3167:     my ($cmd, $tail, $client)= @_;
 3168: 
 3169:     my $userinput  = "$cmd:$tail";
 3170: 
 3171:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
 3172: 
 3173:     return 1;
 3174: }
 3175: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
 3176: 
 3177: #
 3178: #   Determine the latest version of a resource (it looks for the highest
 3179: #   past version and then returns that +1)
 3180: #
 3181: # Parameters:
 3182: #    $cmd      - The command that got us here.
 3183: #    $tail     - Tail of the command (remaining parameters).
 3184: #                 (Should consist of an absolute path to a file)
 3185: #    $client   - File descriptor connected to client.
 3186: # Returns
 3187: #     0        - Requested to exit, caller should shut down.
 3188: #     1        - Continue processing.
 3189: #
 3190: sub current_version_handler {
 3191:     my ($cmd, $tail, $client) = @_;
 3192: 
 3193:     my $userinput= "$cmd:$tail";
 3194:    
 3195:     my $fname   = $tail;
 3196:     &Reply( $client, &currentversion($fname)."\n", $userinput);
 3197:     return 1;
 3198: 
 3199: }
 3200: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
 3201: 
 3202: #  Make an entry in a user's activity log.
 3203: #
 3204: # Parameters:
 3205: #    $cmd      - The command that got us here.
 3206: #    $tail     - Tail of the command (remaining parameters).
 3207: #    $client   - File descriptor connected to client.
 3208: # Returns
 3209: #     0        - Requested to exit, caller should shut down.
 3210: #     1        - Continue processing.
 3211: #
 3212: sub activity_log_handler {
 3213:     my ($cmd, $tail, $client) = @_;
 3214: 
 3215: 
 3216:     my $userinput= "$cmd:$tail";
 3217: 
 3218:     my ($udom,$uname,$what)=split(/:/,$tail);
 3219:     chomp($what);
 3220:     my $proname=&propath($udom,$uname);
 3221:     my $now=time;
 3222:     my $hfh;
 3223:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
 3224: 	print $hfh "$now:$clientname:$what\n";
 3225: 	&Reply( $client, "ok\n", $userinput); 
 3226:     } else {
 3227: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
 3228: 		 ."while attempting log\n", 
 3229: 		 $userinput);
 3230:     }
 3231: 
 3232:     return 1;
 3233: }
 3234: &register_handler("log", \&activity_log_handler, 0, 1, 0);
 3235: 
 3236: #
 3237: #   Put a namespace entry in a user profile hash.
 3238: #   My druthers would be for this to be an encrypted interaction too.
 3239: #   anything that might be an inadvertent covert channel about either
 3240: #   user authentication or user personal information....
 3241: #
 3242: # Parameters:
 3243: #    $cmd      - The command that got us here.
 3244: #    $tail     - Tail of the command (remaining parameters).
 3245: #    $client   - File descriptor connected to client.
 3246: # Returns
 3247: #     0        - Requested to exit, caller should shut down.
 3248: #     1        - Continue processing.
 3249: #
 3250: sub put_user_profile_entry {
 3251:     my ($cmd, $tail, $client)  = @_;
 3252: 
 3253:     my $userinput = "$cmd:$tail";
 3254:     
 3255:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
 3256:     if ($namespace ne 'roles') {
 3257: 	chomp($what);
 3258: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3259: 				  &GDBM_WRCREAT(),"P",$what);
 3260: 	if($hashref) {
 3261: 	    my @pairs=split(/\&/,$what);
 3262: 	    foreach my $pair (@pairs) {
 3263: 		my ($key,$value)=split(/=/,$pair);
 3264: 		$hashref->{$key}=$value;
 3265: 	    }
 3266: 	    if (&untie_user_hash($hashref)) {
 3267: 		&Reply( $client, "ok\n", $userinput);
 3268: 	    } else {
 3269: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 3270: 			"while attempting put\n", 
 3271: 			$userinput);
 3272: 	    }
 3273: 	} else {
 3274: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3275: 		     "while attempting put\n", $userinput);
 3276: 	}
 3277:     } else {
 3278:         &Failure( $client, "refused\n", $userinput);
 3279:     }
 3280:     
 3281:     return 1;
 3282: }
 3283: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
 3284: 
 3285: #   Put a piece of new data in hash, returns error if entry already exists
 3286: # Parameters:
 3287: #    $cmd      - The command that got us here.
 3288: #    $tail     - Tail of the command (remaining parameters).
 3289: #    $client   - File descriptor connected to client.
 3290: # Returns
 3291: #     0        - Requested to exit, caller should shut down.
 3292: #     1        - Continue processing.
 3293: #
 3294: sub newput_user_profile_entry {
 3295:     my ($cmd, $tail, $client)  = @_;
 3296: 
 3297:     my $userinput = "$cmd:$tail";
 3298: 
 3299:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
 3300:     if ($namespace eq 'roles') {
 3301:         &Failure( $client, "refused\n", $userinput);
 3302: 	return 1;
 3303:     }
 3304: 
 3305:     chomp($what);
 3306: 
 3307:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3308: 				 &GDBM_WRCREAT(),"N",$what);
 3309:     if(!$hashref) {
 3310: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3311: 		  "while attempting put\n", $userinput);
 3312: 	return 1;
 3313:     }
 3314: 
 3315:     my @pairs=split(/\&/,$what);
 3316:     foreach my $pair (@pairs) {
 3317: 	my ($key,$value)=split(/=/,$pair);
 3318: 	if (exists($hashref->{$key})) {
 3319:             if (!&untie_user_hash($hashref)) {
 3320:                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
 3321:                          "while attempting newput - early out as key exists");
 3322:             }
 3323:             &Failure($client, "key_exists: ".$key."\n",$userinput);
 3324:             return 1;
 3325: 	}
 3326:     }
 3327: 
 3328:     foreach my $pair (@pairs) {
 3329: 	my ($key,$value)=split(/=/,$pair);
 3330: 	$hashref->{$key}=$value;
 3331:     }
 3332: 
 3333:     if (&untie_user_hash($hashref)) {
 3334: 	&Reply( $client, "ok\n", $userinput);
 3335:     } else {
 3336: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 3337: 		 "while attempting put\n", 
 3338: 		 $userinput);
 3339:     }
 3340:     return 1;
 3341: }
 3342: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
 3343: 
 3344: # 
 3345: #   Increment a profile entry in the user history file.
 3346: #   The history contains keyword value pairs.  In this case,
 3347: #   The value itself is a pair of numbers.  The first, the current value
 3348: #   the second an increment that this function applies to the current
 3349: #   value.
 3350: #
 3351: # Parameters:
 3352: #    $cmd      - The command that got us here.
 3353: #    $tail     - Tail of the command (remaining parameters).
 3354: #    $client   - File descriptor connected to client.
 3355: # Returns
 3356: #     0        - Requested to exit, caller should shut down.
 3357: #     1        - Continue processing.
 3358: #
 3359: sub increment_user_value_handler {
 3360:     my ($cmd, $tail, $client) = @_;
 3361:     
 3362:     my $userinput   = "$cmd:$tail";
 3363:     
 3364:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
 3365:     if ($namespace ne 'roles') {
 3366:         chomp($what);
 3367: 	my $hashref = &tie_user_hash($udom, $uname,
 3368: 				     $namespace, &GDBM_WRCREAT(),
 3369: 				     "P",$what);
 3370: 	if ($hashref) {
 3371: 	    my @pairs=split(/\&/,$what);
 3372: 	    foreach my $pair (@pairs) {
 3373: 		my ($key,$value)=split(/=/,$pair);
 3374:                 $value = &unescape($value);
 3375: 		# We could check that we have a number...
 3376: 		if (! defined($value) || $value eq '') {
 3377: 		    $value = 1;
 3378: 		}
 3379: 		$hashref->{$key}+=$value;
 3380:                 if ($namespace eq 'nohist_resourcetracker') {
 3381:                     if ($hashref->{$key} < 0) {
 3382:                         $hashref->{$key} = 0;
 3383:                     }
 3384:                 }
 3385: 	    }
 3386: 	    if (&untie_user_hash($hashref)) {
 3387: 		&Reply( $client, "ok\n", $userinput);
 3388: 	    } else {
 3389: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 3390: 			 "while attempting inc\n", $userinput);
 3391: 	    }
 3392: 	} else {
 3393: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3394: 		     "while attempting inc\n", $userinput);
 3395: 	}
 3396:     } else {
 3397: 	&Failure($client, "refused\n", $userinput);
 3398:     }
 3399:     
 3400:     return 1;
 3401: }
 3402: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
 3403: 
 3404: #
 3405: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
 3406: #   Each 'role' a user has implies a set of permissions.  Adding a new role
 3407: #   for a person grants the permissions packaged with that role
 3408: #   to that user when the role is selected.
 3409: #
 3410: # Parameters:
 3411: #    $cmd       - The command string (rolesput).
 3412: #    $tail      - The remainder of the request line.  For rolesput this
 3413: #                 consists of a colon separated list that contains:
 3414: #                 The domain and user that is granting the role (logged).
 3415: #                 The domain and user that is getting the role.
 3416: #                 The roles being granted as a set of & separated pairs.
 3417: #                 each pair a key value pair.
 3418: #    $client    - File descriptor connected to the client.
 3419: # Returns:
 3420: #     0         - If the daemon should exit
 3421: #     1         - To continue processing.
 3422: #
 3423: #
 3424: sub roles_put_handler {
 3425:     my ($cmd, $tail, $client) = @_;
 3426: 
 3427:     my $userinput  = "$cmd:$tail";
 3428: 
 3429:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
 3430:     
 3431: 
 3432:     my $namespace='roles';
 3433:     chomp($what);
 3434:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3435: 				 &GDBM_WRCREAT(), "P",
 3436: 				 "$exedom:$exeuser:$what");
 3437:     #
 3438:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
 3439:     #  handle is open for the minimal amount of time.  Since the flush
 3440:     #  is done on close this improves the chances the log will be an un-
 3441:     #  corrupted ordered thing.
 3442:     if ($hashref) {
 3443: 	my $pass_entry = &get_auth_type($udom, $uname);
 3444: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
 3445: 	$auth_type = $auth_type.":";
 3446: 	my @pairs=split(/\&/,$what);
 3447: 	foreach my $pair (@pairs) {
 3448: 	    my ($key,$value)=split(/=/,$pair);
 3449: 	    &manage_permissions($key, $udom, $uname,
 3450: 			       $auth_type);
 3451: 	    $hashref->{$key}=$value;
 3452: 	}
 3453: 	if (&untie_user_hash($hashref)) {
 3454: 	    &Reply($client, "ok\n", $userinput);
 3455: 	} else {
 3456: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 3457: 		     "while attempting rolesput\n", $userinput);
 3458: 	}
 3459:     } else {
 3460: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3461: 		 "while attempting rolesput\n", $userinput);
 3462:     }
 3463:     return 1;
 3464: }
 3465: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
 3466: 
 3467: #
 3468: #   Deletes (removes) a role for a user.   This is equivalent to removing
 3469: #  a permissions package associated with the role from the user's profile.
 3470: #
 3471: # Parameters:
 3472: #     $cmd                 - The command (rolesdel)
 3473: #     $tail                - The remainder of the request line. This consists
 3474: #                             of:
 3475: #                             The domain and user requesting the change (logged)
 3476: #                             The domain and user being changed.
 3477: #                             The roles being revoked.  These are shipped to us
 3478: #                             as a bunch of & separated role name keywords.
 3479: #     $client              - The file handle open on the client.
 3480: # Returns:
 3481: #     1                    - Continue processing
 3482: #     0                    - Exit.
 3483: #
 3484: sub roles_delete_handler {
 3485:     my ($cmd, $tail, $client)  = @_;
 3486: 
 3487:     my $userinput    = "$cmd:$tail";
 3488:    
 3489:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
 3490:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
 3491: 	   "what = ".$what);
 3492:     my $namespace='roles';
 3493:     chomp($what);
 3494:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3495: 				 &GDBM_WRCREAT(), "D",
 3496: 				 "$exedom:$exeuser:$what");
 3497:     
 3498:     if ($hashref) {
 3499: 	my @rolekeys=split(/\&/,$what);
 3500: 	
 3501: 	foreach my $key (@rolekeys) {
 3502: 	    delete $hashref->{$key};
 3503: 	}
 3504: 	if (&untie_user_hash($hashref)) {
 3505: 	    &Reply($client, "ok\n", $userinput);
 3506: 	} else {
 3507: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 3508: 		     "while attempting rolesdel\n", $userinput);
 3509: 	}
 3510:     } else {
 3511:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3512: 		 "while attempting rolesdel\n", $userinput);
 3513:     }
 3514:     
 3515:     return 1;
 3516: }
 3517: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
 3518: 
 3519: # Unencrypted get from a user's profile database.  See 
 3520: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
 3521: # This function retrieves a keyed item from a specific named database in the
 3522: # user's directory.
 3523: #
 3524: # Parameters:
 3525: #   $cmd             - Command request keyword (get).
 3526: #   $tail            - Tail of the command.  This is a colon separated list
 3527: #                      consisting of the domain and username that uniquely
 3528: #                      identifies the profile,
 3529: #                      The 'namespace' which selects the gdbm file to 
 3530: #                      do the lookup in, 
 3531: #                      & separated list of keys to lookup.  Note that
 3532: #                      the values are returned as an & separated list too.
 3533: #   $client          - File descriptor open on the client.
 3534: # Returns:
 3535: #   1       - Continue processing.
 3536: #   0       - Exit.
 3537: #
 3538: sub get_profile_entry {
 3539:     my ($cmd, $tail, $client) = @_;
 3540: 
 3541:     my $userinput= "$cmd:$tail";
 3542:    
 3543:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 3544:     chomp($what);
 3545: 
 3546: 
 3547:     my $replystring = read_profile($udom, $uname, $namespace, $what);
 3548:     my ($first) = split(/:/,$replystring);
 3549:     if($first ne "error") {
 3550: 	&Reply($client, \$replystring, $userinput);
 3551:     } else {
 3552: 	&Failure($client, $replystring." while attempting get\n", $userinput);
 3553:     }
 3554:     return 1;
 3555: 
 3556: 
 3557: }
 3558: &register_handler("get", \&get_profile_entry, 0,1,0);
 3559: 
 3560: #
 3561: #  Process the encrypted get request.  Note that the request is sent
 3562: #  in clear, but the reply is encrypted.  This is a small covert channel:
 3563: #  information about the sensitive keys is given to the snooper.  Just not
 3564: #  information about the values of the sensitive key.  Hmm if I wanted to
 3565: #  know these I'd snoop for the egets. Get the profile item names from them
 3566: #  and then issue a get for them since there's no enforcement of the
 3567: #  requirement of an encrypted get for particular profile items.  If I
 3568: #  were re-doing this, I'd force the request to be encrypted as well as the
 3569: #  reply.  I'd also just enforce encrypted transactions for all gets since
 3570: #  that would prevent any covert channel snooping.
 3571: #
 3572: #  Parameters:
 3573: #     $cmd               - Command keyword of request (eget).
 3574: #     $tail              - Tail of the command.  See GetProfileEntry
 3575: #                          for more information about this.
 3576: #     $client            - File open on the client.
 3577: #  Returns:
 3578: #     1      - Continue processing
 3579: #     0      - server should exit.
 3580: sub get_profile_entry_encrypted {
 3581:     my ($cmd, $tail, $client) = @_;
 3582: 
 3583:     my $userinput = "$cmd:$tail";
 3584:    
 3585:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 3586:     chomp($what);
 3587:     my $qresult = read_profile($udom, $uname, $namespace, $what);
 3588:     my ($first) = split(/:/, $qresult);
 3589:     if($first ne "error") {
 3590: 	
 3591: 	if ($cipher) {
 3592: 	    my $cmdlength=length($qresult);
 3593: 	    $qresult.="         ";
 3594: 	    my $encqresult='';
 3595: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 3596: 		$encqresult.= unpack("H16", 
 3597: 				     $cipher->encrypt(substr($qresult,
 3598: 							     $encidx,
 3599: 							     8)));
 3600: 	    }
 3601: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
 3602: 	} else {
 3603: 		&Failure( $client, "error:no_key\n", $userinput);
 3604: 	    }
 3605:     } else {
 3606: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
 3607: 
 3608:     }
 3609:     
 3610:     return 1;
 3611: }
 3612: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
 3613: 
 3614: #
 3615: #   Deletes a key in a user profile database.
 3616: #   
 3617: #   Parameters:
 3618: #       $cmd                  - Command keyword (del).
 3619: #       $tail                 - Command tail.  IN this case a colon
 3620: #                               separated list containing:
 3621: #                               The domain and user that identifies uniquely
 3622: #                               the identity of the user.
 3623: #                               The profile namespace (name of the profile
 3624: #                               database file).
 3625: #                               & separated list of keywords to delete.
 3626: #       $client              - File open on client socket.
 3627: # Returns:
 3628: #     1   - Continue processing
 3629: #     0   - Exit server.
 3630: #
 3631: #
 3632: sub delete_profile_entry {
 3633:     my ($cmd, $tail, $client) = @_;
 3634: 
 3635:     my $userinput = "cmd:$tail";
 3636: 
 3637:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 3638:     chomp($what);
 3639:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3640: 				 &GDBM_WRCREAT(),
 3641: 				 "D",$what);
 3642:     if ($hashref) {
 3643:         my @keys=split(/\&/,$what);
 3644: 	foreach my $key (@keys) {
 3645: 	    delete($hashref->{$key});
 3646: 	}
 3647: 	if (&untie_user_hash($hashref)) {
 3648: 	    &Reply($client, "ok\n", $userinput);
 3649: 	} else {
 3650: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3651: 		    "while attempting del\n", $userinput);
 3652: 	}
 3653:     } else {
 3654: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3655: 		 "while attempting del\n", $userinput);
 3656:     }
 3657:     return 1;
 3658: }
 3659: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
 3660: 
 3661: #
 3662: #  List the set of keys that are defined in a profile database file.
 3663: #  A successful reply from this will contain an & separated list of
 3664: #  the keys. 
 3665: # Parameters:
 3666: #     $cmd              - Command request (keys).
 3667: #     $tail             - Remainder of the request, a colon separated
 3668: #                         list containing domain/user that identifies the
 3669: #                         user being queried, and the database namespace
 3670: #                         (database filename essentially).
 3671: #     $client           - File open on the client.
 3672: #  Returns:
 3673: #    1    - Continue processing.
 3674: #    0    - Exit the server.
 3675: #
 3676: sub get_profile_keys {
 3677:     my ($cmd, $tail, $client) = @_;
 3678: 
 3679:     my $userinput = "$cmd:$tail";
 3680: 
 3681:     my ($udom,$uname,$namespace)=split(/:/,$tail);
 3682:     my $qresult='';
 3683:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3684: 				  &GDBM_READER());
 3685:     if ($hashref) {
 3686: 	foreach my $key (keys %$hashref) {
 3687: 	    $qresult.="$key&";
 3688: 	}
 3689: 	if (&untie_user_hash($hashref)) {
 3690: 	    $qresult=~s/\&$//;
 3691: 	    &Reply($client, \$qresult, $userinput);
 3692: 	} else {
 3693: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3694: 		    "while attempting keys\n", $userinput);
 3695: 	}
 3696:     } else {
 3697: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3698: 		 "while attempting keys\n", $userinput);
 3699:     }
 3700:    
 3701:     return 1;
 3702: }
 3703: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
 3704: 
 3705: #
 3706: #   Dump the contents of a user profile database.
 3707: #   Note that this constitutes a very large covert channel too since
 3708: #   the dump will return sensitive information that is not encrypted.
 3709: #   The naive security assumption is that the session negotiation ensures
 3710: #   our client is trusted and I don't believe that's assured at present.
 3711: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
 3712: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
 3713: # 
 3714: #  Parameters:
 3715: #     $cmd           - The command request keyword (currentdump).
 3716: #     $tail          - Remainder of the request, consisting of a colon
 3717: #                      separated list that has the domain/username and
 3718: #                      the namespace to dump (database file).
 3719: #     $client        - file open on the remote client.
 3720: # Returns:
 3721: #     1    - Continue processing.
 3722: #     0    - Exit the server.
 3723: #
 3724: sub dump_profile_database {
 3725:     my ($cmd, $tail, $client) = @_;
 3726: 
 3727:     my $res = LONCAPA::Lond::dump_profile_database($tail);
 3728: 
 3729:     if ($res =~ /^error:/) {
 3730:         Failure($client, \$res, "$cmd:$tail");
 3731:     } else {
 3732:         Reply($client, \$res, "$cmd:$tail");
 3733:     }
 3734: 
 3735:     return 1;  
 3736: 
 3737:     #TODO remove 
 3738:     my $userinput = "$cmd:$tail";
 3739:    
 3740:     my ($udom,$uname,$namespace) = split(/:/,$tail);
 3741:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3742: 				 &GDBM_READER());
 3743:     if ($hashref) {
 3744: 	# Structure of %data:
 3745: 	# $data{$symb}->{$parameter}=$value;
 3746: 	# $data{$symb}->{'v.'.$parameter}=$version;
 3747: 	# since $parameter will be unescaped, we do not
 3748:  	# have to worry about silly parameter names...
 3749: 	
 3750:         my $qresult='';
 3751: 	my %data = ();                     # A hash of anonymous hashes..
 3752: 	while (my ($key,$value) = each(%$hashref)) {
 3753: 	    my ($v,$symb,$param) = split(/:/,$key);
 3754: 	    next if ($v eq 'version' || $symb eq 'keys');
 3755: 	    next if (exists($data{$symb}) && 
 3756: 		     exists($data{$symb}->{$param}) &&
 3757: 		     $data{$symb}->{'v.'.$param} > $v);
 3758: 	    $data{$symb}->{$param}=$value;
 3759: 	    $data{$symb}->{'v.'.$param}=$v;
 3760: 	}
 3761: 	if (&untie_user_hash($hashref)) {
 3762: 	    while (my ($symb,$param_hash) = each(%data)) {
 3763: 		while(my ($param,$value) = each (%$param_hash)){
 3764: 		    next if ($param =~ /^v\./);       # Ignore versions...
 3765: 		    #
 3766: 		    #   Just dump the symb=value pairs separated by &
 3767: 		    #
 3768: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
 3769: 		}
 3770: 	    }
 3771: 	    chop($qresult);
 3772: 	    &Reply($client , \$qresult, $userinput);
 3773: 	} else {
 3774: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 3775: 		     "while attempting currentdump\n", $userinput);
 3776: 	}
 3777:     } else {
 3778: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3779: 		"while attempting currentdump\n", $userinput);
 3780:     }
 3781: 
 3782:     return 1;
 3783: }
 3784: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
 3785: 
 3786: #
 3787: #   Dump a profile database with an optional regular expression
 3788: #   to match against the keys.  In this dump, no effort is made
 3789: #   to separate symb from version information. Presumably the
 3790: #   databases that are dumped by this command are of a different
 3791: #   structure.  Need to look at this and improve the documentation of
 3792: #   both this and the currentdump handler.
 3793: # Parameters:
 3794: #    $cmd                     - The command keyword.
 3795: #    $tail                    - All of the characters after the $cmd:
 3796: #                               These are expected to be a colon
 3797: #                               separated list containing:
 3798: #                               domain/user - identifying the user.
 3799: #                               namespace   - identifying the database.
 3800: #                               regexp      - optional regular expression
 3801: #                                             that is matched against
 3802: #                                             database keywords to do
 3803: #                                             selective dumps.
 3804: #                               range       - optional range of entries
 3805: #                                             e.g., 10-20 would return the
 3806: #                                             10th to 19th items, etc.  
 3807: #   $client                   - Channel open on the client.
 3808: # Returns:
 3809: #    1    - Continue processing.
 3810: # Side effects:
 3811: #    response is written to $client.
 3812: #
 3813: sub dump_with_regexp {
 3814:     my ($cmd, $tail, $client) = @_;
 3815: 
 3816:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
 3817:     
 3818:     if ($res =~ /^error:/) {
 3819:         Failure($client, \$res, "$cmd:$tail");
 3820:     } else {
 3821:         Reply($client, \$res, "$cmd:$tail");
 3822:     }
 3823: 
 3824:     return 1;
 3825: }
 3826: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
 3827: 
 3828: #  Store a set of key=value pairs associated with a versioned name.
 3829: #
 3830: #  Parameters:
 3831: #    $cmd                - Request command keyword.
 3832: #    $tail               - Tail of the request.  This is a colon
 3833: #                          separated list containing:
 3834: #                          domain/user - User and authentication domain.
 3835: #                          namespace   - Name of the database being modified
 3836: #                          rid         - Resource keyword to modify.
 3837: #                          what        - new value associated with rid.
 3838: #                          laststore   - (optional) version=timestamp
 3839: #                                        for most recent transaction for rid
 3840: #                                        in namespace, when cstore was called
 3841: #
 3842: #    $client             - Socket open on the client.
 3843: #
 3844: #
 3845: #  Returns:
 3846: #      1 (keep on processing).
 3847: #  Side-Effects:
 3848: #    Writes to the client
 3849: #    Successful storage will cause either 'ok', or, if $laststore was included
 3850: #    in the tail of the request, and the version number for the last transaction
 3851: #    is larger than the version in $laststore, delay:$numtrans , where $numtrans
 3852: #    is the number of store evevnts recorded for rid in namespace since
 3853: #    lonnet::store() was called by the client.
 3854: #
 3855: sub store_handler {
 3856:     my ($cmd, $tail, $client) = @_;
 3857:  
 3858:     my $userinput = "$cmd:$tail";
 3859:     chomp($tail);
 3860:     my ($udom,$uname,$namespace,$rid,$what,$laststore) =split(/:/,$tail);
 3861:     if ($namespace ne 'roles') {
 3862: 
 3863: 	my @pairs=split(/\&/,$what);
 3864: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
 3865: 				       &GDBM_WRCREAT(), "S",
 3866: 				       "$rid:$what");
 3867: 	if ($hashref) {
 3868: 	    my $now = time;
 3869:             my $numtrans;
 3870:             if ($laststore) {
 3871:                 my ($previousversion,$previoustime) = split(/\=/,$laststore);
 3872:                 my ($lastversion,$lasttime) = (0,0);
 3873:                 $lastversion = $hashref->{"version:$rid"};
 3874:                 if ($lastversion) {
 3875:                     $lasttime = $hashref->{"$lastversion:$rid:timestamp"};
 3876:                 }
 3877:                 if (($previousversion) && ($previousversion !~ /\D/)) {
 3878:                     if (($lastversion > $previousversion) && ($lasttime >= $previoustime)) {
 3879:                         $numtrans = $lastversion - $previousversion;
 3880:                     }
 3881:                 } elsif ($lastversion) {
 3882:                     $numtrans = $lastversion;
 3883:                 }
 3884:                 if ($numtrans) {
 3885:                     $numtrans =~ s/D//g;
 3886:                 }
 3887:             }
 3888: 	    $hashref->{"version:$rid"}++;
 3889: 	    my $version=$hashref->{"version:$rid"};
 3890: 	    my $allkeys=''; 
 3891: 	    foreach my $pair (@pairs) {
 3892: 		my ($key,$value)=split(/=/,$pair);
 3893: 		$allkeys.=$key.':';
 3894: 		$hashref->{"$version:$rid:$key"}=$value;
 3895: 	    }
 3896: 	    $hashref->{"$version:$rid:timestamp"}=$now;
 3897: 	    $allkeys.='timestamp';
 3898: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
 3899: 	    if (&untie_user_hash($hashref)) {
 3900:                 my $msg = 'ok';
 3901:                 if ($numtrans) {
 3902:                     $msg = 'delay:'.$numtrans;
 3903:                 }
 3904: 		&Reply($client, "$msg\n", $userinput);
 3905: 	    } else {
 3906: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3907: 			"while attempting store\n", $userinput);
 3908: 	    }
 3909: 	} else {
 3910: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3911: 		     "while attempting store\n", $userinput);
 3912: 	}
 3913:     } else {
 3914: 	&Failure($client, "refused\n", $userinput);
 3915:     }
 3916: 
 3917:     return 1;
 3918: }
 3919: &register_handler("store", \&store_handler, 0, 1, 0);
 3920: 
 3921: #  Modify a set of key=value pairs associated with a versioned name.
 3922: #
 3923: #  Parameters:
 3924: #    $cmd                - Request command keyword.
 3925: #    $tail               - Tail of the request.  This is a colon
 3926: #                          separated list containing:
 3927: #                          domain/user - User and authentication domain.
 3928: #                          namespace   - Name of the database being modified
 3929: #                          rid         - Resource keyword to modify.
 3930: #                          v           - Version item to modify
 3931: #                          what        - new value associated with rid.
 3932: #
 3933: #    $client             - Socket open on the client.
 3934: #
 3935: #
 3936: #  Returns:
 3937: #      1 (keep on processing).
 3938: #  Side-Effects:
 3939: #    Writes to the client
 3940: sub putstore_handler {
 3941:     my ($cmd, $tail, $client) = @_;
 3942:  
 3943:     my $userinput = "$cmd:$tail";
 3944: 
 3945:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
 3946:     if ($namespace ne 'roles') {
 3947: 
 3948: 	chomp($what);
 3949: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
 3950: 				       &GDBM_WRCREAT(), "M",
 3951: 				       "$rid:$v:$what");
 3952: 	if ($hashref) {
 3953: 	    my $now = time;
 3954: 	    my %data = &hash_extract($what);
 3955: 	    my @allkeys;
 3956: 	    while (my($key,$value) = each(%data)) {
 3957: 		push(@allkeys,$key);
 3958: 		$hashref->{"$v:$rid:$key"} = $value;
 3959: 	    }
 3960: 	    my $allkeys = join(':',@allkeys);
 3961: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
 3962: 
 3963: 	    if (&untie_user_hash($hashref)) {
 3964: 		&Reply($client, "ok\n", $userinput);
 3965: 	    } else {
 3966: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3967: 			"while attempting store\n", $userinput);
 3968: 	    }
 3969: 	} else {
 3970: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3971: 		     "while attempting store\n", $userinput);
 3972: 	}
 3973:     } else {
 3974: 	&Failure($client, "refused\n", $userinput);
 3975:     }
 3976: 
 3977:     return 1;
 3978: }
 3979: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
 3980: 
 3981: sub hash_extract {
 3982:     my ($str)=@_;
 3983:     my %hash;
 3984:     foreach my $pair (split(/\&/,$str)) {
 3985: 	my ($key,$value)=split(/=/,$pair);
 3986: 	$hash{$key}=$value;
 3987:     }
 3988:     return (%hash);
 3989: }
 3990: sub hash_to_str {
 3991:     my ($hash_ref)=@_;
 3992:     my $str;
 3993:     foreach my $key (keys(%$hash_ref)) {
 3994: 	$str.=$key.'='.$hash_ref->{$key}.'&';
 3995:     }
 3996:     $str=~s/\&$//;
 3997:     return $str;
 3998: }
 3999: 
 4000: #
 4001: #  Dump out all versions of a resource that has key=value pairs associated
 4002: # with it for each version.  These resources are built up via the store
 4003: # command.
 4004: #
 4005: #  Parameters:
 4006: #     $cmd               - Command keyword.
 4007: #     $tail              - Remainder of the request which consists of:
 4008: #                          domain/user   - User and auth. domain.
 4009: #                          namespace     - name of resource database.
 4010: #                          rid           - Resource id.
 4011: #    $client             - socket open on the client.
 4012: #
 4013: # Returns:
 4014: #      1  indicating the caller should not yet exit.
 4015: # Side-effects:
 4016: #   Writes a reply to the client.
 4017: #   The reply is a string of the following shape:
 4018: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
 4019: #    Where the 1 above represents version 1.
 4020: #    this continues for all pairs of keys in all versions.
 4021: #
 4022: #
 4023: #    
 4024: #
 4025: sub restore_handler {
 4026:     my ($cmd, $tail, $client) = @_;
 4027: 
 4028:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
 4029:     my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
 4030:     $namespace=~s/\//\_/g;
 4031:     $namespace = &LONCAPA::clean_username($namespace);
 4032: 
 4033:     chomp($rid);
 4034:     my $qresult='';
 4035:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
 4036:     if ($hashref) {
 4037: 	my $version=$hashref->{"version:$rid"};
 4038: 	$qresult.="version=$version&";
 4039: 	my $scope;
 4040: 	for ($scope=1;$scope<=$version;$scope++) {
 4041: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
 4042: 	    my @keys=split(/:/,$vkeys);
 4043: 	    my $key;
 4044: 	    $qresult.="$scope:keys=$vkeys&";
 4045: 	    foreach $key (@keys) {
 4046: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
 4047: 	    }                                  
 4048: 	}
 4049: 	if (&untie_user_hash($hashref)) {
 4050: 	    $qresult=~s/\&$//;
 4051: 	    &Reply( $client, \$qresult, $userinput);
 4052: 	} else {
 4053: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4054: 		    "while attempting restore\n", $userinput);
 4055: 	}
 4056:     } else {
 4057: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 4058: 		"while attempting restore\n", $userinput);
 4059:     }
 4060:   
 4061:     return 1;
 4062: 
 4063: 
 4064: }
 4065: &register_handler("restore", \&restore_handler, 0,1,0);
 4066: 
 4067: #
 4068: #   Add a chat message to a synchronous discussion board.
 4069: #
 4070: # Parameters:
 4071: #    $cmd                - Request keyword.
 4072: #    $tail               - Tail of the command. A colon separated list
 4073: #                          containing:
 4074: #                          cdom    - Domain on which the chat board lives
 4075: #                          cnum    - Course containing the chat board.
 4076: #                          newpost - Body of the posting.
 4077: #                          group   - Optional group, if chat board is only 
 4078: #                                    accessible in a group within the course 
 4079: #   $client              - Socket open on the client.
 4080: # Returns:
 4081: #   1    - Indicating caller should keep on processing.
 4082: #
 4083: # Side-effects:
 4084: #   writes a reply to the client.
 4085: #
 4086: #
 4087: sub send_chat_handler {
 4088:     my ($cmd, $tail, $client) = @_;
 4089: 
 4090:     
 4091:     my $userinput = "$cmd:$tail";
 4092: 
 4093:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
 4094:     &chat_add($cdom,$cnum,$newpost,$group);
 4095:     &Reply($client, "ok\n", $userinput);
 4096: 
 4097:     return 1;
 4098: }
 4099: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
 4100: 
 4101: #
 4102: #   Retrieve the set of chat messages from a discussion board.
 4103: #
 4104: #  Parameters:
 4105: #    $cmd             - Command keyword that initiated the request.
 4106: #    $tail            - Remainder of the request after the command
 4107: #                       keyword.  In this case a colon separated list of
 4108: #                       chat domain    - Which discussion board.
 4109: #                       chat id        - Discussion thread(?)
 4110: #                       domain/user    - Authentication domain and username
 4111: #                                        of the requesting person.
 4112: #                       group          - Optional course group containing
 4113: #                                        the board.      
 4114: #   $client           - Socket open on the client program.
 4115: # Returns:
 4116: #    1     - continue processing
 4117: # Side effects:
 4118: #    Response is written to the client.
 4119: #
 4120: sub retrieve_chat_handler {
 4121:     my ($cmd, $tail, $client) = @_;
 4122: 
 4123: 
 4124:     my $userinput = "$cmd:$tail";
 4125: 
 4126:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
 4127:     my $reply='';
 4128:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
 4129: 	$reply.=&escape($_).':';
 4130:     }
 4131:     $reply=~s/\:$//;
 4132:     &Reply($client, \$reply, $userinput);
 4133: 
 4134: 
 4135:     return 1;
 4136: }
 4137: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
 4138: 
 4139: #
 4140: #  Initiate a query of an sql database.  SQL query repsonses get put in
 4141: #  a file for later retrieval.  This prevents sql query results from
 4142: #  bottlenecking the system.  Note that with loncnew, perhaps this is
 4143: #  less of an issue since multiple outstanding requests can be concurrently
 4144: #  serviced.
 4145: #
 4146: #  Parameters:
 4147: #     $cmd       - Command keyword that initiated the request.
 4148: #     $tail      - Remainder of the command after the keyword.
 4149: #                  For this function, this consists of a query and
 4150: #                  3 arguments that are self-documentingly labelled
 4151: #                  in the original arg1, arg2, arg3.
 4152: #     $client    - Socket open on the client.
 4153: # Return:
 4154: #    1   - Indicating processing should continue.
 4155: # Side-effects:
 4156: #    a reply is written to $client.
 4157: #
 4158: sub send_query_handler {
 4159:     my ($cmd, $tail, $client) = @_;
 4160: 
 4161:     my $userinput = "$cmd:$tail";
 4162: 
 4163:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
 4164:     $query=~s/\n*$//g;
 4165:     if (($query eq 'usersearch') || ($query eq 'instdirsearch')) {
 4166:         my $usersearchconf = &get_usersearch_config($currentdomainid,'directorysrch');
 4167:         my $earlyout;
 4168:         if (ref($usersearchconf) eq 'HASH') {
 4169:             if ($currentdomainid eq $clienthomedom) {
 4170:                 if ($query eq 'usersearch') {
 4171:                     if ($usersearchconf->{'lcavailable'} eq '0') {
 4172:                         $earlyout = 1;
 4173:                     }
 4174:                 } else {
 4175:                     if ($usersearchconf->{'available'} eq '0') {
 4176:                         $earlyout = 1;
 4177:                     }
 4178:                 }
 4179:             } else {
 4180:                 if ($query eq 'usersearch') {
 4181:                     if ($usersearchconf->{'lclocalonly'}) {
 4182:                         $earlyout = 1;
 4183:                     }
 4184:                 } else {
 4185:                     if ($usersearchconf->{'localonly'}) {
 4186:                         $earlyout = 1;
 4187:                     }
 4188:                 }
 4189:             }
 4190:         }
 4191:         if ($earlyout) {
 4192:             &Reply($client, "query_not_authorized\n");
 4193:             return 1;
 4194:         }
 4195:     }
 4196:     &Reply($client, "". &sql_reply("$clientname\&$query".
 4197: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
 4198: 	  $userinput);
 4199:     
 4200:     return 1;
 4201: }
 4202: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
 4203: 
 4204: #
 4205: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
 4206: #   The query is submitted via a "querysend" transaction.
 4207: #   There it is passed on to the lonsql daemon, queued and issued to
 4208: #   mysql.
 4209: #     This transaction is invoked when the sql transaction is complete
 4210: #   it stores the query results in flie and indicates query completion.
 4211: #   presumably local software then fetches this response... I'm guessing
 4212: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
 4213: #   lonsql on completion of the query interacts with the lond of our
 4214: #   client to do a query reply storing two files:
 4215: #    - id     - The results of the query.
 4216: #    - id.end - Indicating the transaction completed. 
 4217: #    NOTE: id is a unique id assigned to the query and querysend time.
 4218: # Parameters:
 4219: #    $cmd        - Command keyword that initiated this request.
 4220: #    $tail       - Remainder of the tail.  In this case that's a colon
 4221: #                  separated list containing the query Id and the 
 4222: #                  results of the query.
 4223: #    $client     - Socket open on the client.
 4224: # Return:
 4225: #    1           - Indicating that we should continue processing.
 4226: # Side effects:
 4227: #    ok written to the client.
 4228: #
 4229: sub reply_query_handler {
 4230:     my ($cmd, $tail, $client) = @_;
 4231: 
 4232: 
 4233:     my $userinput = "$cmd:$tail";
 4234: 
 4235:     my ($id,$reply)=split(/:/,$tail); 
 4236:     my $store;
 4237:     my $execdir=$perlvar{'lonDaemons'};
 4238:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
 4239: 	$reply=~s/\&/\n/g;
 4240: 	print $store $reply;
 4241: 	close $store;
 4242: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
 4243: 	print $store2 "done\n";
 4244: 	close $store2;
 4245: 	&Reply($client, "ok\n", $userinput);
 4246:     } else {
 4247: 	&Failure($client, "error: ".($!+0)
 4248: 		." IO::File->new Failed ".
 4249: 		"while attempting queryreply\n", $userinput);
 4250:     }
 4251:  
 4252: 
 4253:     return 1;
 4254: }
 4255: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
 4256: 
 4257: #
 4258: #  Process the courseidput request.  Not quite sure what this means
 4259: #  at the system level sense.  It appears a gdbm file in the 
 4260: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
 4261: #  a set of entries made in that database.
 4262: #
 4263: # Parameters:
 4264: #   $cmd      - The command keyword that initiated this request.
 4265: #   $tail     - Tail of the command.  In this case consists of a colon
 4266: #               separated list contaning the domain to apply this to and
 4267: #               an ampersand separated list of keyword=value pairs.
 4268: #               Each value is a colon separated list that includes:  
 4269: #               description, institutional code and course owner.
 4270: #               For backward compatibility with versions included
 4271: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
 4272: #               code and/or course owner are preserved from the existing 
 4273: #               record when writing a new record in response to 1.1 or 
 4274: #               1.2 implementations of lonnet::flushcourselogs().   
 4275: #                      
 4276: #   $client   - Socket open on the client.
 4277: # Returns:
 4278: #   1    - indicating that processing should continue
 4279: #
 4280: # Side effects:
 4281: #   reply is written to the client.
 4282: #
 4283: sub put_course_id_handler {
 4284:     my ($cmd, $tail, $client) = @_;
 4285: 
 4286: 
 4287:     my $userinput = "$cmd:$tail";
 4288: 
 4289:     my ($udom, $what) = split(/:/, $tail,2);
 4290:     chomp($what);
 4291:     my $now=time;
 4292:     my @pairs=split(/\&/,$what);
 4293: 
 4294:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 4295:     if ($hashref) {
 4296: 	foreach my $pair (@pairs) {
 4297:             my ($key,$courseinfo) = split(/=/,$pair,2);
 4298:             $courseinfo =~ s/=/:/g;
 4299:             if (defined($hashref->{$key})) {
 4300:                 my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
 4301:                 if (ref($value) eq 'HASH') {
 4302:                     my @items = ('description','inst_code','owner','type');
 4303:                     my @new_items = split(/:/,$courseinfo,-1);
 4304:                     my %storehash; 
 4305:                     for (my $i=0; $i<@new_items; $i++) {
 4306:                         $storehash{$items[$i]} = &unescape($new_items[$i]);
 4307:                     }
 4308:                     $hashref->{$key} = 
 4309:                         &Apache::lonnet::freeze_escape(\%storehash);
 4310:                     my $unesc_key = &unescape($key);
 4311:                     $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
 4312:                     next;
 4313:                 }
 4314:             }
 4315:             my @current_items = split(/:/,$hashref->{$key},-1);
 4316:             shift(@current_items); # remove description
 4317:             pop(@current_items);   # remove last access
 4318:             my $numcurrent = scalar(@current_items);
 4319:             if ($numcurrent > 3) {
 4320:                 $numcurrent = 3;
 4321:             }
 4322:             my @new_items = split(/:/,$courseinfo,-1);
 4323:             my $numnew = scalar(@new_items);
 4324:             if ($numcurrent > 0) {
 4325:                 if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2 
 4326:                     for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
 4327:                         $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
 4328:                     }
 4329:                 }
 4330:             }
 4331:             $hashref->{$key}=$courseinfo.':'.$now;
 4332: 	}
 4333: 	if (&untie_domain_hash($hashref)) {
 4334: 	    &Reply( $client, "ok\n", $userinput);
 4335: 	} else {
 4336: 	    &Failure($client, "error: ".($!+0)
 4337: 		     ." untie(GDBM) Failed ".
 4338: 		     "while attempting courseidput\n", $userinput);
 4339: 	}
 4340:     } else {
 4341: 	&Failure($client, "error: ".($!+0)
 4342: 		 ." tie(GDBM) Failed ".
 4343: 		 "while attempting courseidput\n", $userinput);
 4344:     }
 4345: 
 4346:     return 1;
 4347: }
 4348: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
 4349: 
 4350: sub put_course_id_hash_handler {
 4351:     my ($cmd, $tail, $client) = @_;
 4352:     my $userinput = "$cmd:$tail";
 4353:     my ($udom,$mode,$what) = split(/:/, $tail,3);
 4354:     chomp($what);
 4355:     my $now=time;
 4356:     my @pairs=split(/\&/,$what);
 4357:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 4358:     if ($hashref) {
 4359:         foreach my $pair (@pairs) {
 4360:             my ($key,$value)=split(/=/,$pair);
 4361:             my $unesc_key = &unescape($key);
 4362:             if ($mode ne 'timeonly') {
 4363:                 if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
 4364:                     my $curritems = &Apache::lonnet::thaw_unescape($key); 
 4365:                     if (ref($curritems) ne 'HASH') {
 4366:                         my @current_items = split(/:/,$hashref->{$key},-1);
 4367:                         my $lasttime = pop(@current_items);
 4368:                         $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
 4369:                     } else {
 4370:                         $hashref->{&escape('lasttime:'.$unesc_key)} = '';
 4371:                     }
 4372:                 } 
 4373:                 $hashref->{$key} = $value;
 4374:             }
 4375:             if ($mode ne 'notime') {
 4376:                 $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
 4377:             }
 4378:         }
 4379:         if (&untie_domain_hash($hashref)) {
 4380:             &Reply($client, "ok\n", $userinput);
 4381:         } else {
 4382:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4383:                      "while attempting courseidputhash\n", $userinput);
 4384:         }
 4385:     } else {
 4386:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 4387:                   "while attempting courseidputhash\n", $userinput);
 4388:     }
 4389:     return 1;
 4390: }
 4391: &register_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
 4392: 
 4393: #  Retrieves the value of a course id resource keyword pattern
 4394: #  defined since a starting date.  Both the starting date and the
 4395: #  keyword pattern are optional.  If the starting date is not supplied it
 4396: #  is treated as the beginning of time.  If the pattern is not found,
 4397: #  it is treatred as "." matching everything.
 4398: #
 4399: #  Parameters:
 4400: #     $cmd     - Command keyword that resulted in us being dispatched.
 4401: #     $tail    - The remainder of the command that, in this case, consists
 4402: #                of a colon separated list of:
 4403: #                 domain   - The domain in which the course database is 
 4404: #                            defined.
 4405: #                 since    - Optional parameter describing the minimum
 4406: #                            time of definition(?) of the resources that
 4407: #                            will match the dump.
 4408: #                 description - regular expression that is used to filter
 4409: #                            the dump.  Only keywords matching this regexp
 4410: #                            will be used.
 4411: #                 institutional code - optional supplied code to filter 
 4412: #                            the dump. Only courses with an institutional code 
 4413: #                            that match the supplied code will be returned.
 4414: #                 owner    - optional supplied username and domain of owner to
 4415: #                            filter the dump.  Only courses for which the course
 4416: #                            owner matches the supplied username and/or domain
 4417: #                            will be returned. Pre-2.2.0 legacy entries from 
 4418: #                            nohist_courseiddump will only contain usernames.
 4419: #                 type     - optional parameter for selection 
 4420: #                 regexp_ok - if 1 or -1 allow the supplied institutional code
 4421: #                            filter to behave as a regular expression:
 4422: #	                      1 will not exclude the course if the instcode matches the RE 
 4423: #                            -1 will exclude the course if the instcode matches the RE
 4424: #                 rtn_as_hash - whether to return the information available for
 4425: #                            each matched item as a frozen hash of all 
 4426: #                            key, value pairs in the item's hash, or as a 
 4427: #                            colon-separated list of (in order) description,
 4428: #                            institutional code, and course owner.
 4429: #                 selfenrollonly - filter by courses allowing self-enrollment  
 4430: #                                  now or in the future (selfenrollonly = 1).
 4431: #                 catfilter - filter by course category, assigned to a course 
 4432: #                             using manually defined categories (i.e., not
 4433: #                             self-cataloging based on on institutional code).   
 4434: #                 showhidden - include course in results even if course  
 4435: #                              was set to be excluded from course catalog (DC only).
 4436: #                 caller -  if set to 'coursecatalog', courses set to be hidden
 4437: #                           from course catalog will be excluded from results (unless
 4438: #                           overridden by "showhidden".
 4439: #                 cloner - escaped username:domain of course cloner (if picking course to
 4440: #                          clone).
 4441: #                 cc_clone_list - escaped comma separated list of courses for which 
 4442: #                                 course cloner has active CC role (and so can clone
 4443: #                                 automatically).
 4444: #                 cloneonly - filter by courses for which cloner has rights to clone.
 4445: #                 createdbefore - include courses for which creation date preceeded this date.
 4446: #                 createdafter - include courses for which creation date followed this date.
 4447: #                 creationcontext - include courses created in specified context 
 4448: #
 4449: #                 domcloner - flag to indicate if user can create CCs in course's domain.
 4450: #                             If so, ability to clone course is automatic.
 4451: #                 hasuniquecode - filter by courses for which a six character unique code has 
 4452: #                                 been set.
 4453: #
 4454: #     $client  - The socket open on the client.
 4455: # Returns:
 4456: #    1     - Continue processing.
 4457: # Side Effects:
 4458: #   a reply is written to $client.
 4459: sub dump_course_id_handler {
 4460:     my ($cmd, $tail, $client) = @_;
 4461: 
 4462:     my $res = LONCAPA::Lond::dump_course_id_handler($tail);
 4463:     if ($res =~ /^error:/) {
 4464:         Failure($client, \$res, "$cmd:$tail");
 4465:     } else {
 4466:         Reply($client, \$res, "$cmd:$tail");
 4467:     }
 4468: 
 4469:     return 1;  
 4470: 
 4471:     #TODO remove
 4472:     my $userinput = "$cmd:$tail";
 4473: 
 4474:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
 4475:         $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
 4476:         $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
 4477:         $creationcontext,$domcloner,$hasuniquecode) =split(/:/,$tail);
 4478:     my $now = time;
 4479:     my ($cloneruname,$clonerudom,%cc_clone);
 4480:     if (defined($description)) {
 4481: 	$description=&unescape($description);
 4482:     } else {
 4483: 	$description='.';
 4484:     }
 4485:     if (defined($instcodefilter)) {
 4486:         $instcodefilter=&unescape($instcodefilter);
 4487:     } else {
 4488:         $instcodefilter='.';
 4489:     }
 4490:     my ($ownerunamefilter,$ownerdomfilter);
 4491:     if (defined($ownerfilter)) {
 4492:         $ownerfilter=&unescape($ownerfilter);
 4493:         if ($ownerfilter ne '.' && defined($ownerfilter)) {
 4494:             if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
 4495:                  $ownerunamefilter = $1;
 4496:                  $ownerdomfilter = $2;
 4497:             } else {
 4498:                 $ownerunamefilter = $ownerfilter;
 4499:                 $ownerdomfilter = '';
 4500:             }
 4501:         }
 4502:     } else {
 4503:         $ownerfilter='.';
 4504:     }
 4505: 
 4506:     if (defined($coursefilter)) {
 4507:         $coursefilter=&unescape($coursefilter);
 4508:     } else {
 4509:         $coursefilter='.';
 4510:     }
 4511:     if (defined($typefilter)) {
 4512:         $typefilter=&unescape($typefilter);
 4513:     } else {
 4514:         $typefilter='.';
 4515:     }
 4516:     if (defined($regexp_ok)) {
 4517:         $regexp_ok=&unescape($regexp_ok);
 4518:     }
 4519:     if (defined($catfilter)) {
 4520:         $catfilter=&unescape($catfilter);
 4521:     }
 4522:     if (defined($cloner)) {
 4523:         $cloner = &unescape($cloner);
 4524:         ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/); 
 4525:     }
 4526:     if (defined($cc_clone_list)) {
 4527:         $cc_clone_list = &unescape($cc_clone_list);
 4528:         my @cc_cloners = split('&',$cc_clone_list);
 4529:         foreach my $cid (@cc_cloners) {
 4530:             my ($clonedom,$clonenum) = split(':',$cid);
 4531:             next if ($clonedom ne $udom); 
 4532:             $cc_clone{$clonedom.'_'.$clonenum} = 1;
 4533:         } 
 4534:     }
 4535:     if ($createdbefore ne '') {
 4536:         $createdbefore = &unescape($createdbefore);
 4537:     } else {
 4538:        $createdbefore = 0;
 4539:     }
 4540:     if ($createdafter ne '') {
 4541:         $createdafter = &unescape($createdafter);
 4542:     } else {
 4543:         $createdafter = 0;
 4544:     }
 4545:     if ($creationcontext ne '') {
 4546:         $creationcontext = &unescape($creationcontext);
 4547:     } else {
 4548:         $creationcontext = '.';
 4549:     }
 4550:     unless ($hasuniquecode) {
 4551:         $hasuniquecode = '.';
 4552:     }
 4553:     my $unpack = 1;
 4554:     if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' && 
 4555:         $typefilter eq '.') {
 4556:         $unpack = 0;
 4557:     }
 4558:     if (!defined($since)) { $since=0; }
 4559:     my $qresult='';
 4560:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 4561:     if ($hashref) {
 4562: 	while (my ($key,$value) = each(%$hashref)) {
 4563:             my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
 4564:                 %unesc_val,$selfenroll_end,$selfenroll_types,$created,
 4565:                 $context);
 4566:             $unesc_key = &unescape($key);
 4567:             if ($unesc_key =~ /^lasttime:/) {
 4568:                 next;
 4569:             } else {
 4570:                 $lasttime_key = &escape('lasttime:'.$unesc_key);
 4571:             }
 4572:             if ($hashref->{$lasttime_key} ne '') {
 4573:                 $lasttime = $hashref->{$lasttime_key};
 4574:                 next if ($lasttime<$since);
 4575:             }
 4576:             my ($canclone,$valchange);
 4577:             my $items = &Apache::lonnet::thaw_unescape($value);
 4578:             if (ref($items) eq 'HASH') {
 4579:                 if ($hashref->{$lasttime_key} eq '') {
 4580:                     next if ($since > 1);
 4581:                 }
 4582:                 $is_hash =  1;
 4583:                 if ($domcloner) {
 4584:                     $canclone = 1;
 4585:                 } elsif (defined($clonerudom)) {
 4586:                     if ($items->{'cloners'}) {
 4587:                         my @cloneable = split(',',$items->{'cloners'});
 4588:                         if (@cloneable) {
 4589:                             if (grep(/^\*$/,@cloneable))  {
 4590:                                 $canclone = 1;
 4591:                             } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
 4592:                                 $canclone = 1;
 4593:                             } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
 4594:                                 $canclone = 1;
 4595:                             }
 4596:                         }
 4597:                         unless ($canclone) {
 4598:                             if ($cloneruname ne '' && $clonerudom ne '') {
 4599:                                 if ($cc_clone{$unesc_key}) {
 4600:                                     $canclone = 1;
 4601:                                     $items->{'cloners'} .= ','.$cloneruname.':'.
 4602:                                                            $clonerudom;
 4603:                                     $valchange = 1;
 4604:                                 }
 4605:                             }
 4606:                         }
 4607:                     } elsif (defined($cloneruname)) {
 4608:                         if ($cc_clone{$unesc_key}) {
 4609:                             $canclone = 1;
 4610:                             $items->{'cloners'} = $cloneruname.':'.$clonerudom;
 4611:                             $valchange = 1;
 4612:                         }
 4613:                         unless ($canclone) {
 4614:                             if ($items->{'owner'} =~ /:/) {
 4615:                                 if ($items->{'owner'} eq $cloner) {
 4616:                                     $canclone = 1;
 4617:                                 }
 4618:                             } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
 4619:                                 $canclone = 1;
 4620:                             }
 4621:                             if ($canclone) {
 4622:                                 $items->{'cloners'} = $cloneruname.':'.$clonerudom;
 4623:                                 $valchange = 1;
 4624:                             }
 4625:                         }
 4626:                     }
 4627:                 }
 4628:                 if ($unpack || !$rtn_as_hash) {
 4629:                     $unesc_val{'descr'} = $items->{'description'};
 4630:                     $unesc_val{'inst_code'} = $items->{'inst_code'};
 4631:                     $unesc_val{'owner'} = $items->{'owner'};
 4632:                     $unesc_val{'type'} = $items->{'type'};
 4633:                     $unesc_val{'cloners'} = $items->{'cloners'};
 4634:                     $unesc_val{'created'} = $items->{'created'};
 4635:                     $unesc_val{'context'} = $items->{'context'};
 4636:                 }
 4637:                 $selfenroll_types = $items->{'selfenroll_types'};
 4638:                 $selfenroll_end = $items->{'selfenroll_end_date'};
 4639:                 $created = $items->{'created'};
 4640:                 $context = $items->{'context'};
 4641:                 if ($hasuniquecode ne '.') {
 4642:                     next unless ($items->{'uniquecode'});
 4643:                 }
 4644:                 if ($selfenrollonly) {
 4645:                     next if (!$selfenroll_types);
 4646:                     if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
 4647:                         next;
 4648:                     }
 4649:                 }
 4650:                 if ($creationcontext ne '.') {
 4651:                     next if (($context ne '') && ($context ne $creationcontext));  
 4652:                 }
 4653:                 if ($createdbefore > 0) {
 4654:                     next if (($created eq '') || ($created > $createdbefore));   
 4655:                 }
 4656:                 if ($createdafter > 0) {
 4657:                     next if (($created eq '') || ($created <= $createdafter)); 
 4658:                 }
 4659:                 if ($catfilter ne '') {
 4660:                     next if ($items->{'categories'} eq '');
 4661:                     my @categories = split('&',$items->{'categories'}); 
 4662:                     next if (@categories == 0);
 4663:                     my @subcats = split('&',$catfilter);
 4664:                     my $matchcat = 0;
 4665:                     foreach my $cat (@categories) {
 4666:                         if (grep(/^\Q$cat\E$/,@subcats)) {
 4667:                             $matchcat = 1;
 4668:                             last;
 4669:                         }
 4670:                     }
 4671:                     next if (!$matchcat);
 4672:                 }
 4673:                 if ($caller eq 'coursecatalog') {
 4674:                     if ($items->{'hidefromcat'} eq 'yes') {
 4675:                         next if !$showhidden;
 4676:                     }
 4677:                 }
 4678:             } else {
 4679:                 next if ($catfilter ne '');
 4680:                 next if ($selfenrollonly);
 4681:                 next if ($createdbefore || $createdafter);
 4682:                 next if ($creationcontext ne '.');
 4683:                 if ((defined($clonerudom)) && (defined($cloneruname)))  {
 4684:                     if ($cc_clone{$unesc_key}) {
 4685:                         $canclone = 1;
 4686:                         $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
 4687:                     }
 4688:                 }
 4689:                 $is_hash =  0;
 4690:                 my @courseitems = split(/:/,$value);
 4691:                 $lasttime = pop(@courseitems);
 4692:                 if ($hashref->{$lasttime_key} eq '') {
 4693:                     next if ($lasttime<$since);
 4694:                 }
 4695: 	        ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
 4696:             }
 4697:             if ($cloneonly) {
 4698:                next unless ($canclone);
 4699:             }
 4700:             my $match = 1;
 4701: 	    if ($description ne '.') {
 4702:                 if (!$is_hash) {
 4703:                     $unesc_val{'descr'} = &unescape($val{'descr'});
 4704:                 }
 4705:                 if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
 4706:                     $match = 0;
 4707:                 }
 4708:             }
 4709:             if ($instcodefilter ne '.') {
 4710:                 if (!$is_hash) {
 4711:                     $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
 4712:                 }
 4713:                 if ($regexp_ok == 1) {
 4714:                     if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
 4715:                         $match = 0;
 4716:                     }
 4717:                 } elsif ($regexp_ok == -1) {
 4718:                     if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
 4719:                         $match = 0;
 4720:                     }
 4721:                 } else {
 4722:                     if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
 4723:                         $match = 0;
 4724:                     }
 4725:                 }
 4726: 	    }
 4727:             if ($ownerfilter ne '.') {
 4728:                 if (!$is_hash) {
 4729:                     $unesc_val{'owner'} = &unescape($val{'owner'});
 4730:                 }
 4731:                 if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
 4732:                     if ($unesc_val{'owner'} =~ /:/) {
 4733:                         if (eval{$unesc_val{'owner'} !~ 
 4734:                              /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
 4735:                             $match = 0;
 4736:                         } 
 4737:                     } else {
 4738:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
 4739:                             $match = 0;
 4740:                         }
 4741:                     }
 4742:                 } elsif ($ownerunamefilter ne '') {
 4743:                     if ($unesc_val{'owner'} =~ /:/) {
 4744:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
 4745:                              $match = 0;
 4746:                         }
 4747:                     } else {
 4748:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
 4749:                             $match = 0;
 4750:                         }
 4751:                     }
 4752:                 } elsif ($ownerdomfilter ne '') {
 4753:                     if ($unesc_val{'owner'} =~ /:/) {
 4754:                         if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
 4755:                              $match = 0;
 4756:                         }
 4757:                     } else {
 4758:                         if ($ownerdomfilter ne $udom) {
 4759:                             $match = 0;
 4760:                         }
 4761:                     }
 4762:                 }
 4763:             }
 4764:             if ($coursefilter ne '.') {
 4765:                 if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
 4766:                     $match = 0;
 4767:                 }
 4768:             }
 4769:             if ($typefilter ne '.') {
 4770:                 if (!$is_hash) {
 4771:                     $unesc_val{'type'} = &unescape($val{'type'});
 4772:                 }
 4773:                 if ($unesc_val{'type'} eq '') {
 4774:                     if ($typefilter ne 'Course') {
 4775:                         $match = 0;
 4776:                     }
 4777:                 } else {
 4778:                     if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
 4779:                         $match = 0;
 4780:                     }
 4781:                 }
 4782:             }
 4783:             if ($match == 1) {
 4784:                 if ($rtn_as_hash) {
 4785:                     if ($is_hash) {
 4786:                         if ($valchange) {
 4787:                             my $newvalue = &Apache::lonnet::freeze_escape($items);
 4788:                             $qresult.=$key.'='.$newvalue.'&';
 4789:                         } else {
 4790:                             $qresult.=$key.'='.$value.'&';
 4791:                         }
 4792:                     } else {
 4793:                         my %rtnhash = ( 'description' => &unescape($val{'descr'}),
 4794:                                         'inst_code' => &unescape($val{'inst_code'}),
 4795:                                         'owner'     => &unescape($val{'owner'}),
 4796:                                         'type'      => &unescape($val{'type'}),
 4797:                                         'cloners'   => &unescape($val{'cloners'}),
 4798:                                       );
 4799:                         my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
 4800:                         $qresult.=$key.'='.$items.'&';
 4801:                     }
 4802:                 } else {
 4803:                     if ($is_hash) {
 4804:                         $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
 4805:                                     &escape($unesc_val{'inst_code'}).':'.
 4806:                                     &escape($unesc_val{'owner'}).'&';
 4807:                     } else {
 4808:                         $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
 4809:                                     ':'.$val{'owner'}.'&';
 4810:                     }
 4811:                 }
 4812:             }
 4813: 	}
 4814: 	if (&untie_domain_hash($hashref)) {
 4815: 	    chop($qresult);
 4816: 	    &Reply($client, \$qresult, $userinput);
 4817: 	} else {
 4818: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4819: 		    "while attempting courseiddump\n", $userinput);
 4820: 	}
 4821:     } else {
 4822: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 4823: 		"while attempting courseiddump\n", $userinput);
 4824:     }
 4825:     return 1;
 4826: }
 4827: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
 4828: 
 4829: sub course_lastaccess_handler {
 4830:     my ($cmd, $tail, $client) = @_;
 4831:     my $userinput = "$cmd:$tail";
 4832:     my ($cdom,$cnum) = split(':',$tail); 
 4833:     my (%lastaccess,$qresult);
 4834:     my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
 4835:     if ($hashref) {
 4836:         while (my ($key,$value) = each(%$hashref)) {
 4837:             my ($unesc_key,$lasttime);
 4838:             $unesc_key = &unescape($key);
 4839:             if ($cnum) {
 4840:                 next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
 4841:             }
 4842:             if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
 4843:                 $lastaccess{$1} = $value;
 4844:             } else {
 4845:                 my $items = &Apache::lonnet::thaw_unescape($value);
 4846:                 if (ref($items) eq 'HASH') {
 4847:                     unless ($lastaccess{$unesc_key}) {
 4848:                         $lastaccess{$unesc_key} = '';
 4849:                     }
 4850:                 } else {
 4851:                     my @courseitems = split(':',$value);
 4852:                     $lastaccess{$unesc_key} = pop(@courseitems);
 4853:                 }
 4854:             }
 4855:         }
 4856:         foreach my $cid (sort(keys(%lastaccess))) {
 4857:             $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&'; 
 4858:         }
 4859:         if (&untie_domain_hash($hashref)) {
 4860:             if ($qresult) {
 4861:                 chop($qresult);
 4862:             }
 4863:             &Reply($client, \$qresult, $userinput);
 4864:         } else {
 4865:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4866:                     "while attempting lastacourseaccess\n", $userinput);
 4867:         }
 4868:     } else {
 4869:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 4870:                 "while attempting lastcourseaccess\n", $userinput);
 4871:     }
 4872:     return 1;
 4873: }
 4874: &register_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
 4875: 
 4876: #
 4877: # Puts an unencrypted entry in a namespace db file at the domain level 
 4878: #
 4879: # Parameters:
 4880: #    $cmd      - The command that got us here.
 4881: #    $tail     - Tail of the command (remaining parameters).
 4882: #    $client   - File descriptor connected to client.
 4883: # Returns
 4884: #     0        - Requested to exit, caller should shut down.
 4885: #     1        - Continue processing.
 4886: #  Side effects:
 4887: #     reply is written to $client.
 4888: #
 4889: sub put_domain_handler {
 4890:     my ($cmd,$tail,$client) = @_;
 4891: 
 4892:     my $userinput = "$cmd:$tail";
 4893: 
 4894:     my ($udom,$namespace,$what) =split(/:/,$tail,3);
 4895:     chomp($what);
 4896:     my @pairs=split(/\&/,$what);
 4897:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
 4898:                                    "P", $what);
 4899:     if ($hashref) {
 4900:         foreach my $pair (@pairs) {
 4901:             my ($key,$value)=split(/=/,$pair);
 4902:             $hashref->{$key}=$value;
 4903:         }
 4904:         if (&untie_domain_hash($hashref)) {
 4905:             &Reply($client, "ok\n", $userinput);
 4906:         } else {
 4907:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4908:                      "while attempting putdom\n", $userinput);
 4909:         }
 4910:     } else {
 4911:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 4912:                   "while attempting putdom\n", $userinput);
 4913:     }
 4914: 
 4915:     return 1;
 4916: }
 4917: &register_handler("putdom", \&put_domain_handler, 0, 1, 0);
 4918: 
 4919: # Updates one or more entries in clickers.db file at the domain level
 4920: #
 4921: # Parameters:
 4922: #    $cmd      - The command that got us here.
 4923: #    $tail     - Tail of the command (remaining parameters).
 4924: #                In this case a colon separated list containing:
 4925: #                (a) the domain for which we are updating the entries,
 4926: #                (b) the action required -- add or del -- and
 4927: #                (c) a &-separated list of entries to add or delete.
 4928: #    $client   - File descriptor connected to client.
 4929: # Returns
 4930: #     1        - Continue processing.
 4931: #     0        - Requested to exit, caller should shut down.
 4932: #  Side effects:
 4933: #     reply is written to $client.
 4934: #
 4935: 
 4936: 
 4937: sub update_clickers {
 4938:     my ($cmd, $tail, $client)  = @_;
 4939: 
 4940:     my $userinput = "$cmd:$tail";
 4941:     my ($udom,$action,$what) =split(/:/,$tail,3);
 4942:     chomp($what);
 4943: 
 4944:     my $hashref = &tie_domain_hash($udom, "clickers", &GDBM_WRCREAT(),
 4945:                                  "U","$action:$what");
 4946: 
 4947:     if (!$hashref) {
 4948:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 4949:                   "while attempting updateclickers\n", $userinput);
 4950:         return 1;
 4951:     }
 4952: 
 4953:     my @pairs=split(/\&/,$what);
 4954:     foreach my $pair (@pairs) {
 4955:         my ($key,$value)=split(/=/,$pair);
 4956:         if ($action eq 'add') {
 4957:             if (exists($hashref->{$key})) {
 4958:                 my @newvals = split(/,/,&unescape($value));
 4959:                 my @currvals = split(/,/,&unescape($hashref->{$key}));
 4960:                 my @merged = sort(keys(%{{map { $_ => 1 } (@newvals,@currvals)}}));
 4961:                 $hashref->{$key}=&escape(join(',',@merged));
 4962:             } else {
 4963:                 $hashref->{$key}=$value;
 4964:             }
 4965:         } elsif ($action eq 'del') {
 4966:             if (exists($hashref->{$key})) {
 4967:                 my %current;
 4968:                 map { $current{$_} = 1; } split(/,/,&unescape($hashref->{$key}));
 4969:                 map { delete($current{$_}); } split(/,/,&unescape($value));
 4970:                 if (keys(%current)) {
 4971:                     $hashref->{$key}=&escape(join(',',sort(keys(%current))));
 4972:                 } else {
 4973:                     delete($hashref->{$key});
 4974:                 }
 4975:             }
 4976:         }
 4977:     }
 4978:     if (&untie_user_hash($hashref)) {
 4979:         &Reply( $client, "ok\n", $userinput);
 4980:     } else {
 4981:         &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 4982:                  "while attempting put\n",
 4983:                  $userinput);
 4984:     }
 4985:     return 1;
 4986: }
 4987: &register_handler("updateclickers", \&update_clickers, 0, 1, 0);
 4988: 
 4989: 
 4990: # Deletes one or more entries in a namespace db file at the domain level
 4991: #
 4992: # Parameters:
 4993: #    $cmd      - The command that got us here.
 4994: #    $tail     - Tail of the command (remaining parameters).
 4995: #                In this case a colon separated list containing:
 4996: #                (a) the domain for which we are deleting the entries,
 4997: #                (b) &-separated list of keys to delete.  
 4998: #    $client   - File descriptor connected to client.
 4999: # Returns
 5000: #     1        - Continue processing.
 5001: #     0        - Requested to exit, caller should shut down.
 5002: #  Side effects:
 5003: #     reply is written to $client.
 5004: #
 5005: 
 5006: sub del_domain_handler {
 5007:     my ($cmd,$tail,$client) = @_;
 5008: 
 5009:     my $userinput = "$cmd:$tail";
 5010: 
 5011:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
 5012:     chomp($what);
 5013:     my $hashref = &tie_domain_hash($udom,$namespace,&GDBM_WRCREAT(),
 5014:                                    "D", $what);
 5015:     if ($hashref) {
 5016:         my @keys=split(/\&/,$what);
 5017:         foreach my $key (@keys) {
 5018:             delete($hashref->{$key});
 5019:         }
 5020:         if (&untie_user_hash($hashref)) {
 5021:             &Reply($client, "ok\n", $userinput);
 5022:         } else {
 5023:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5024:                     "while attempting deldom\n", $userinput);
 5025:         }
 5026:     } else {
 5027:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 5028:                  "while attempting deldom\n", $userinput);
 5029:     }
 5030:     return 1;
 5031: }
 5032: &register_handler("deldom", \&del_domain_handler, 0, 1, 0);
 5033: 
 5034: 
 5035: # Unencrypted get from the namespace database file at the domain level.
 5036: # This function retrieves a keyed item from a specific named database in the
 5037: # domain directory.
 5038: #
 5039: # Parameters:
 5040: #   $cmd             - Command request keyword (get).
 5041: #   $tail            - Tail of the command.  This is a colon separated list
 5042: #                      consisting of the domain and the 'namespace' 
 5043: #                      which selects the gdbm file to do the lookup in,
 5044: #                      & separated list of keys to lookup.  Note that
 5045: #                      the values are returned as an & separated list too.
 5046: #   $client          - File descriptor open on the client.
 5047: # Returns:
 5048: #   1       - Continue processing.
 5049: #   0       - Exit.
 5050: #  Side effects:
 5051: #     reply is written to $client.
 5052: #
 5053: 
 5054: sub get_domain_handler {
 5055:     my ($cmd, $tail, $client) = @_;
 5056: 
 5057: 
 5058:     my $userinput = "$cmd:$tail";
 5059: 
 5060:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
 5061:     chomp($what);
 5062:     if ($namespace =~ /^enc/) {
 5063:         &Failure( $client, "refused\n", $userinput);
 5064:     } else {
 5065:         my @queries=split(/\&/,$what);
 5066:         my $qresult='';
 5067:         my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
 5068:         if ($hashref) {
 5069:             for (my $i=0;$i<=$#queries;$i++) {
 5070:                 $qresult.="$hashref->{$queries[$i]}&";
 5071:             }
 5072:             if (&untie_domain_hash($hashref)) {
 5073:                 $qresult=~s/\&$//;
 5074:                 &Reply($client, \$qresult, $userinput);
 5075:             } else {
 5076:                 &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 5077:                           "while attempting getdom\n",$userinput);
 5078:             }
 5079:         } else {
 5080:             &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 5081:                      "while attempting getdom\n",$userinput);
 5082:         }
 5083:     }
 5084: 
 5085:     return 1;
 5086: }
 5087: &register_handler("getdom", \&get_domain_handler, 0, 1, 0);
 5088: 
 5089: sub encrypted_get_domain_handler {
 5090:     my ($cmd, $tail, $client) = @_;
 5091: 
 5092:     my $userinput = "$cmd:$tail";
 5093: 
 5094:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
 5095:     chomp($what);
 5096:     my @queries=split(/\&/,$what);
 5097:     my $qresult='';
 5098:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
 5099:     if ($hashref) {
 5100:         for (my $i=0;$i<=$#queries;$i++) {
 5101:             $qresult.="$hashref->{$queries[$i]}&";
 5102:         }
 5103:         if (&untie_domain_hash($hashref)) {
 5104:             $qresult=~s/\&$//;
 5105:             if ($cipher) {
 5106:                 my $cmdlength=length($qresult);
 5107:                 $qresult.="         ";
 5108:                 my $encqresult='';
 5109:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 5110:                     $encqresult.= unpack("H16",
 5111:                                          $cipher->encrypt(substr($qresult,
 5112:                                                                  $encidx,
 5113:                                                                  8)));
 5114:                 }
 5115:                 &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
 5116:             } else {
 5117:                 &Failure( $client, "error:no_key\n", $userinput);
 5118:             }
 5119:         } else {
 5120:             &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 5121:                       "while attempting egetdom\n",$userinput);
 5122:         }
 5123:     } else {
 5124:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 5125:                  "while attempting egetdom\n",$userinput);
 5126:     }
 5127:     return 1;
 5128: }
 5129: &register_handler("egetdom", \&encrypted_get_domain_handler, 1, 1, 0);
 5130: 
 5131: #
 5132: #  Puts an id to a domains id database. 
 5133: #
 5134: #  Parameters:
 5135: #   $cmd     - The command that triggered us.
 5136: #   $tail    - Remainder of the request other than the command. This is a 
 5137: #              colon separated list containing:
 5138: #              $domain  - The domain for which we are writing the id.
 5139: #              $pairs  - The id info to write... this is and & separated list
 5140: #                        of keyword=value.
 5141: #   $client  - Socket open on the client.
 5142: #  Returns:
 5143: #    1   - Continue processing.
 5144: #  Side effects:
 5145: #     reply is written to $client.
 5146: #
 5147: sub put_id_handler {
 5148:     my ($cmd,$tail,$client) = @_;
 5149: 
 5150: 
 5151:     my $userinput = "$cmd:$tail";
 5152: 
 5153:     my ($udom,$what)=split(/:/,$tail);
 5154:     chomp($what);
 5155:     my @pairs=split(/\&/,$what);
 5156:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
 5157: 				   "P", $what);
 5158:     if ($hashref) {
 5159: 	foreach my $pair (@pairs) {
 5160: 	    my ($key,$value)=split(/=/,$pair);
 5161: 	    $hashref->{$key}=$value;
 5162: 	}
 5163: 	if (&untie_domain_hash($hashref)) {
 5164: 	    &Reply($client, "ok\n", $userinput);
 5165: 	} else {
 5166: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5167: 		     "while attempting idput\n", $userinput);
 5168: 	}
 5169:     } else {
 5170: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 5171: 		  "while attempting idput\n", $userinput);
 5172:     }
 5173: 
 5174:     return 1;
 5175: }
 5176: &register_handler("idput", \&put_id_handler, 0, 1, 0);
 5177: 
 5178: #
 5179: #  Retrieves a set of id values from the id database.
 5180: #  Returns an & separated list of results, one for each requested id to the
 5181: #  client.
 5182: #
 5183: # Parameters:
 5184: #   $cmd       - Command keyword that caused us to be dispatched.
 5185: #   $tail      - Tail of the command.  Consists of a colon separated:
 5186: #               domain - the domain whose id table we dump
 5187: #               ids      Consists of an & separated list of
 5188: #                        id keywords whose values will be fetched.
 5189: #                        nonexisting keywords will have an empty value.
 5190: #   $client    - Socket open on the client.
 5191: #
 5192: # Returns:
 5193: #    1 - indicating processing should continue.
 5194: # Side effects:
 5195: #   An & separated list of results is written to $client.
 5196: #
 5197: sub get_id_handler {
 5198:     my ($cmd, $tail, $client) = @_;
 5199: 
 5200:     
 5201:     my $userinput = "$client:$tail";
 5202:     
 5203:     my ($udom,$what)=split(/:/,$tail);
 5204:     chomp($what);
 5205:     my @queries=split(/\&/,$what);
 5206:     my $qresult='';
 5207:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
 5208:     if ($hashref) {
 5209: 	for (my $i=0;$i<=$#queries;$i++) {
 5210: 	    $qresult.="$hashref->{$queries[$i]}&";
 5211: 	}
 5212: 	if (&untie_domain_hash($hashref)) {
 5213: 	    $qresult=~s/\&$//;
 5214: 	    &Reply($client, \$qresult, $userinput);
 5215: 	} else {
 5216: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 5217: 		      "while attempting idget\n",$userinput);
 5218: 	}
 5219:     } else {
 5220: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 5221: 		 "while attempting idget\n",$userinput);
 5222:     }
 5223:     
 5224:     return 1;
 5225: }
 5226: &register_handler("idget", \&get_id_handler, 0, 1, 0);
 5227: 
 5228: #   Deletes one or more ids in a domain's id database.
 5229: #
 5230: #   Parameters:
 5231: #       $cmd                  - Command keyword (iddel).
 5232: #       $tail                 - Command tail.  In this case a colon
 5233: #                               separated list containing:
 5234: #                               The domain for which we are deleting the id(s).
 5235: #                               &-separated list of id(s) to delete.
 5236: #       $client               - File open on client socket.
 5237: # Returns:
 5238: #     1   - Continue processing
 5239: #     0   - Exit server.
 5240: #     
 5241: #
 5242: 
 5243: sub del_id_handler {
 5244:     my ($cmd,$tail,$client) = @_;
 5245: 
 5246:     my $userinput = "$cmd:$tail";
 5247: 
 5248:     my ($udom,$what)=split(/:/,$tail);
 5249:     chomp($what);
 5250:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
 5251:                                    "D", $what);
 5252:     if ($hashref) {
 5253:         my @keys=split(/\&/,$what);
 5254:         foreach my $key (@keys) {
 5255:             delete($hashref->{$key});
 5256:         }
 5257:         if (&untie_user_hash($hashref)) {
 5258:             &Reply($client, "ok\n", $userinput);
 5259:         } else {
 5260:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5261:                     "while attempting iddel\n", $userinput);
 5262:         }
 5263:     } else {
 5264:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 5265:                  "while attempting iddel\n", $userinput);
 5266:     }
 5267:     return 1;
 5268: }
 5269: &register_handler("iddel", \&del_id_handler, 0, 1, 0);
 5270: 
 5271: #
 5272: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
 5273: #
 5274: # Parameters
 5275: #   $cmd       - Command keyword that caused us to be dispatched.
 5276: #   $tail      - Tail of the command.  Consists of a colon separated:
 5277: #               domain - the domain whose dcmail we are recording
 5278: #               email    Consists of key=value pair 
 5279: #                        where key is unique msgid
 5280: #                        and value is message (in XML)
 5281: #   $client    - Socket open on the client.
 5282: #
 5283: # Returns:
 5284: #    1 - indicating processing should continue.
 5285: # Side effects
 5286: #     reply is written to $client.
 5287: #
 5288: sub put_dcmail_handler {
 5289:     my ($cmd,$tail,$client) = @_;
 5290:     my $userinput = "$cmd:$tail";
 5291: 
 5292: 
 5293:     my ($udom,$what)=split(/:/,$tail);
 5294:     chomp($what);
 5295:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
 5296:     if ($hashref) {
 5297:         my ($key,$value)=split(/=/,$what);
 5298:         $hashref->{$key}=$value;
 5299:     }
 5300:     if (&untie_domain_hash($hashref)) {
 5301:         &Reply($client, "ok\n", $userinput);
 5302:     } else {
 5303:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5304:                  "while attempting dcmailput\n", $userinput);
 5305:     }
 5306:     return 1;
 5307: }
 5308: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
 5309: 
 5310: #
 5311: # Retrieves broadcast e-mail from nohist_dcmail database
 5312: # Returns to client an & separated list of key=value pairs,
 5313: # where key is msgid and value is message information.
 5314: #
 5315: # Parameters
 5316: #   $cmd       - Command keyword that caused us to be dispatched.
 5317: #   $tail      - Tail of the command.  Consists of a colon separated:
 5318: #               domain - the domain whose dcmail table we dump
 5319: #               startfilter - beginning of time window 
 5320: #               endfilter - end of time window
 5321: #               sendersfilter - & separated list of username:domain 
 5322: #                 for senders to search for.
 5323: #   $client    - Socket open on the client.
 5324: #
 5325: # Returns:
 5326: #    1 - indicating processing should continue.
 5327: # Side effects
 5328: #     reply (& separated list of msgid=messageinfo pairs) is 
 5329: #     written to $client.
 5330: #
 5331: sub dump_dcmail_handler {
 5332:     my ($cmd, $tail, $client) = @_;
 5333:                                                                                 
 5334:     my $userinput = "$cmd:$tail";
 5335:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
 5336:     chomp($sendersfilter);
 5337:     my @senders = ();
 5338:     if (defined($startfilter)) {
 5339:         $startfilter=&unescape($startfilter);
 5340:     } else {
 5341:         $startfilter='.';
 5342:     }
 5343:     if (defined($endfilter)) {
 5344:         $endfilter=&unescape($endfilter);
 5345:     } else {
 5346:         $endfilter='.';
 5347:     }
 5348:     if (defined($sendersfilter)) {
 5349:         $sendersfilter=&unescape($sendersfilter);
 5350: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
 5351:     }
 5352: 
 5353:     my $qresult='';
 5354:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
 5355:     if ($hashref) {
 5356:         while (my ($key,$value) = each(%$hashref)) {
 5357:             my $match = 1;
 5358:             my ($timestamp,$subj,$uname,$udom) = 
 5359: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
 5360:             $subj = &unescape($subj);
 5361:             unless ($startfilter eq '.' || !defined($startfilter)) {
 5362:                 if ($timestamp < $startfilter) {
 5363:                     $match = 0;
 5364:                 }
 5365:             }
 5366:             unless ($endfilter eq '.' || !defined($endfilter)) {
 5367:                 if ($timestamp > $endfilter) {
 5368:                     $match = 0;
 5369:                 }
 5370:             }
 5371:             unless (@senders < 1) {
 5372:                 unless (grep/^$uname:$udom$/,@senders) {
 5373:                     $match = 0;
 5374:                 }
 5375:             }
 5376:             if ($match == 1) {
 5377:                 $qresult.=$key.'='.$value.'&';
 5378:             }
 5379:         }
 5380:         if (&untie_domain_hash($hashref)) {
 5381:             chop($qresult);
 5382:             &Reply($client, \$qresult, $userinput);
 5383:         } else {
 5384:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5385:                     "while attempting dcmaildump\n", $userinput);
 5386:         }
 5387:     } else {
 5388:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 5389:                 "while attempting dcmaildump\n", $userinput);
 5390:     }
 5391:     return 1;
 5392: }
 5393: 
 5394: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
 5395: 
 5396: #
 5397: # Puts domain roles in nohist_domainroles database
 5398: #
 5399: # Parameters
 5400: #   $cmd       - Command keyword that caused us to be dispatched.
 5401: #   $tail      - Tail of the command.  Consists of a colon separated:
 5402: #               domain - the domain whose roles we are recording  
 5403: #               role -   Consists of key=value pair
 5404: #                        where key is unique role
 5405: #                        and value is start/end date information
 5406: #   $client    - Socket open on the client.
 5407: #
 5408: # Returns:
 5409: #    1 - indicating processing should continue.
 5410: # Side effects
 5411: #     reply is written to $client.
 5412: #
 5413: 
 5414: sub put_domainroles_handler {
 5415:     my ($cmd,$tail,$client) = @_;
 5416: 
 5417:     my $userinput = "$cmd:$tail";
 5418:     my ($udom,$what)=split(/:/,$tail);
 5419:     chomp($what);
 5420:     my @pairs=split(/\&/,$what);
 5421:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
 5422:     if ($hashref) {
 5423:         foreach my $pair (@pairs) {
 5424:             my ($key,$value)=split(/=/,$pair);
 5425:             $hashref->{$key}=$value;
 5426:         }
 5427:         if (&untie_domain_hash($hashref)) {
 5428:             &Reply($client, "ok\n", $userinput);
 5429:         } else {
 5430:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5431:                      "while attempting domroleput\n", $userinput);
 5432:         }
 5433:     } else {
 5434:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 5435:                   "while attempting domroleput\n", $userinput);
 5436:     }
 5437:                                                                                   
 5438:     return 1;
 5439: }
 5440: 
 5441: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
 5442: 
 5443: #
 5444: # Retrieves domain roles from nohist_domainroles database
 5445: # Returns to client an & separated list of key=value pairs,
 5446: # where key is role and value is start and end date information.
 5447: #
 5448: # Parameters
 5449: #   $cmd       - Command keyword that caused us to be dispatched.
 5450: #   $tail      - Tail of the command.  Consists of a colon separated:
 5451: #               domain - the domain whose domain roles table we dump
 5452: #   $client    - Socket open on the client.
 5453: #
 5454: # Returns:
 5455: #    1 - indicating processing should continue.
 5456: # Side effects
 5457: #     reply (& separated list of role=start/end info pairs) is
 5458: #     written to $client.
 5459: #
 5460: sub dump_domainroles_handler {
 5461:     my ($cmd, $tail, $client) = @_;
 5462:                                                                                            
 5463:     my $userinput = "$cmd:$tail";
 5464:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
 5465:     chomp($rolesfilter);
 5466:     my @roles = ();
 5467:     if (defined($startfilter)) {
 5468:         $startfilter=&unescape($startfilter);
 5469:     } else {
 5470:         $startfilter='.';
 5471:     }
 5472:     if (defined($endfilter)) {
 5473:         $endfilter=&unescape($endfilter);
 5474:     } else {
 5475:         $endfilter='.';
 5476:     }
 5477:     if (defined($rolesfilter)) {
 5478:         $rolesfilter=&unescape($rolesfilter);
 5479: 	@roles = split(/\&/,$rolesfilter);
 5480:     }
 5481: 
 5482:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
 5483:     if ($hashref) {
 5484:         my $qresult = '';
 5485:         while (my ($key,$value) = each(%$hashref)) {
 5486:             my $match = 1;
 5487:             my ($end,$start) = split(/:/,&unescape($value));
 5488:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
 5489:             unless (@roles < 1) {
 5490:                 unless (grep/^\Q$trole\E$/,@roles) {
 5491:                     $match = 0;
 5492:                     next;
 5493:                 }
 5494:             }
 5495:             unless ($startfilter eq '.' || !defined($startfilter)) {
 5496:                 if ((defined($start)) && ($start >= $startfilter)) {
 5497:                     $match = 0;
 5498:                     next;
 5499:                 }
 5500:             }
 5501:             unless ($endfilter eq '.' || !defined($endfilter)) {
 5502:                 if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
 5503:                     $match = 0;
 5504:                     next;
 5505:                 }
 5506:             }
 5507:             if ($match == 1) {
 5508:                 $qresult.=$key.'='.$value.'&';
 5509:             }
 5510:         }
 5511:         if (&untie_domain_hash($hashref)) {
 5512:             chop($qresult);
 5513:             &Reply($client, \$qresult, $userinput);
 5514:         } else {
 5515:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5516:                     "while attempting domrolesdump\n", $userinput);
 5517:         }
 5518:     } else {
 5519:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 5520:                 "while attempting domrolesdump\n", $userinput);
 5521:     }
 5522:     return 1;
 5523: }
 5524: 
 5525: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
 5526: 
 5527: 
 5528: #  Process the tmpput command I'm not sure what this does.. Seems to
 5529: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
 5530: # where Id is the client's ip concatenated with a sequence number.
 5531: # The file will contain some value that is passed in.  Is this e.g.
 5532: # a login token?
 5533: #
 5534: # Parameters:
 5535: #    $cmd     - The command that got us dispatched.
 5536: #    $tail    - The remainder of the request following $cmd:
 5537: #               In this case this will be the contents of the file.
 5538: #    $client  - Socket connected to the client.
 5539: # Returns:
 5540: #    1 indicating processing can continue.
 5541: # Side effects:
 5542: #   A file is created in the local filesystem.
 5543: #   A reply is sent to the client.
 5544: sub tmp_put_handler {
 5545:     my ($cmd, $what, $client) = @_;
 5546: 
 5547:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
 5548: 
 5549:     my ($record,$context) = split(/:/,$what);
 5550:     if ($context ne '') {
 5551:         chomp($context);
 5552:         $context = &unescape($context);
 5553:     }
 5554:     my ($id,$store);
 5555:     $tmpsnum++;
 5556:     if (($context eq 'resetpw') || ($context eq 'createaccount')) {
 5557:         $id = &md5_hex(&md5_hex(time.{}.rand().$$));
 5558:     } else {
 5559:         $id = $$.'_'.$clientip.'_'.$tmpsnum;
 5560:     }
 5561:     $id=~s/\W/\_/g;
 5562:     $record=~s/\n//g;
 5563:     my $execdir=$perlvar{'lonDaemons'};
 5564:     if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
 5565: 	print $store $record;
 5566: 	close $store;
 5567: 	&Reply($client, \$id, $userinput);
 5568:     } else {
 5569: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
 5570: 		  "while attempting tmpput\n", $userinput);
 5571:     }
 5572:     return 1;
 5573:   
 5574: }
 5575: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
 5576: 
 5577: #   Processes the tmpget command.  This command returns the contents
 5578: #  of a temporary resource file(?) created via tmpput.
 5579: #
 5580: # Paramters:
 5581: #    $cmd      - Command that got us dispatched.
 5582: #    $id       - Tail of the command, contain the id of the resource
 5583: #                we want to fetch.
 5584: #    $client   - socket open on the client.
 5585: # Return:
 5586: #    1         - Inidcating processing can continue.
 5587: # Side effects:
 5588: #   A reply is sent to the client.
 5589: #
 5590: sub tmp_get_handler {
 5591:     my ($cmd, $id, $client) = @_;
 5592: 
 5593:     my $userinput = "$cmd:$id"; 
 5594:     
 5595: 
 5596:     $id=~s/\W/\_/g;
 5597:     my $store;
 5598:     my $execdir=$perlvar{'lonDaemons'};
 5599:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
 5600: 	my $reply=<$store>;
 5601: 	&Reply( $client, \$reply, $userinput);
 5602: 	close $store;
 5603:     } else {
 5604: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
 5605: 		  "while attempting tmpget\n", $userinput);
 5606:     }
 5607: 
 5608:     return 1;
 5609: }
 5610: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
 5611: 
 5612: #
 5613: #  Process the tmpdel command.  This command deletes a temp resource
 5614: #  created by the tmpput command.
 5615: #
 5616: # Parameters:
 5617: #   $cmd      - Command that got us here.
 5618: #   $id       - Id of the temporary resource created.
 5619: #   $client   - socket open on the client process.
 5620: #
 5621: # Returns:
 5622: #   1     - Indicating processing should continue.
 5623: # Side Effects:
 5624: #   A file is deleted
 5625: #   A reply is sent to the client.
 5626: sub tmp_del_handler {
 5627:     my ($cmd, $id, $client) = @_;
 5628:     
 5629:     my $userinput= "$cmd:$id";
 5630:     
 5631:     chomp($id);
 5632:     $id=~s/\W/\_/g;
 5633:     my $execdir=$perlvar{'lonDaemons'};
 5634:     if (unlink("$execdir/tmp/$id.tmp")) {
 5635: 	&Reply($client, "ok\n", $userinput);
 5636:     } else {
 5637: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
 5638: 		  "while attempting tmpdel\n", $userinput);
 5639:     }
 5640:     
 5641:     return 1;
 5642: 
 5643: }
 5644: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
 5645: 
 5646: #
 5647: #  Process the delbalcookie command. This command deletes a balancer
 5648: #  cookie in the lonBalancedir directory created by switchserver
 5649: #
 5650: # Parameters:
 5651: #   $cmd      - Command that got us here.
 5652: #   $cookie   - Cookie to be deleted.
 5653: #   $client   - socket open on the client process.
 5654: #
 5655: # Returns:
 5656: #   1     - Indicating processing should continue.
 5657: # Side Effects:
 5658: #   A cookie file is deleted from the lonBalancedir directory
 5659: #   A reply is sent to the client.
 5660: sub del_balcookie_handler {
 5661:     my ($cmd, $cookie, $client) = @_;
 5662: 
 5663:     my $userinput= "$cmd:$cookie";
 5664: 
 5665:     chomp($cookie);
 5666:     my $deleted = '';
 5667:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
 5668:         my $execdir=$perlvar{'lonBalanceDir'};
 5669:         if (-e "$execdir/$cookie.id") {
 5670:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
 5671:                 my $dodelete;
 5672:                 while (my $line = <$fh>) {
 5673:                     chomp($line);
 5674:                     if ($line eq $clientname) {
 5675:                         $dodelete = 1;
 5676:                         last;
 5677:                     }
 5678:                 }
 5679:                 close($fh);
 5680:                 if ($dodelete) {
 5681:                     if (unlink("$execdir/$cookie.id")) {
 5682:                         $deleted = 1;
 5683:                     }
 5684:                 }
 5685:             }
 5686:         }
 5687:     }
 5688:     if ($deleted) {
 5689:         &Reply($client, "ok\n", $userinput);
 5690:     } else {
 5691:         &Failure( $client, "error: ".($!+0)."Unlinking cookie file Failed ".
 5692:                   "while attempting delbalcookie\n", $userinput);
 5693:     }
 5694:     return 1;
 5695: }
 5696: &register_handler("delbalcookie", \&del_balcookie_handler, 0, 1, 0);
 5697: 
 5698: #
 5699: #   Processes the setannounce command.  This command
 5700: #   creates a file named announce.txt in the top directory of
 5701: #   the documentn root and sets its contents.  The announce.txt file is
 5702: #   printed in its entirety at the LonCAPA login page.  Note:
 5703: #   once the announcement.txt fileis created it cannot be deleted.
 5704: #   However, setting the contents of the file to empty removes the
 5705: #   announcement from the login page of loncapa so who cares.
 5706: #
 5707: # Parameters:
 5708: #    $cmd          - The command that got us dispatched.
 5709: #    $announcement - The text of the announcement.
 5710: #    $client       - Socket open on the client process.
 5711: # Retunrns:
 5712: #   1             - Indicating request processing should continue
 5713: # Side Effects:
 5714: #   The file {DocRoot}/announcement.txt is created.
 5715: #   A reply is sent to $client.
 5716: #
 5717: sub set_announce_handler {
 5718:     my ($cmd, $announcement, $client) = @_;
 5719:   
 5720:     my $userinput    = "$cmd:$announcement";
 5721: 
 5722:     chomp($announcement);
 5723:     $announcement=&unescape($announcement);
 5724:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
 5725: 				'/announcement.txt')) {
 5726: 	print $store $announcement;
 5727: 	close $store;
 5728: 	&Reply($client, "ok\n", $userinput);
 5729:     } else {
 5730: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
 5731:     }
 5732: 
 5733:     return 1;
 5734: }
 5735: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
 5736: 
 5737: #
 5738: #  Return the version of the daemon.  This can be used to determine
 5739: #  the compatibility of cross version installations or, alternatively to
 5740: #  simply know who's out of date and who isn't.  Note that the version
 5741: #  is returned concatenated with the tail.
 5742: # Parameters:
 5743: #   $cmd        - the request that dispatched to us.
 5744: #   $tail       - Tail of the request (client's version?).
 5745: #   $client     - Socket open on the client.
 5746: #Returns:
 5747: #   1 - continue processing requests.
 5748: # Side Effects:
 5749: #   Replies with version to $client.
 5750: sub get_version_handler {
 5751:     my ($cmd, $tail, $client) = @_;
 5752: 
 5753:     my $userinput  = $cmd.$tail;
 5754:     
 5755:     &Reply($client, &version($userinput)."\n", $userinput);
 5756: 
 5757: 
 5758:     return 1;
 5759: }
 5760: &register_handler("version", \&get_version_handler, 0, 1, 0);
 5761: 
 5762: #  Set the current host and domain.  This is used to support
 5763: #  multihomed systems.  Each IP of the system, or even separate daemons
 5764: #  on the same IP can be treated as handling a separate lonCAPA virtual
 5765: #  machine.  This command selects the virtual lonCAPA.  The client always
 5766: #  knows the right one since it is lonc and it is selecting the domain/system
 5767: #  from the hosts.tab file.
 5768: # Parameters:
 5769: #    $cmd      - Command that dispatched us.
 5770: #    $tail     - Tail of the command (domain/host requested).
 5771: #    $socket   - Socket open on the client.
 5772: #
 5773: # Returns:
 5774: #     1   - Indicates the program should continue to process requests.
 5775: # Side-effects:
 5776: #     The default domain/system context is modified for this daemon.
 5777: #     a reply is sent to the client.
 5778: #
 5779: sub set_virtual_host_handler {
 5780:     my ($cmd, $tail, $socket) = @_;
 5781:   
 5782:     my $userinput  ="$cmd:$tail";
 5783: 
 5784:     &Reply($client, &sethost($userinput)."\n", $userinput);
 5785: 
 5786: 
 5787:     return 1;
 5788: }
 5789: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
 5790: 
 5791: #  Process a request to exit:
 5792: #   - "bye" is sent to the client.
 5793: #   - The client socket is shutdown and closed.
 5794: #   - We indicate to the caller that we should exit.
 5795: # Formal Parameters:
 5796: #   $cmd                - The command that got us here.
 5797: #   $tail               - Tail of the command (empty).
 5798: #   $client             - Socket open on the tail.
 5799: # Returns:
 5800: #   0      - Indicating the program should exit!!
 5801: #
 5802: sub exit_handler {
 5803:     my ($cmd, $tail, $client) = @_;
 5804: 
 5805:     my $userinput = "$cmd:$tail";
 5806: 
 5807:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
 5808:     &Reply($client, "bye\n", $userinput);
 5809:     $client->shutdown(2);        # shutdown the socket forcibly.
 5810:     $client->close();
 5811: 
 5812:     return 0;
 5813: }
 5814: &register_handler("exit", \&exit_handler, 0,1,1);
 5815: &register_handler("init", \&exit_handler, 0,1,1);
 5816: &register_handler("quit", \&exit_handler, 0,1,1);
 5817: 
 5818: #  Determine if auto-enrollment is enabled.
 5819: #  Note that the original had what I believe to be a defect.
 5820: #  The original returned 0 if the requestor was not a registerd client.
 5821: #  It should return "refused".
 5822: # Formal Parameters:
 5823: #   $cmd       - The command that invoked us.
 5824: #   $tail      - The tail of the command (Extra command parameters.
 5825: #   $client    - The socket open on the client that issued the request.
 5826: # Returns:
 5827: #    1         - Indicating processing should continue.
 5828: #
 5829: sub enrollment_enabled_handler {
 5830:     my ($cmd, $tail, $client) = @_;
 5831:     my $userinput = $cmd.":".$tail; # For logging purposes.
 5832: 
 5833:     
 5834:     my ($cdom) = split(/:/, $tail, 2);   # Domain we're asking about.
 5835: 
 5836:     my $outcome  = &localenroll::run($cdom);
 5837:     &Reply($client, \$outcome, $userinput);
 5838: 
 5839:     return 1;
 5840: }
 5841: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
 5842: 
 5843: #
 5844: #   Validate an institutional code used for a LON-CAPA course.          
 5845: #
 5846: # Formal Parameters:
 5847: #   $cmd          - The command request that got us dispatched.
 5848: #   $tail         - The tail of the command.  In this case,
 5849: #                   this is a colon separated set of words that will be split
 5850: #                   into:
 5851: #                        $dom      - The domain for which the check of 
 5852: #                                    institutional course code will occur.
 5853: #
 5854: #                        $instcode - The institutional code for the course
 5855: #                                    being requested, or validated for rights
 5856: #                                    to request.
 5857: #
 5858: #                        $owner    - The course requestor (who will be the
 5859: #                                    course owner, in the form username:domain
 5860: #
 5861: #   $client       - Socket open on the client.
 5862: # Returns:
 5863: #    1           - Indicating processing should continue.
 5864: #
 5865: sub validate_instcode_handler {
 5866:     my ($cmd, $tail, $client) = @_;
 5867:     my $userinput = "$cmd:$tail";
 5868:     my ($dom,$instcode,$owner) = split(/:/, $tail);
 5869:     $instcode = &unescape($instcode);
 5870:     $owner = &unescape($owner);
 5871:     my ($outcome,$description,$credits) = 
 5872:         &localenroll::validate_instcode($dom,$instcode,$owner);
 5873:     my $result = &escape($outcome).'&'.&escape($description).'&'.
 5874:                  &escape($credits);
 5875:     &Reply($client, \$result, $userinput);
 5876: 
 5877:     return 1;
 5878: }
 5879: &register_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
 5880: 
 5881: #   Get the official sections for which auto-enrollment is possible.
 5882: #   Since the admin people won't know about 'unofficial sections' 
 5883: #   we cannot auto-enroll on them.
 5884: # Formal Parameters:
 5885: #    $cmd     - The command request that got us dispatched here.
 5886: #    $tail    - The remainder of the request.  In our case this
 5887: #               will be split into:
 5888: #               $coursecode   - The course name from the admin point of view.
 5889: #               $cdom         - The course's domain(?).
 5890: #    $client  - Socket open on the client.
 5891: # Returns:
 5892: #    1    - Indiciting processing should continue.
 5893: #
 5894: sub get_sections_handler {
 5895:     my ($cmd, $tail, $client) = @_;
 5896:     my $userinput = "$cmd:$tail";
 5897: 
 5898:     my ($coursecode, $cdom) = split(/:/, $tail);
 5899:     my @secs = &localenroll::get_sections($coursecode,$cdom);
 5900:     my $seclist = &escape(join(':',@secs));
 5901: 
 5902:     &Reply($client, \$seclist, $userinput);
 5903:     
 5904: 
 5905:     return 1;
 5906: }
 5907: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
 5908: 
 5909: #   Validate the owner of a new course section.  
 5910: #
 5911: # Formal Parameters:
 5912: #   $cmd      - Command that got us dispatched.
 5913: #   $tail     - the remainder of the command.  For us this consists of a
 5914: #               colon separated string containing:
 5915: #                  $inst    - Course Id from the institutions point of view.
 5916: #                  $owner   - Proposed owner of the course.
 5917: #                  $cdom    - Domain of the course (from the institutions
 5918: #                             point of view?)..
 5919: #   $client   - Socket open on the client.
 5920: #
 5921: # Returns:
 5922: #   1        - Processing should continue.
 5923: #
 5924: sub validate_course_owner_handler {
 5925:     my ($cmd, $tail, $client)  = @_;
 5926:     my $userinput = "$cmd:$tail";
 5927:     my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
 5928:     
 5929:     $owner = &unescape($owner);
 5930:     $coowners = &unescape($coowners);
 5931:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
 5932:     &Reply($client, \$outcome, $userinput);
 5933: 
 5934: 
 5935: 
 5936:     return 1;
 5937: }
 5938: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
 5939: 
 5940: #
 5941: #   Validate a course section in the official schedule of classes
 5942: #   from the institutions point of view (part of autoenrollment).
 5943: #
 5944: # Formal Parameters:
 5945: #   $cmd          - The command request that got us dispatched.
 5946: #   $tail         - The tail of the command.  In this case,
 5947: #                   this is a colon separated set of words that will be split
 5948: #                   into:
 5949: #                        $inst_course_id - The course/section id from the
 5950: #                                          institutions point of view.
 5951: #                        $cdom           - The domain from the institutions
 5952: #                                          point of view.
 5953: #   $client       - Socket open on the client.
 5954: # Returns:
 5955: #    1           - Indicating processing should continue.
 5956: #
 5957: sub validate_course_section_handler {
 5958:     my ($cmd, $tail, $client) = @_;
 5959:     my $userinput = "$cmd:$tail";
 5960:     my ($inst_course_id, $cdom) = split(/:/, $tail);
 5961: 
 5962:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
 5963:     &Reply($client, \$outcome, $userinput);
 5964: 
 5965: 
 5966:     return 1;
 5967: }
 5968: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
 5969: 
 5970: #
 5971: #   Validate course owner's access to enrollment data for specific class section. 
 5972: #   
 5973: #
 5974: # Formal Parameters:
 5975: #    $cmd     - The command request that got us dispatched.
 5976: #    $tail    - The tail of the command.   In this case this is a colon separated
 5977: #               set of values that will be split into:
 5978: #               $inst_class  - Institutional code for the specific class section   
 5979: #               $ownerlist   - An escaped comma-separated list of username:domain 
 5980: #                              of the course owner, and co-owner(s).
 5981: #               $cdom        - The domain of the course from the institution's
 5982: #                              point of view.
 5983: #    $client  - The socket open on the client.
 5984: # Returns:
 5985: #    1 - continue processing.
 5986: #
 5987: 
 5988: sub validate_class_access_handler {
 5989:     my ($cmd, $tail, $client) = @_;
 5990:     my $userinput = "$cmd:$tail";
 5991:     my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
 5992:     my $owners = &unescape($ownerlist);
 5993:     my $outcome;
 5994:     eval {
 5995: 	local($SIG{__DIE__})='DEFAULT';
 5996: 	$outcome=&localenroll::check_section($inst_class,$owners,$cdom);
 5997:     };
 5998:     &Reply($client,\$outcome, $userinput);
 5999: 
 6000:     return 1;
 6001: }
 6002: &register_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
 6003: 
 6004: #
 6005: #   Validate course owner or co-owners(s) access to enrollment data for all sections
 6006: #   and crosslistings for a particular course.
 6007: #
 6008: #
 6009: # Formal Parameters:
 6010: #    $cmd     - The command request that got us dispatched.
 6011: #    $tail    - The tail of the command.   In this case this is a colon separated
 6012: #               set of values that will be split into:
 6013: #               $ownerlist   - An escaped comma-separated list of username:domain
 6014: #                              of the course owner, and co-owner(s).
 6015: #               $cdom        - The domain of the course from the institution's
 6016: #                              point of view.
 6017: #               $classes     - Frozen hash of institutional course sections and
 6018: #                              crosslistings.
 6019: #    $client  - The socket open on the client.
 6020: # Returns:
 6021: #    1 - continue processing.
 6022: #
 6023: 
 6024: sub validate_classes_handler {
 6025:     my ($cmd, $tail, $client) = @_;
 6026:     my $userinput = "$cmd:$tail";
 6027:     my ($ownerlist,$cdom,$classes) = split(/:/, $tail);
 6028:     my $classesref = &Apache::lonnet::thaw_unescape($classes);
 6029:     my $owners = &unescape($ownerlist);
 6030:     my $result;
 6031:     eval {
 6032:         local($SIG{__DIE__})='DEFAULT';
 6033:         my %validations;
 6034:         my $response = &localenroll::check_instclasses($owners,$cdom,$classesref,
 6035:                                                        \%validations);
 6036:         if ($response eq 'ok') {
 6037:             foreach my $key (keys(%validations)) {
 6038:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
 6039:             }
 6040:             $result =~ s/\&$//;
 6041:         } else {
 6042:             $result = 'error';
 6043:         }
 6044:     };
 6045:     if (!$@) {
 6046:         &Reply($client, \$result, $userinput);
 6047:     } else {
 6048:         &Failure($client,"unknown_cmd\n",$userinput);
 6049:     }
 6050:     return 1;
 6051: }
 6052: &register_handler("autovalidateinstclasses", \&validate_classes_handler, 0, 1, 0);
 6053: 
 6054: #
 6055: #   Create a password for a new LON-CAPA user added by auto-enrollment.
 6056: #   Only used for case where authentication method for new user is localauth
 6057: #
 6058: # Formal Parameters:
 6059: #    $cmd     - The command request that got us dispatched.
 6060: #    $tail    - The tail of the command.   In this case this is a colon separated
 6061: #               set of words that will be split into:
 6062: #               $authparam - An authentication parameter (localauth parameter).
 6063: #               $cdom      - The domain of the course from the institution's
 6064: #                            point of view.
 6065: #    $client  - The socket open on the client.
 6066: # Returns:
 6067: #    1 - continue processing.
 6068: #
 6069: sub create_auto_enroll_password_handler {
 6070:     my ($cmd, $tail, $client) = @_;
 6071:     my $userinput = "$cmd:$tail";
 6072: 
 6073:     my ($authparam, $cdom) = split(/:/, $userinput);
 6074: 
 6075:     my ($create_passwd,$authchk);
 6076:     ($authparam,
 6077:      $create_passwd,
 6078:      $authchk) = &localenroll::create_password($authparam,$cdom);
 6079: 
 6080:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
 6081: 	   $userinput);
 6082: 
 6083: 
 6084:     return 1;
 6085: }
 6086: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
 6087: 		  0, 1, 0);
 6088: 
 6089: sub auto_export_grades_handler {
 6090:     my ($cmd, $tail, $client) = @_;
 6091:     my $userinput = "$cmd:$tail";
 6092:     my ($cdom,$cnum,$info,$data) = split(/:/,$tail);
 6093:     my $inforef = &Apache::lonnet::thaw_unescape($info);
 6094:     my $dataref = &Apache::lonnet::thaw_unescape($data);
 6095:     my ($outcome,$result);;
 6096:     eval {
 6097:         local($SIG{__DIE__})='DEFAULT';
 6098:         my %rtnhash;
 6099:         $outcome=&localenroll::export_grades($cdom,$cnum,$inforef,$dataref,\%rtnhash);
 6100:         if ($outcome eq 'ok') {
 6101:             foreach my $key (keys(%rtnhash)) {
 6102:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
 6103:             }
 6104:             $result =~ s/\&$//;
 6105:         }
 6106:     };
 6107:     if (!$@) {
 6108:         if ($outcome eq 'ok') {
 6109:             if ($cipher) {
 6110:                 my $cmdlength=length($result);
 6111:                 $result.="         ";
 6112:                 my $encresult='';
 6113:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 6114:                     $encresult.= unpack("H16",
 6115:                                         $cipher->encrypt(substr($result,
 6116:                                                                 $encidx,
 6117:                                                                 8)));
 6118:                 }
 6119:                 &Reply( $client, "enc:$cmdlength:$encresult\n", $userinput);
 6120:             } else {
 6121:                 &Failure( $client, "error:no_key\n", $userinput);
 6122:             }
 6123:         } else {
 6124:             &Reply($client, "$outcome\n", $userinput);
 6125:         }
 6126:     } else {
 6127:         &Failure($client,"export_error\n",$userinput);
 6128:     }
 6129:     return 1;
 6130: }
 6131: &register_handler("autoexportgrades", \&auto_export_grades_handler,
 6132:                   1, 1, 0);
 6133: 
 6134: #   Retrieve and remove temporary files created by/during autoenrollment.
 6135: #
 6136: # Formal Parameters:
 6137: #    $cmd      - The command that got us dispatched.
 6138: #    $tail     - The tail of the command.  In our case this is a colon 
 6139: #                separated list that will be split into:
 6140: #                $filename - The name of the file to retrieve.
 6141: #                            The filename is given as a path relative to
 6142: #                            the LonCAPA temp file directory.
 6143: #    $client   - Socket open on the client.
 6144: #
 6145: # Returns:
 6146: #   1     - Continue processing.
 6147: sub retrieve_auto_file_handler {
 6148:     my ($cmd, $tail, $client)    = @_;
 6149:     my $userinput                = "cmd:$tail";
 6150: 
 6151:     my ($filename)   = split(/:/, $tail);
 6152: 
 6153:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
 6154: 
 6155:     if ($filename =~m{/\.\./}) {
 6156:         &Failure($client, "refused\n", $userinput);
 6157:     } elsif ($filename !~ /^$LONCAPA::match_domain\_$LONCAPA::match_courseid\_.+_classlist\.xml$/) {
 6158:         &Failure($client, "refused\n", $userinput);
 6159:     } elsif ( (-e $source) && ($filename ne '') ) {
 6160: 	my $reply = '';
 6161: 	if (open(my $fh,$source)) {
 6162: 	    while (<$fh>) {
 6163: 		chomp($_);
 6164: 		$_ =~ s/^\s+//g;
 6165: 		$_ =~ s/\s+$//g;
 6166: 		$reply .= $_;
 6167: 	    }
 6168: 	    close($fh);
 6169: 	    &Reply($client, &escape($reply)."\n", $userinput);
 6170: 
 6171: #   Does this have to be uncommented??!?  (RF).
 6172: #
 6173: #                                unlink($source);
 6174: 	} else {
 6175: 	    &Failure($client, "error\n", $userinput);
 6176: 	}
 6177:     } else {
 6178: 	&Failure($client, "error\n", $userinput);
 6179:     }
 6180:     
 6181: 
 6182:     return 1;
 6183: }
 6184: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
 6185: 
 6186: sub crsreq_checks_handler {
 6187:     my ($cmd, $tail, $client) = @_;
 6188:     my $userinput = "$cmd:$tail";
 6189:     my $dom = $tail;
 6190:     my $result;
 6191:     my @reqtypes = ('official','unofficial','community','textbook','placement');
 6192:     eval {
 6193:         local($SIG{__DIE__})='DEFAULT';
 6194:         my %validations;
 6195:         my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
 6196:                                                    \%validations);
 6197:         if ($response eq 'ok') { 
 6198:             foreach my $key (keys(%validations)) {
 6199:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
 6200:             }
 6201:             $result =~ s/\&$//;
 6202:         } else {
 6203:             $result = 'error';
 6204:         }
 6205:     };
 6206:     if (!$@) {
 6207:         &Reply($client, \$result, $userinput);
 6208:     } else {
 6209:         &Failure($client,"unknown_cmd\n",$userinput);
 6210:     }
 6211:     return 1;
 6212: }
 6213: &register_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
 6214: 
 6215: sub validate_crsreq_handler {
 6216:     my ($cmd, $tail, $client) = @_;
 6217:     my $userinput = "$cmd:$tail";
 6218:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
 6219:     $instcode = &unescape($instcode);
 6220:     $owner = &unescape($owner);
 6221:     $crstype = &unescape($crstype);
 6222:     $inststatuslist = &unescape($inststatuslist);
 6223:     $instcode = &unescape($instcode);
 6224:     $instseclist = &unescape($instseclist);
 6225:     my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
 6226:     my $outcome;
 6227:     eval {
 6228:         local($SIG{__DIE__})='DEFAULT';
 6229:         $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
 6230:                                                  $inststatuslist,$instcode,
 6231:                                                  $instseclist,$custominfo);
 6232:     };
 6233:     if (!$@) {
 6234:         &Reply($client, \$outcome, $userinput);
 6235:     } else {
 6236:         &Failure($client,"unknown_cmd\n",$userinput);
 6237:     }
 6238:     return 1;
 6239: }
 6240: &register_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
 6241: 
 6242: sub crsreq_update_handler {
 6243:     my ($cmd, $tail, $client) = @_;
 6244:     my $userinput = "$cmd:$tail";
 6245:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
 6246:         $accessstart,$accessend,$infohashref) =
 6247:         split(/:/, $tail);
 6248:     $crstype = &unescape($crstype);
 6249:     $action = &unescape($action);
 6250:     $ownername = &unescape($ownername);
 6251:     $ownerdomain = &unescape($ownerdomain);
 6252:     $fullname = &unescape($fullname);
 6253:     $title = &unescape($title);
 6254:     $code = &unescape($code);
 6255:     $accessstart = &unescape($accessstart);
 6256:     $accessend = &unescape($accessend);
 6257:     my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
 6258:     my ($result,$outcome);
 6259:     eval {
 6260:         local($SIG{__DIE__})='DEFAULT';
 6261:         my %rtnhash;
 6262:         $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
 6263:                                                 $ownername,$ownerdomain,$fullname,
 6264:                                                 $title,$code,$accessstart,$accessend,
 6265:                                                 $incoming,\%rtnhash);
 6266:         if ($outcome eq 'ok') {
 6267:             my @posskeys = qw(createdweb createdmsg createdcustomized createdactions queuedweb queuedmsg formitems reviewweb validationjs onload javascript);
 6268:             foreach my $key (keys(%rtnhash)) {
 6269:                 if (grep(/^\Q$key\E/,@posskeys)) {
 6270:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
 6271:                 }
 6272:             }
 6273:             $result =~ s/\&$//;
 6274:         }
 6275:     };
 6276:     if (!$@) {
 6277:         if ($outcome eq 'ok') {
 6278:             &Reply($client, \$result, $userinput);
 6279:         } else {
 6280:             &Reply($client, "format_error\n", $userinput);
 6281:         }
 6282:     } else {
 6283:         &Failure($client,"unknown_cmd\n",$userinput);
 6284:     }
 6285:     return 1;
 6286: }
 6287: &register_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
 6288: 
 6289: #
 6290: #   Read and retrieve institutional code format (for support form).
 6291: # Formal Parameters:
 6292: #    $cmd        - Command that dispatched us.
 6293: #    $tail       - Tail of the command.  In this case it conatins 
 6294: #                  the course domain and the coursename.
 6295: #    $client     - Socket open on the client.
 6296: # Returns:
 6297: #    1     - Continue processing.
 6298: #
 6299: sub get_institutional_code_format_handler {
 6300:     my ($cmd, $tail, $client)   = @_;
 6301:     my $userinput               = "$cmd:$tail";
 6302: 
 6303:     my $reply;
 6304:     my($cdom,$course) = split(/:/,$tail);
 6305:     my @pairs = split/\&/,$course;
 6306:     my %instcodes = ();
 6307:     my %codes = ();
 6308:     my @codetitles = ();
 6309:     my %cat_titles = ();
 6310:     my %cat_order = ();
 6311:     foreach (@pairs) {
 6312: 	my ($key,$value) = split/=/,$_;
 6313: 	$instcodes{&unescape($key)} = &unescape($value);
 6314:     }
 6315:     my $formatreply = &localenroll::instcode_format($cdom,
 6316: 						    \%instcodes,
 6317: 						    \%codes,
 6318: 						    \@codetitles,
 6319: 						    \%cat_titles,
 6320: 						    \%cat_order);
 6321:     if ($formatreply eq 'ok') {
 6322: 	my $codes_str = &Apache::lonnet::hash2str(%codes);
 6323: 	my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
 6324: 	my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
 6325: 	my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
 6326: 	&Reply($client,
 6327: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
 6328: 	       .$cat_order_str."\n",
 6329: 	       $userinput);
 6330:     } else {
 6331: 	# this else branch added by RF since if not ok, lonc will
 6332: 	# hang waiting on reply until timeout.
 6333: 	#
 6334: 	&Reply($client, "format_error\n", $userinput);
 6335:     }
 6336:     
 6337:     return 1;
 6338: }
 6339: &register_handler("autoinstcodeformat",
 6340: 		  \&get_institutional_code_format_handler,0,1,0);
 6341: 
 6342: sub get_institutional_defaults_handler {
 6343:     my ($cmd, $tail, $client)   = @_;
 6344:     my $userinput               = "$cmd:$tail";
 6345: 
 6346:     my $dom = $tail;
 6347:     my %defaults_hash;
 6348:     my @code_order;
 6349:     my $outcome;
 6350:     eval {
 6351:         local($SIG{__DIE__})='DEFAULT';
 6352:         $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
 6353:                                                    \@code_order);
 6354:     };
 6355:     if (!$@) {
 6356:         if ($outcome eq 'ok') {
 6357:             my $result='';
 6358:             while (my ($key,$value) = each(%defaults_hash)) {
 6359:                 $result.=&escape($key).'='.&escape($value).'&';
 6360:             }
 6361:             $result .= 'code_order='.&escape(join('&',@code_order));
 6362:             &Reply($client,\$result,$userinput);
 6363:         } else {
 6364:             &Reply($client,"error\n", $userinput);
 6365:         }
 6366:     } else {
 6367:         &Failure($client,"unknown_cmd\n",$userinput);
 6368:     }
 6369: }
 6370: &register_handler("autoinstcodedefaults",
 6371:                   \&get_institutional_defaults_handler,0,1,0);
 6372: 
 6373: sub get_possible_instcodes_handler {
 6374:     my ($cmd, $tail, $client)   = @_;
 6375:     my $userinput               = "$cmd:$tail";
 6376: 
 6377:     my $reply;
 6378:     my $cdom = $tail;
 6379:     my (@codetitles,%cat_titles,%cat_order,@code_order);
 6380:     my $formatreply = &localenroll::possible_instcodes($cdom,
 6381:                                                        \@codetitles,
 6382:                                                        \%cat_titles,
 6383:                                                        \%cat_order,
 6384:                                                        \@code_order);
 6385:     if ($formatreply eq 'ok') {
 6386:         my $result = join('&',map {&escape($_);} (@codetitles)).':';
 6387:         $result .= join('&',map {&escape($_);} (@code_order)).':';
 6388:         foreach my $key (keys(%cat_titles)) {
 6389:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
 6390:         }
 6391:         $result =~ s/\&$//;
 6392:         $result .= ':';
 6393:         foreach my $key (keys(%cat_order)) {
 6394:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
 6395:         }
 6396:         $result =~ s/\&$//;
 6397:         &Reply($client,\$result,$userinput);
 6398:     } else {
 6399:         &Reply($client, "format_error\n", $userinput);
 6400:     }
 6401:     return 1;
 6402: }
 6403: &register_handler("autopossibleinstcodes",
 6404:                   \&get_possible_instcodes_handler,0,1,0);
 6405: 
 6406: sub get_institutional_user_rules {
 6407:     my ($cmd, $tail, $client)   = @_;
 6408:     my $userinput               = "$cmd:$tail";
 6409:     my $dom = &unescape($tail);
 6410:     my (%rules_hash,@rules_order);
 6411:     my $outcome;
 6412:     eval {
 6413:         local($SIG{__DIE__})='DEFAULT';
 6414:         $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
 6415:     };
 6416:     if (!$@) {
 6417:         if ($outcome eq 'ok') {
 6418:             my $result;
 6419:             foreach my $key (keys(%rules_hash)) {
 6420:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
 6421:             }
 6422:             $result =~ s/\&$//;
 6423:             $result .= ':';
 6424:             if (@rules_order > 0) {
 6425:                 foreach my $item (@rules_order) {
 6426:                     $result .= &escape($item).'&';
 6427:                 }
 6428:             }
 6429:             $result =~ s/\&$//;
 6430:             &Reply($client,\$result,$userinput);
 6431:         } else {
 6432:             &Reply($client,"error\n", $userinput);
 6433:         }
 6434:     } else {
 6435:         &Failure($client,"unknown_cmd\n",$userinput);
 6436:     }
 6437: }
 6438: &register_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
 6439: 
 6440: sub get_institutional_id_rules {
 6441:     my ($cmd, $tail, $client)   = @_;
 6442:     my $userinput               = "$cmd:$tail";
 6443:     my $dom = &unescape($tail);
 6444:     my (%rules_hash,@rules_order);
 6445:     my $outcome;
 6446:     eval {
 6447:         local($SIG{__DIE__})='DEFAULT';
 6448:         $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
 6449:     };
 6450:     if (!$@) {
 6451:         if ($outcome eq 'ok') {
 6452:             my $result;
 6453:             foreach my $key (keys(%rules_hash)) {
 6454:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
 6455:             }
 6456:             $result =~ s/\&$//;
 6457:             $result .= ':';
 6458:             if (@rules_order > 0) {
 6459:                 foreach my $item (@rules_order) {
 6460:                     $result .= &escape($item).'&';
 6461:                 }
 6462:             }
 6463:             $result =~ s/\&$//;
 6464:             &Reply($client,\$result,$userinput);
 6465:         } else {
 6466:             &Reply($client,"error\n", $userinput);
 6467:         }
 6468:     } else {
 6469:         &Failure($client,"unknown_cmd\n",$userinput);
 6470:     }
 6471: }
 6472: &register_handler("instidrules",\&get_institutional_id_rules,0,1,0);
 6473: 
 6474: sub get_institutional_selfcreate_rules {
 6475:     my ($cmd, $tail, $client)   = @_;
 6476:     my $userinput               = "$cmd:$tail";
 6477:     my $dom = &unescape($tail);
 6478:     my (%rules_hash,@rules_order);
 6479:     my $outcome;
 6480:     eval {
 6481:         local($SIG{__DIE__})='DEFAULT';
 6482:         $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
 6483:     };
 6484:     if (!$@) {
 6485:         if ($outcome eq 'ok') {
 6486:             my $result;
 6487:             foreach my $key (keys(%rules_hash)) {
 6488:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
 6489:             }
 6490:             $result =~ s/\&$//;
 6491:             $result .= ':';
 6492:             if (@rules_order > 0) {
 6493:                 foreach my $item (@rules_order) {
 6494:                     $result .= &escape($item).'&';
 6495:                 }
 6496:             }
 6497:             $result =~ s/\&$//;
 6498:             &Reply($client,\$result,$userinput);
 6499:         } else {
 6500:             &Reply($client,"error\n", $userinput);
 6501:         }
 6502:     } else {
 6503:         &Failure($client,"unknown_cmd\n",$userinput);
 6504:     }
 6505: }
 6506: &register_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
 6507: 
 6508: 
 6509: sub institutional_username_check {
 6510:     my ($cmd, $tail, $client)   = @_;
 6511:     my $userinput               = "$cmd:$tail";
 6512:     my %rulecheck;
 6513:     my $outcome;
 6514:     my ($udom,$uname,@rules) = split(/:/,$tail);
 6515:     $udom = &unescape($udom);
 6516:     $uname = &unescape($uname);
 6517:     @rules = map {&unescape($_);} (@rules);
 6518:     eval {
 6519:         local($SIG{__DIE__})='DEFAULT';
 6520:         $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
 6521:     };
 6522:     if (!$@) {
 6523:         if ($outcome eq 'ok') {
 6524:             my $result='';
 6525:             foreach my $key (keys(%rulecheck)) {
 6526:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
 6527:             }
 6528:             &Reply($client,\$result,$userinput);
 6529:         } else {
 6530:             &Reply($client,"error\n", $userinput);
 6531:         }
 6532:     } else {
 6533:         &Failure($client,"unknown_cmd\n",$userinput);
 6534:     }
 6535: }
 6536: &register_handler("instrulecheck",\&institutional_username_check,0,1,0);
 6537: 
 6538: sub institutional_id_check {
 6539:     my ($cmd, $tail, $client)   = @_;
 6540:     my $userinput               = "$cmd:$tail";
 6541:     my %rulecheck;
 6542:     my $outcome;
 6543:     my ($udom,$id,@rules) = split(/:/,$tail);
 6544:     $udom = &unescape($udom);
 6545:     $id = &unescape($id);
 6546:     @rules = map {&unescape($_);} (@rules);
 6547:     eval {
 6548:         local($SIG{__DIE__})='DEFAULT';
 6549:         $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
 6550:     };
 6551:     if (!$@) {
 6552:         if ($outcome eq 'ok') {
 6553:             my $result='';
 6554:             foreach my $key (keys(%rulecheck)) {
 6555:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
 6556:             }
 6557:             &Reply($client,\$result,$userinput);
 6558:         } else {
 6559:             &Reply($client,"error\n", $userinput);
 6560:         }
 6561:     } else {
 6562:         &Failure($client,"unknown_cmd\n",$userinput);
 6563:     }
 6564: }
 6565: &register_handler("instidrulecheck",\&institutional_id_check,0,1,0);
 6566: 
 6567: sub institutional_selfcreate_check {
 6568:     my ($cmd, $tail, $client)   = @_;
 6569:     my $userinput               = "$cmd:$tail";
 6570:     my %rulecheck;
 6571:     my $outcome;
 6572:     my ($udom,$email,@rules) = split(/:/,$tail);
 6573:     $udom = &unescape($udom);
 6574:     $email = &unescape($email);
 6575:     @rules = map {&unescape($_);} (@rules);
 6576:     eval {
 6577:         local($SIG{__DIE__})='DEFAULT';
 6578:         $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
 6579:     };
 6580:     if (!$@) {
 6581:         if ($outcome eq 'ok') {
 6582:             my $result='';
 6583:             foreach my $key (keys(%rulecheck)) {
 6584:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
 6585:             }
 6586:             &Reply($client,\$result,$userinput);
 6587:         } else {
 6588:             &Reply($client,"error\n", $userinput);
 6589:         }
 6590:     } else {
 6591:         &Failure($client,"unknown_cmd\n",$userinput);
 6592:     }
 6593: }
 6594: &register_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
 6595: 
 6596: # Get domain specific conditions for import of student photographs to a course
 6597: #
 6598: # Retrieves information from photo_permission subroutine in localenroll.
 6599: # Returns outcome (ok) if no processing errors, and whether course owner is 
 6600: # required to accept conditions of use (yes/no).
 6601: #
 6602: #    
 6603: sub photo_permission_handler {
 6604:     my ($cmd, $tail, $client)   = @_;
 6605:     my $userinput               = "$cmd:$tail";
 6606:     my $cdom = $tail;
 6607:     my ($perm_reqd,$conditions);
 6608:     my $outcome;
 6609:     eval {
 6610: 	local($SIG{__DIE__})='DEFAULT';
 6611: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
 6612: 						  \$conditions);
 6613:     };
 6614:     if (!$@) {
 6615: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
 6616: 	       $userinput);
 6617:     } else {
 6618: 	&Failure($client,"unknown_cmd\n",$userinput);
 6619:     }
 6620:     return 1;
 6621: }
 6622: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
 6623: 
 6624: #
 6625: # Checks if student photo is available for a user in the domain, in the user's
 6626: # directory (in /userfiles/internal/studentphoto.jpg).
 6627: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
 6628: # the student's photo.   
 6629: 
 6630: sub photo_check_handler {
 6631:     my ($cmd, $tail, $client)   = @_;
 6632:     my $userinput               = "$cmd:$tail";
 6633:     my ($udom,$uname,$pid) = split(/:/,$tail);
 6634:     $udom = &unescape($udom);
 6635:     $uname = &unescape($uname);
 6636:     $pid = &unescape($pid);
 6637:     my $path=&propath($udom,$uname).'/userfiles/internal/';
 6638:     if (!-e $path) {
 6639:         &mkpath($path);
 6640:     }
 6641:     my $response;
 6642:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
 6643:     $result .= ':'.$response;
 6644:     &Reply($client, &escape($result)."\n",$userinput);
 6645:     return 1;
 6646: }
 6647: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
 6648: 
 6649: #
 6650: # Retrieve information from localenroll about whether to provide a button     
 6651: # for users who have enbled import of student photos to initiate an 
 6652: # update of photo files for registered students. Also include 
 6653: # comment to display alongside button.  
 6654: 
 6655: sub photo_choice_handler {
 6656:     my ($cmd, $tail, $client) = @_;
 6657:     my $userinput             = "$cmd:$tail";
 6658:     my $cdom                  = &unescape($tail);
 6659:     my ($update,$comment);
 6660:     eval {
 6661: 	local($SIG{__DIE__})='DEFAULT';
 6662: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
 6663:     };
 6664:     if (!$@) {
 6665: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
 6666:     } else {
 6667: 	&Failure($client,"unknown_cmd\n",$userinput);
 6668:     }
 6669:     return 1;
 6670: }
 6671: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
 6672: 
 6673: #
 6674: # Gets a student's photo to exist (in the correct image type) in the user's 
 6675: # directory.
 6676: # Formal Parameters:
 6677: #    $cmd     - The command request that got us dispatched.
 6678: #    $tail    - A colon separated set of words that will be split into:
 6679: #               $domain - student's domain
 6680: #               $uname  - student username
 6681: #               $type   - image type desired
 6682: #    $client  - The socket open on the client.
 6683: # Returns:
 6684: #    1 - continue processing.
 6685: 
 6686: sub student_photo_handler {
 6687:     my ($cmd, $tail, $client) = @_;
 6688:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
 6689: 
 6690:     my $path=&propath($domain,$uname). '/userfiles/internal/';
 6691:     my $filename = 'studentphoto.'.$ext;
 6692:     if ($type eq 'thumbnail') {
 6693:         $filename = 'studentphoto_tn.'.$ext;
 6694:     }
 6695:     if (-e $path.$filename) {
 6696: 	&Reply($client,"ok\n","$cmd:$tail");
 6697: 	return 1;
 6698:     }
 6699:     &mkpath($path);
 6700:     my $file;
 6701:     if ($type eq 'thumbnail') {
 6702: 	eval {
 6703: 	    local($SIG{__DIE__})='DEFAULT';
 6704: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
 6705: 	};
 6706:     } else {
 6707:         $file=&localstudentphoto::fetch($domain,$uname);
 6708:     }
 6709:     if (!$file) {
 6710: 	&Failure($client,"unavailable\n","$cmd:$tail");
 6711: 	return 1;
 6712:     }
 6713:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
 6714:     if (-e $path.$filename) {
 6715: 	&Reply($client,"ok\n","$cmd:$tail");
 6716: 	return 1;
 6717:     }
 6718:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
 6719:     return 1;
 6720: }
 6721: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
 6722: 
 6723: sub inst_usertypes_handler {
 6724:     my ($cmd, $domain, $client) = @_;
 6725:     my $res;
 6726:     my $userinput = $cmd.":".$domain; # For logging purposes.
 6727:     my (%typeshash,@order,$result);
 6728:     eval {
 6729: 	local($SIG{__DIE__})='DEFAULT';
 6730: 	$result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
 6731:     };
 6732:     if ($result eq 'ok') {
 6733:         if (keys(%typeshash) > 0) {
 6734:             foreach my $key (keys(%typeshash)) {
 6735:                 $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
 6736:             }
 6737:         }
 6738:         $res=~s/\&$//;
 6739:         $res .= ':';
 6740:         if (@order > 0) {
 6741:             foreach my $item (@order) {
 6742:                 $res .= &escape($item).'&';
 6743:             }
 6744:         }
 6745:         $res=~s/\&$//;
 6746:     }
 6747:     &Reply($client, \$res, $userinput);
 6748:     return 1;
 6749: }
 6750: &register_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
 6751: 
 6752: # mkpath makes all directories for a file, expects an absolute path with a
 6753: # file or a trailing / if just a dir is passed
 6754: # returns 1 on success 0 on failure
 6755: sub mkpath {
 6756:     my ($file)=@_;
 6757:     my @parts=split(/\//,$file,-1);
 6758:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
 6759:     for (my $i=3;$i<= ($#parts-1);$i++) {
 6760: 	$now.='/'.$parts[$i]; 
 6761: 	if (!-e $now) {
 6762: 	    if  (!mkdir($now,0770)) { return 0; }
 6763: 	}
 6764:     }
 6765:     return 1;
 6766: }
 6767: 
 6768: #---------------------------------------------------------------
 6769: #
 6770: #   Getting, decoding and dispatching requests:
 6771: #
 6772: #
 6773: #   Get a Request:
 6774: #   Gets a Request message from the client.  The transaction
 6775: #   is defined as a 'line' of text.  We remove the new line
 6776: #   from the text line.  
 6777: #
 6778: sub get_request {
 6779:     my $input = <$client>;
 6780:     chomp($input);
 6781: 
 6782:     &Debug("get_request: Request = $input\n");
 6783: 
 6784:     &status('Processing '.$clientname.':'.$input);
 6785: 
 6786:     return $input;
 6787: }
 6788: #---------------------------------------------------------------
 6789: #
 6790: #  Process a request.  This sub should shrink as each action
 6791: #  gets farmed out into a separat sub that is registered 
 6792: #  with the dispatch hash.  
 6793: #
 6794: # Parameters:
 6795: #    user_input   - The request received from the client (lonc).
 6796: #
 6797: # Returns:
 6798: #    true to keep processing, false if caller should exit.
 6799: #
 6800: sub process_request {
 6801:     my ($userinput) = @_; # Easier for now to break style than to
 6802:                           # fix all the userinput -> user_input.
 6803:     my $wasenc    = 0;		# True if request was encrypted.
 6804: # ------------------------------------------------------------ See if encrypted
 6805:     # for command
 6806:     # sethost:<server>
 6807:     # <command>:<args>
 6808:     #   we just send it to the processor
 6809:     # for
 6810:     # sethost:<server>:<command>:<args>
 6811:     #  we do the implict set host and then do the command
 6812:     if ($userinput =~ /^sethost:/) {
 6813: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
 6814: 	if (defined($userinput)) {
 6815: 	    &sethost("$cmd:$newid");
 6816: 	} else {
 6817: 	    $userinput = "$cmd:$newid";
 6818: 	}
 6819:     }
 6820: 
 6821:     if ($userinput =~ /^enc/) {
 6822: 	$userinput = decipher($userinput);
 6823: 	$wasenc=1;
 6824: 	if(!$userinput) {	# Cipher not defined.
 6825: 	    &Failure($client, "error: Encrypted data without negotated key\n");
 6826: 	    return 0;
 6827: 	}
 6828:     }
 6829:     Debug("process_request: $userinput\n");
 6830:     
 6831:     #  
 6832:     #   The 'correct way' to add a command to lond is now to
 6833:     #   write a sub to execute it and Add it to the command dispatch
 6834:     #   hash via a call to register_handler..  The comments to that
 6835:     #   sub should give you enough to go on to show how to do this
 6836:     #   along with the examples that are building up as this code
 6837:     #   is getting refactored.   Until all branches of the
 6838:     #   if/elseif monster below have been factored out into
 6839:     #   separate procesor subs, if the dispatch hash is missing
 6840:     #   the command keyword, we will fall through to the remainder
 6841:     #   of the if/else chain below in order to keep this thing in 
 6842:     #   working order throughout the transmogrification.
 6843: 
 6844:     my ($command, $tail) = split(/:/, $userinput, 2);
 6845:     chomp($command);
 6846:     chomp($tail);
 6847:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
 6848:     $command =~ s/(\r)//;	# And this too for parameterless commands.
 6849:     if(!$tail) {
 6850: 	$tail ="";		# defined but blank.
 6851:     }
 6852: 
 6853:     &Debug("Command received: $command, encoded = $wasenc");
 6854: 
 6855:     if(defined $Dispatcher{$command}) {
 6856: 
 6857: 	my $dispatch_info = $Dispatcher{$command};
 6858: 	my $handler       = $$dispatch_info[0];
 6859: 	my $need_encode   = $$dispatch_info[1];
 6860: 	my $client_types  = $$dispatch_info[2];
 6861: 	Debug("Matched dispatch hash: mustencode: $need_encode "
 6862: 	      ."ClientType $client_types");
 6863:       
 6864: 	#  Validate the request:
 6865:       
 6866: 	my $ok = 1;
 6867: 	my $requesterprivs = 0;
 6868: 	if(&isClient()) {
 6869: 	    $requesterprivs |= $CLIENT_OK;
 6870: 	}
 6871: 	if(&isManager()) {
 6872: 	    $requesterprivs |= $MANAGER_OK;
 6873: 	}
 6874: 	if($need_encode && (!$wasenc)) {
 6875: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
 6876: 	    $ok = 0;
 6877: 	}
 6878: 	if(($client_types & $requesterprivs) == 0) {
 6879: 	    Debug("Client not privileged to do this operation");
 6880: 	    $ok = 0;
 6881: 	}
 6882:         if ($ok) {
 6883:             my $realcommand = $command;
 6884:             if ($command eq 'querysend') {
 6885:                 my ($query,$rest)=split(/\:/,$tail,2);
 6886:                 $query=~s/\n*$//g;
 6887:                 my @possqueries = 
 6888:                     qw(userlog courselog fetchenrollment institutionalphotos usersearch instdirsearch getinstuser getmultinstusers);
 6889:                 if (grep(/^\Q$query\E$/,@possqueries)) {
 6890:                     $command .= '_'.$query;
 6891:                 } elsif ($query eq 'prepare activity log') {
 6892:                     $command .= '_activitylog';
 6893:                 }
 6894:             }
 6895:             if (ref($trust{$command}) eq 'HASH') {
 6896:                 my $donechecks;
 6897:                 if ($trust{$command}{'anywhere'}) {
 6898:                    $donechecks = 1;
 6899:                 } elsif ($trust{$command}{'manageronly'}) {
 6900:                     unless (&isManager()) {
 6901:                         $ok = 0;
 6902:                     }
 6903:                     $donechecks = 1;
 6904:                 } elsif ($trust{$command}{'institutiononly'}) {
 6905:                     unless ($clientsameinst) {
 6906:                         $ok = 0;
 6907:                     }
 6908:                     $donechecks = 1;
 6909:                 } elsif ($clientsameinst) {
 6910:                     $donechecks = 1;
 6911:                 }
 6912:                 unless ($donechecks) {
 6913:                     foreach my $rule (keys(%{$trust{$command}})) {
 6914:                         next if ($rule eq 'remote');
 6915:                         if ($trust{$command}{$rule}) {
 6916:                             if ($clientprohibited{$rule}) {
 6917:                                 $ok = 0;
 6918:                             } else {
 6919:                                 $ok = 1;
 6920:                                 $donechecks = 1;
 6921:                                 last;
 6922:                             }
 6923:                         }
 6924:                     }
 6925:                 }
 6926:                 unless ($donechecks) {
 6927:                     if ($trust{$command}{'remote'}) {
 6928:                         if ($clientremoteok) {
 6929:                             $ok = 1;
 6930:                         } else {
 6931:                             $ok = 0;
 6932:                         } 
 6933:                     }
 6934:                 }
 6935:             }
 6936:             $command = $realcommand;
 6937:         }
 6938: 
 6939: 	if($ok) {
 6940: 	    Debug("Dispatching to handler $command $tail");
 6941: 	    my $keep_going = &$handler($command, $tail, $client);
 6942: 	    return $keep_going;
 6943: 	} else {
 6944: 	    Debug("Refusing to dispatch because client did not match requirements");
 6945: 	    Failure($client, "refused\n", $userinput);
 6946: 	    return 1;
 6947: 	}
 6948:     }
 6949: 
 6950:     print $client "unknown_cmd\n";
 6951: # -------------------------------------------------------------------- complete
 6952:     Debug("process_request - returning 1");
 6953:     return 1;
 6954: }
 6955: #
 6956: #   Decipher encoded traffic
 6957: #  Parameters:
 6958: #     input      - Encoded data.
 6959: #  Returns:
 6960: #     Decoded data or undef if encryption key was not yet negotiated.
 6961: #  Implicit input:
 6962: #     cipher  - This global holds the negotiated encryption key.
 6963: #
 6964: sub decipher {
 6965:     my ($input)  = @_;
 6966:     my $output = '';
 6967:     
 6968:     
 6969:     if($cipher) {
 6970: 	my($enc, $enclength, $encinput) = split(/:/, $input);
 6971: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
 6972: 	    $output .= 
 6973: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
 6974: 	}
 6975: 	return substr($output, 0, $enclength);
 6976:     } else {
 6977: 	return undef;
 6978:     }
 6979: }
 6980: 
 6981: #
 6982: #   Register a command processor.  This function is invoked to register a sub
 6983: #   to process a request.  Once registered, the ProcessRequest sub can automatically
 6984: #   dispatch requests to an appropriate sub, and do the top level validity checking
 6985: #   as well:
 6986: #    - Is the keyword recognized.
 6987: #    - Is the proper client type attempting the request.
 6988: #    - Is the request encrypted if it has to be.
 6989: #   Parameters:
 6990: #    $request_name         - Name of the request being registered.
 6991: #                           This is the command request that will match
 6992: #                           against the hash keywords to lookup the information
 6993: #                           associated with the dispatch information.
 6994: #    $procedure           - Reference to a sub to call to process the request.
 6995: #                           All subs get called as follows:
 6996: #                             Procedure($cmd, $tail, $replyfd, $key)
 6997: #                             $cmd    - the actual keyword that invoked us.
 6998: #                             $tail   - the tail of the request that invoked us.
 6999: #                             $replyfd- File descriptor connected to the client
 7000: #    $must_encode          - True if the request must be encoded to be good.
 7001: #    $client_ok            - True if it's ok for a client to request this.
 7002: #    $manager_ok           - True if it's ok for a manager to request this.
 7003: # Side effects:
 7004: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
 7005: #      - On failure, the program will die as it's a bad internal bug to try to 
 7006: #        register a duplicate command handler.
 7007: #
 7008: sub register_handler {
 7009:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
 7010: 
 7011:     #  Don't allow duplication#
 7012:    
 7013:     if (defined $Dispatcher{$request_name}) {
 7014: 	die "Attempting to define a duplicate request handler for $request_name\n";
 7015:     }
 7016:     #   Build the client type mask:
 7017:     
 7018:     my $client_type_mask = 0;
 7019:     if($client_ok) {
 7020: 	$client_type_mask  |= $CLIENT_OK;
 7021:     }
 7022:     if($manager_ok) {
 7023: 	$client_type_mask  |= $MANAGER_OK;
 7024:     }
 7025:    
 7026:     #  Enter the hash:
 7027:       
 7028:     my @entry = ($procedure, $must_encode, $client_type_mask);
 7029:    
 7030:     $Dispatcher{$request_name} = \@entry;
 7031:    
 7032: }
 7033: 
 7034: 
 7035: #------------------------------------------------------------------
 7036: 
 7037: 
 7038: 
 7039: 
 7040: #
 7041: #  Convert an error return code from lcpasswd to a string value.
 7042: #
 7043: sub lcpasswdstrerror {
 7044:     my $ErrorCode = shift;
 7045:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
 7046: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
 7047:     } else {
 7048: 	return $passwderrors[$ErrorCode];
 7049:     }
 7050: }
 7051: 
 7052: # grabs exception and records it to log before exiting
 7053: sub catchexception {
 7054:     my ($error)=@_;
 7055:     $SIG{'QUIT'}='DEFAULT';
 7056:     $SIG{__DIE__}='DEFAULT';
 7057:     &status("Catching exception");
 7058:     &logthis("<font color='red'>CRITICAL: "
 7059:      ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
 7060:      ."a crash with this error msg->[$error]</font>");
 7061:     &logthis('Famous last words: '.$status.' - '.$lastlog);
 7062:     if ($client) { print $client "error: $error\n"; }
 7063:     $server->close();
 7064:     die($error);
 7065: }
 7066: sub timeout {
 7067:     &status("Handling Timeout");
 7068:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
 7069:     &catchexception('Timeout');
 7070: }
 7071: # -------------------------------- Set signal handlers to record abnormal exits
 7072: 
 7073: 
 7074: $SIG{'QUIT'}=\&catchexception;
 7075: $SIG{__DIE__}=\&catchexception;
 7076: 
 7077: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
 7078: &status("Read loncapa.conf and loncapa_apache.conf");
 7079: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
 7080: %perlvar=%{$perlvarref};
 7081: undef $perlvarref;
 7082: 
 7083: # ----------------------------- Make sure this process is running from user=www
 7084: my $wwwid=getpwnam('www');
 7085: if ($wwwid!=$<) {
 7086:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
 7087:    my $subj="LON: $currenthostid User ID mismatch";
 7088:    system("echo 'User ID mismatch.  lond must be run as user www.' |".
 7089:           " mail -s '$subj' $emailto > /dev/null");
 7090:    exit 1;
 7091: }
 7092: 
 7093: # --------------------------------------------- Check if other instance running
 7094: 
 7095: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
 7096: 
 7097: if (-e $pidfile) {
 7098:    my $lfh=IO::File->new("$pidfile");
 7099:    my $pide=<$lfh>;
 7100:    chomp($pide);
 7101:    if (kill 0 => $pide) { die "already running"; }
 7102: }
 7103: 
 7104: # ------------------------------------------------------------- Read hosts file
 7105: 
 7106: 
 7107: 
 7108: # establish SERVER socket, bind and listen.
 7109: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
 7110:                                 Type      => SOCK_STREAM,
 7111:                                 Proto     => 'tcp',
 7112:                                 ReuseAddr     => 1,
 7113:                                 Listen    => 10 )
 7114:   or die "making socket: $@\n";
 7115: 
 7116: # --------------------------------------------------------- Do global variables
 7117: 
 7118: # global variables
 7119: 
 7120: my %children               = ();       # keys are current child process IDs
 7121: 
 7122: sub REAPER {                        # takes care of dead children
 7123:     $SIG{CHLD} = \&REAPER;
 7124:     &status("Handling child death");
 7125:     my $pid;
 7126:     do {
 7127: 	$pid = waitpid(-1,&WNOHANG());
 7128: 	if (defined($children{$pid})) {
 7129: 	    &logthis("Child $pid died");
 7130: 	    delete($children{$pid});
 7131: 	} elsif ($pid > 0) {
 7132: 	    &logthis("Unknown Child $pid died");
 7133: 	}
 7134:     } while ( $pid > 0 );
 7135:     foreach my $child (keys(%children)) {
 7136: 	$pid = waitpid($child,&WNOHANG());
 7137: 	if ($pid > 0) {
 7138: 	    &logthis("Child $child - $pid looks like we missed it's death");
 7139: 	    delete($children{$pid});
 7140: 	}
 7141:     }
 7142:     &status("Finished Handling child death");
 7143: }
 7144: 
 7145: sub HUNTSMAN {                      # signal handler for SIGINT
 7146:     &status("Killing children (INT)");
 7147:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
 7148:     kill 'INT' => keys %children;
 7149:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
 7150:     my $execdir=$perlvar{'lonDaemons'};
 7151:     unlink("$execdir/logs/lond.pid");
 7152:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
 7153:     &status("Done killing children");
 7154:     exit;                           # clean up with dignity
 7155: }
 7156: 
 7157: sub HUPSMAN {                      # signal handler for SIGHUP
 7158:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
 7159:     &status("Killing children for restart (HUP)");
 7160:     kill 'INT' => keys %children;
 7161:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
 7162:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
 7163:     my $execdir=$perlvar{'lonDaemons'};
 7164:     unlink("$execdir/logs/lond.pid");
 7165:     &status("Restarting self (HUP)");
 7166:     exec("$execdir/lond");         # here we go again
 7167: }
 7168: 
 7169: #
 7170: #  Reload the Apache daemon's state.
 7171: #  This is done by invoking /home/httpd/perl/apachereload
 7172: #  a setuid perl script that can be root for us to do this job.
 7173: #
 7174: sub ReloadApache {
 7175: # --------------------------- Handle case of another apachereload process (locking)
 7176:     if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
 7177:         my $execdir = $perlvar{'lonDaemons'};
 7178:         my $script  = $execdir."/apachereload";
 7179:         system($script);
 7180:         unlink('/tmp/lock_apachereload'); #  Remove the lock file.
 7181:     }
 7182: }
 7183: 
 7184: #
 7185: #   Called in response to a USR2 signal.
 7186: #   - Reread hosts.tab
 7187: #   - All children connected to hosts that were removed from hosts.tab
 7188: #     are killed via SIGINT
 7189: #   - All children connected to previously existing hosts are sent SIGUSR1
 7190: #   - Our internal hosts hash is updated to reflect the new contents of
 7191: #     hosts.tab causing connections from hosts added to hosts.tab to
 7192: #     now be honored.
 7193: #
 7194: sub UpdateHosts {
 7195:     &status("Reload hosts.tab");
 7196:     logthis('<font color="blue"> Updating connections </font>');
 7197:     #
 7198:     #  The %children hash has the set of IP's we currently have children
 7199:     #  on.  These need to be matched against records in the hosts.tab
 7200:     #  Any ip's no longer in the table get killed off they correspond to
 7201:     #  either dropped or changed hosts.  Note that the re-read of the table
 7202:     #  will take care of new and changed hosts as connections come into being.
 7203: 
 7204:     &Apache::lonnet::reset_hosts_info();
 7205:     my %active;
 7206: 
 7207:     foreach my $child (keys(%children)) {
 7208: 	my $childip = $children{$child};
 7209: 	if ($childip ne '127.0.0.1'
 7210: 	    && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
 7211: 	    logthis('<font color="blue"> UpdateHosts killing child '
 7212: 		    ." $child for ip $childip </font>");
 7213: 	    kill('INT', $child);
 7214: 	} else {
 7215:             $active{$child} = $childip;
 7216: 	    logthis('<font color="green"> keeping child for ip '
 7217: 		    ." $childip (pid=$child) </font>");
 7218: 	}
 7219:     }
 7220: 
 7221:     my %oldconf = %secureconf;
 7222:     my %connchange;
 7223:     if (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
 7224:         logthis('<font color="blue"> Reloaded SSL connection rules and cleared CRL checking history </font>');
 7225:     } else {
 7226:         logthis('<font color="yellow"> Failed to reload SSL connection rules and clear CRL checking history </font>');
 7227:     }
 7228:     if ((ref($oldconf{'connfrom'}) eq 'HASH') && (ref($secureconf{'connfrom'}) eq 'HASH')) {
 7229:         foreach my $type ('dom','intdom','other') {
 7230:             if ((($oldconf{'connfrom'}{$type} eq 'no') && ($secureconf{'connfrom'}{$type} eq 'req')) ||
 7231:                 (($oldconf{'connfrom'}{$type} eq 'req') && ($secureconf{'connfrom'}{$type} eq 'no'))) {
 7232:                 $connchange{$type} = 1;
 7233:             }
 7234:         }
 7235:     }
 7236:     if (keys(%connchange)) {
 7237:         foreach my $child (keys(%active)) {
 7238:             my $childip = $active{$child};
 7239:             if ($childip ne '127.0.0.1') {
 7240:                 my $childhostname  = gethostbyaddr(Socket::inet_aton($childip),AF_INET);
 7241:                 if ($childhostname ne '') {
 7242:                     my $childlonhost = &Apache::lonnet::get_server_homeID($childhostname);
 7243:                     my ($samedom,$sameinst) = &set_client_info($childlonhost);
 7244:                     if ($samedom) {
 7245:                         if ($connchange{'dom'}) {
 7246:                             logthis('<font color="blue"> UpdateHosts killing child '
 7247:                                    ." $child for ip $childip </font>");
 7248:                             kill('INT', $child);
 7249:                         }
 7250:                     } elsif ($sameinst) {
 7251:                         if ($connchange{'intdom'}) {
 7252:                             logthis('<font color="blue"> UpdateHosts killing child '
 7253:                                    ." $child for ip $childip </font>");
 7254:                            kill('INT', $child);
 7255:                         }
 7256:                     } else {
 7257:                         if ($connchange{'other'}) {
 7258:                             logthis('<font color="blue"> UpdateHosts killing child '
 7259:                                    ." $child for ip $childip </font>");
 7260:                             kill('INT', $child);
 7261:                         }
 7262:                     }
 7263:                 }
 7264:             }
 7265:         }
 7266:     }
 7267:     ReloadApache;
 7268:     &status("Finished reloading hosts.tab");
 7269: }
 7270: 
 7271: sub checkchildren {
 7272:     &status("Checking on the children (sending signals)");
 7273:     &initnewstatus();
 7274:     &logstatus();
 7275:     &logthis('Going to check on the children');
 7276:     my $docdir=$perlvar{'lonDocRoot'};
 7277:     foreach (sort keys %children) {
 7278: 	#sleep 1;
 7279:         unless (kill 'USR1' => $_) {
 7280: 	    &logthis ('Child '.$_.' is dead');
 7281:             &logstatus($$.' is dead');
 7282: 	    delete($children{$_});
 7283:         } 
 7284:     }
 7285:     sleep 5;
 7286:     $SIG{ALRM} = sub { Debug("timeout"); 
 7287: 		       die "timeout";  };
 7288:     $SIG{__DIE__} = 'DEFAULT';
 7289:     &status("Checking on the children (waiting for reports)");
 7290:     foreach (sort keys %children) {
 7291:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
 7292:           eval {
 7293:             alarm(300);
 7294: 	    &logthis('Child '.$_.' did not respond');
 7295: 	    kill 9 => $_;
 7296: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
 7297: 	    #$subj="LON: $currenthostid killed lond process $_";
 7298: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
 7299: 	    #$execdir=$perlvar{'lonDaemons'};
 7300: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
 7301: 	    delete($children{$_});
 7302: 	    alarm(0);
 7303: 	  }
 7304:         }
 7305:     }
 7306:     $SIG{ALRM} = 'DEFAULT';
 7307:     $SIG{__DIE__} = \&catchexception;
 7308:     &status("Finished checking children");
 7309:     &logthis('Finished Checking children');
 7310: }
 7311: 
 7312: # --------------------------------------------------------------------- Logging
 7313: 
 7314: sub logthis {
 7315:     my $message=shift;
 7316:     my $execdir=$perlvar{'lonDaemons'};
 7317:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
 7318:     my $now=time;
 7319:     my $local=localtime($now);
 7320:     $lastlog=$local.': '.$message;
 7321:     print $fh "$local ($$): $message\n";
 7322: }
 7323: 
 7324: # ------------------------- Conditional log if $DEBUG true.
 7325: sub Debug {
 7326:     my $message = shift;
 7327:     if($DEBUG) {
 7328: 	&logthis($message);
 7329:     }
 7330: }
 7331: 
 7332: #
 7333: #   Sub to do replies to client.. this gives a hook for some
 7334: #   debug tracing too:
 7335: #  Parameters:
 7336: #     fd      - File open on client.
 7337: #     reply   - Text to send to client.
 7338: #     request - Original request from client.
 7339: #
 7340: #NOTE $reply must be terminated by exactly *one* \n. If $reply is a reference
 7341: #this is done automatically ($$reply must not contain any \n in this case). 
 7342: #If $reply is a string the caller has to ensure this.
 7343: sub Reply {
 7344:     my ($fd, $reply, $request) = @_;
 7345:     if (ref($reply)) {
 7346: 	print $fd $$reply;
 7347: 	print $fd "\n";
 7348: 	if ($DEBUG) { Debug("Request was $request  Reply was $$reply"); }
 7349:     } else {
 7350: 	print $fd $reply;
 7351: 	if ($DEBUG) { Debug("Request was $request  Reply was $reply"); }
 7352:     }
 7353:     $Transactions++;
 7354: }
 7355: 
 7356: 
 7357: #
 7358: #    Sub to report a failure.
 7359: #    This function:
 7360: #     -   Increments the failure statistic counters.
 7361: #     -   Invokes Reply to send the error message to the client.
 7362: # Parameters:
 7363: #    fd       - File descriptor open on the client
 7364: #    reply    - Reply text to emit.
 7365: #    request  - The original request message (used by Reply
 7366: #               to debug if that's enabled.
 7367: # Implicit outputs:
 7368: #    $Failures- The number of failures is incremented.
 7369: #    Reply (invoked here) sends a message to the 
 7370: #    client:
 7371: #
 7372: sub Failure {
 7373:     my $fd      = shift;
 7374:     my $reply   = shift;
 7375:     my $request = shift;
 7376:    
 7377:     $Failures++;
 7378:     Reply($fd, $reply, $request);      # That's simple eh?
 7379: }
 7380: # ------------------------------------------------------------------ Log status
 7381: 
 7382: sub logstatus {
 7383:     &status("Doing logging");
 7384:     my $docdir=$perlvar{'lonDocRoot'};
 7385:     {
 7386: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
 7387:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
 7388:         $fh->close();
 7389:     }
 7390:     &status("Finished $$.txt");
 7391:     {
 7392: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
 7393: 	flock(LOG,LOCK_EX);
 7394: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
 7395: 	    .$status."\t".$lastlog."\t $keymode\n";
 7396: 	flock(LOG,LOCK_UN);
 7397: 	close(LOG);
 7398:     }
 7399:     &status("Finished logging");
 7400: }
 7401: 
 7402: sub initnewstatus {
 7403:     my $docdir=$perlvar{'lonDocRoot'};
 7404:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
 7405:     my $now=time();
 7406:     my $local=localtime($now);
 7407:     print $fh "LOND status $local - parent $$\n\n";
 7408:     opendir(DIR,"$docdir/lon-status/londchld");
 7409:     while (my $filename=readdir(DIR)) {
 7410:         unlink("$docdir/lon-status/londchld/$filename");
 7411:     }
 7412:     closedir(DIR);
 7413: }
 7414: 
 7415: # -------------------------------------------------------------- Status setting
 7416: 
 7417: sub status {
 7418:     my $what=shift;
 7419:     my $now=time;
 7420:     my $local=localtime($now);
 7421:     $status=$local.': '.$what;
 7422:     $0='lond: '.$what.' '.$local;
 7423: }
 7424: 
 7425: # -------------------------------------------------------------- Talk to lonsql
 7426: 
 7427: sub sql_reply {
 7428:     my ($cmd)=@_;
 7429:     my $answer=&sub_sql_reply($cmd);
 7430:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
 7431:     return $answer;
 7432: }
 7433: 
 7434: sub sub_sql_reply {
 7435:     my ($cmd)=@_;
 7436:     my $unixsock="mysqlsock";
 7437:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
 7438:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
 7439:                                       Type    => SOCK_STREAM,
 7440:                                       Timeout => 10)
 7441:        or return "con_lost";
 7442:     print $sclient "$cmd:$currentdomainid\n";
 7443:     my $answer=<$sclient>;
 7444:     chomp($answer);
 7445:     if (!$answer) { $answer="con_lost"; }
 7446:     return $answer;
 7447: }
 7448: 
 7449: # --------------------------------------- Is this the home server of an author?
 7450: 
 7451: sub ishome {
 7452:     my $author=shift;
 7453:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 7454:     my ($udom,$uname)=split(/\//,$author);
 7455:     my $proname=propath($udom,$uname);
 7456:     if (-e $proname) {
 7457: 	return 'owner';
 7458:     } else {
 7459:         return 'not_owner';
 7460:     }
 7461: }
 7462: 
 7463: # ======================================================= Continue main program
 7464: # ---------------------------------------------------- Fork once and dissociate
 7465: 
 7466: my $fpid=fork;
 7467: exit if $fpid;
 7468: die "Couldn't fork: $!" unless defined ($fpid);
 7469: 
 7470: POSIX::setsid() or die "Can't start new session: $!";
 7471: 
 7472: # ------------------------------------------------------- Write our PID on disk
 7473: 
 7474: my $execdir=$perlvar{'lonDaemons'};
 7475: open (PIDSAVE,">$execdir/logs/lond.pid");
 7476: print PIDSAVE "$$\n";
 7477: close(PIDSAVE);
 7478: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
 7479: &status('Starting');
 7480: 
 7481: 
 7482: 
 7483: # ----------------------------------------------------- Install signal handlers
 7484: 
 7485: 
 7486: $SIG{CHLD} = \&REAPER;
 7487: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 7488: $SIG{HUP}  = \&HUPSMAN;
 7489: $SIG{USR1} = \&checkchildren;
 7490: $SIG{USR2} = \&UpdateHosts;
 7491: 
 7492: #  Read the host hashes:
 7493: &Apache::lonnet::load_hosts_tab();
 7494: my %iphost = &Apache::lonnet::get_iphost(1);
 7495: 
 7496: $dist=`$perlvar{'lonDaemons'}/distprobe`;
 7497: 
 7498: my $arch = `uname -i`;
 7499: chomp($arch);
 7500: if ($arch eq 'unknown') {
 7501:     $arch = `uname -m`;
 7502:     chomp($arch);
 7503: }
 7504: 
 7505: unless (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
 7506:     &logthis('<font color="blue">No connectionrules table. Will fallback to loncapa.conf</font>');
 7507: }
 7508: 
 7509: # --------------------------------------------------------------
 7510: #   Accept connections.  When a connection comes in, it is validated
 7511: #   and if good, a child process is created to process transactions
 7512: #   along the connection.
 7513: 
 7514: while (1) {
 7515:     &status('Starting accept');
 7516:     $client = $server->accept() or next;
 7517:     &status('Accepted '.$client.' off to spawn');
 7518:     make_new_child($client);
 7519:     &status('Finished spawning');
 7520: }
 7521: 
 7522: sub make_new_child {
 7523:     my $pid;
 7524: #    my $cipher;     # Now global
 7525:     my $sigset;
 7526: 
 7527:     $client = shift;
 7528:     &status('Starting new child '.$client);
 7529:     &logthis('<font color="green"> Attempting to start child ('.$client.
 7530: 	     ")</font>");    
 7531:     # block signal for fork
 7532:     $sigset = POSIX::SigSet->new(SIGINT);
 7533:     sigprocmask(SIG_BLOCK, $sigset)
 7534:         or die "Can't block SIGINT for fork: $!\n";
 7535: 
 7536:     die "fork: $!" unless defined ($pid = fork);
 7537: 
 7538:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
 7539: 	                               # connection liveness.
 7540: 
 7541:     #
 7542:     #  Figure out who we're talking to so we can record the peer in 
 7543:     #  the pid hash.
 7544:     #
 7545:     my $caller = getpeername($client);
 7546:     my ($port,$iaddr);
 7547:     if (defined($caller) && length($caller) > 0) {
 7548: 	($port,$iaddr)=unpack_sockaddr_in($caller);
 7549:     } else {
 7550: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
 7551:     }
 7552:     if (defined($iaddr)) {
 7553: 	$clientip  = inet_ntoa($iaddr);
 7554: 	Debug("Connected with $clientip");
 7555:     } else {
 7556: 	&logthis("Unable to determine clientip");
 7557: 	$clientip='Unavailable';
 7558:     }
 7559:     
 7560:     if ($pid) {
 7561:         # Parent records the child's birth and returns.
 7562:         sigprocmask(SIG_UNBLOCK, $sigset)
 7563:             or die "Can't unblock SIGINT for fork: $!\n";
 7564:         $children{$pid} = $clientip;
 7565:         &status('Started child '.$pid);
 7566: 	close($client);
 7567:         return;
 7568:     } else {
 7569:         # Child can *not* return from this subroutine.
 7570:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
 7571:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
 7572:                                 #don't get intercepted
 7573:         $SIG{USR1}= \&logstatus;
 7574:         $SIG{ALRM}= \&timeout;
 7575: 	#
 7576: 	# Block sigpipe as it gets thrownon socket disconnect and we want to 
 7577: 	# deal with that as a read faiure instead.
 7578: 	#
 7579: 	my $blockset = POSIX::SigSet->new(SIGPIPE);
 7580: 	sigprocmask(SIG_BLOCK, $blockset);
 7581: 
 7582:         $lastlog='Forked ';
 7583:         $status='Forked';
 7584: 
 7585:         # unblock signals
 7586:         sigprocmask(SIG_UNBLOCK, $sigset)
 7587:             or die "Can't unblock SIGINT for fork: $!\n";
 7588: 
 7589: #        my $tmpsnum=0;            # Now global
 7590: #---------------------------------------------------- kerberos 5 initialization
 7591:         &Authen::Krb5::init_context();
 7592: 
 7593:         my $no_ets;
 7594:         if ($dist =~ /^(?:centos|rhes|scientific|oracle)(\d+)$/) {
 7595:             if ($1 >= 7) {
 7596:                 $no_ets = 1;
 7597:             }
 7598:         } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
 7599:             if (($1 eq '9.3') || ($1 >= 12.2)) {
 7600:                 $no_ets = 1; 
 7601:             }
 7602:         } elsif ($dist =~ /^sles(\d+)$/) {
 7603:             if ($1 > 11) {
 7604:                 $no_ets = 1;
 7605:             }
 7606:         } elsif ($dist =~ /^fedora(\d+)$/) {
 7607:             if ($1 < 7) {
 7608:                 $no_ets = 1;
 7609:             }
 7610:         }
 7611:         unless ($no_ets) {
 7612: 	    &Authen::Krb5::init_ets();
 7613: 	}
 7614: 
 7615: 	&status('Accepted connection');
 7616: # =============================================================================
 7617:             # do something with the connection
 7618: # -----------------------------------------------------------------------------
 7619: 	# see if we know client and 'check' for spoof IP by ineffective challenge
 7620: 
 7621: 	my $outsideip=$clientip;
 7622: 	if ($clientip eq '127.0.0.1') {
 7623: 	    $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
 7624: 	}
 7625: 	&ReadManagerTable();
 7626: 	my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
 7627: 	my $ismanager=($managers{$outsideip}    ne undef);
 7628: 	$clientname  = "[unknown]";
 7629: 	if($clientrec) {	# Establish client type.
 7630: 	    $ConnectionType = "client";
 7631: 	    $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
 7632: 	    if($ismanager) {
 7633: 		$ConnectionType = "both";
 7634: 	    }
 7635: 	} else {
 7636: 	    $ConnectionType = "manager";
 7637: 	    $clientname = $managers{$outsideip};
 7638: 	}
 7639: 	my $clientok;
 7640: 
 7641: 	if ($clientrec || $ismanager) {
 7642: 	    &status("Waiting for init from $clientip $clientname");
 7643: 	    &logthis('<font color="yellow">INFO: Connection, '.
 7644: 		     $clientip.
 7645: 		  " ($clientname) connection type = $ConnectionType </font>" );
 7646: 	    &status("Connecting $clientip  ($clientname))"); 
 7647: 	    my $remotereq=<$client>;
 7648: 	    chomp($remotereq);
 7649: 	    Debug("Got init: $remotereq");
 7650: 
 7651: 	    if ($remotereq =~ /^init/) {
 7652: 		&sethost("sethost:$perlvar{'lonHostID'}");
 7653: 		#
 7654: 		#  If the remote is attempting a local init... give that a try:
 7655: 		#
 7656: 		(my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
 7657:         # For LON-CAPA 2.9, the  client session will have sent its LON-CAPA
 7658:         # version when initiating the connection. For LON-CAPA 2.8 and older,
 7659:         # the version is retrieved from the global %loncaparevs in lonnet.pm.            
 7660:         # $clientversion contains path to keyfile if $inittype eq 'local'
 7661:         # it's overridden below in this case
 7662:         $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
 7663: 
 7664: 		# If the connection type is ssl, but I didn't get my
 7665: 		# certificate files yet, then I'll drop  back to 
 7666: 		# insecure (if allowed).
 7667: 
 7668:                 if ($inittype eq "ssl") {
 7669:                     my $context;
 7670:                     if ($clientsamedom) {
 7671:                         $context = 'dom';
 7672:                         if ($secureconf{'connfrom'}{'dom'} eq 'no') {
 7673:                             $inittype = "";
 7674:                         }
 7675:                     } elsif ($clientsameinst) {
 7676:                         $context = 'intdom';
 7677:                         if ($secureconf{'connfrom'}{'intdom'} eq 'no') {
 7678:                             $inittype = "";
 7679:                         }
 7680:                     } else {
 7681:                         $context = 'other';
 7682:                         if ($secureconf{'connfrom'}{'other'} eq 'no') {
 7683:                             $inittype = "";
 7684:                         }
 7685:                     }
 7686:                     if ($inittype eq '') {
 7687:                         &logthis("<font color=\"blue\"> Domain config set "
 7688:                                 ."to no ssl for $clientname (context: $context)"
 7689:                                 ." -- trying insecure auth</font>");
 7690:                     }
 7691:                 }
 7692: 
 7693: 		if($inittype eq "ssl") {
 7694: 		    my ($ca, $cert) = lonssl::CertificateFile;
 7695: 		    my $kfile       = lonssl::KeyFile;
 7696: 		    if((!$ca)   || 
 7697: 		       (!$cert) || 
 7698: 		       (!$kfile)) {
 7699: 			$inittype = ""; # This forces insecure attempt.
 7700: 			&logthis("<font color=\"blue\"> Certificates not "
 7701: 				 ."installed -- trying insecure auth</font>");
 7702: 		    } else {	# SSL certificates are in place so
 7703: 		    }		# Leave the inittype alone.
 7704: 		}
 7705: 
 7706: 		if($inittype eq "local") {
 7707:                     $clientversion = $perlvar{'lonVersion'};
 7708: 		    my $key = LocalConnection($client, $remotereq);
 7709: 		    if($key) {
 7710: 			Debug("Got local key $key");
 7711: 			$clientok     = 1;
 7712: 			my $cipherkey = pack("H32", $key);
 7713: 			$cipher       = new IDEA($cipherkey);
 7714: 			print $client "ok:local\n";
 7715: 			&logthis('<font color="green">'
 7716: 				 . "Successful local authentication </font>");
 7717: 			$keymode = "local"
 7718: 		    } else {
 7719: 			Debug("Failed to get local key");
 7720: 			$clientok = 0;
 7721: 			shutdown($client, 3);
 7722: 			close $client;
 7723: 		    }
 7724: 		} elsif ($inittype eq "ssl") {
 7725: 		    my $key = SSLConnection($client,$clientname);
 7726: 		    if ($key) {
 7727: 			$clientok = 1;
 7728: 			my $cipherkey = pack("H32", $key);
 7729: 			$cipher       = new IDEA($cipherkey);
 7730: 			&logthis('<font color="green">'
 7731: 				 ."Successfull ssl authentication with $clientname </font>");
 7732: 			$keymode = "ssl";
 7733: 	     
 7734: 		    } else {
 7735: 			$clientok = 0;
 7736: 			close $client;
 7737: 		    }
 7738: 	   
 7739: 		} else {
 7740: 		    my $ok = InsecureConnection($client);
 7741: 		    if($ok) {
 7742: 			$clientok = 1;
 7743: 			&logthis('<font color="green">'
 7744: 				 ."Successful insecure authentication with $clientname </font>");
 7745: 			print $client "ok\n";
 7746: 			$keymode = "insecure";
 7747: 		    } else {
 7748: 			&logthis('<font color="yellow">'
 7749: 				  ."Attempted insecure connection disallowed </font>");
 7750: 			close $client;
 7751: 			$clientok = 0;
 7752: 		    }
 7753: 		}
 7754: 	    } else {
 7755: 		&logthis(
 7756: 			 "<font color='blue'>WARNING: "
 7757: 			 ."$clientip failed to initialize: >$remotereq< </font>");
 7758: 		&status('No init '.$clientip);
 7759: 	    }
 7760: 	} else {
 7761: 	    &logthis(
 7762: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
 7763: 	    &status('Hung up on '.$clientip);
 7764: 	}
 7765:  
 7766: 	if ($clientok) {
 7767: # ---------------- New known client connecting, could mean machine online again
 7768: 	    if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip 
 7769: 		&& $clientip ne '127.0.0.1') {
 7770: 		&Apache::lonnet::reconlonc($clientname);
 7771: 	    }
 7772: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
 7773: 	    &status('Will listen to '.$clientname);
 7774: # ------------------------------------------------------------ Process requests
 7775: 	    my $keep_going = 1;
 7776: 	    my $user_input;
 7777: 
 7778: 	    while(($user_input = get_request) && $keep_going) {
 7779: 		alarm(120);
 7780: 		Debug("Main: Got $user_input\n");
 7781: 		$keep_going = &process_request($user_input);
 7782: 		alarm(0);
 7783: 		&status('Listening to '.$clientname." ($keymode)");	   
 7784: 	    }
 7785: 
 7786: # --------------------------------------------- client unknown or fishy, refuse
 7787: 	}  else {
 7788: 	    print $client "refused\n";
 7789: 	    $client->close();
 7790: 	    &logthis("<font color='blue'>WARNING: "
 7791: 		     ."Rejected client $clientip, closing connection</font>");
 7792: 	}
 7793:     }
 7794:     
 7795: # =============================================================================
 7796:     
 7797:     &logthis("<font color='red'>CRITICAL: "
 7798: 	     ."Disconnect from $clientip ($clientname)</font>");    
 7799:     
 7800:     
 7801:     # this exit is VERY important, otherwise the child will become
 7802:     # a producer of more and more children, forking yourself into
 7803:     # process death.
 7804:     exit;
 7805:     
 7806: }
 7807: 
 7808: #
 7809: #  Used to determine if a particular client is from the same domain
 7810: #  as the current server, or from the same internet domain, and
 7811: #  also if the client can host sessions for the domain's users.
 7812: #  A hash is populated with keys set to commands sent by the client
 7813: #  which may not be executed for this domain.
 7814: #
 7815: #  Optional input -- the client to check for domain and internet domain.
 7816: #  If not specified, defaults to the package variable: $clientname
 7817: #
 7818: #  If called in array context will not set package variables, but will
 7819: #  instead return an array of two values - (a) true if client is in the
 7820: #  same domain as the server, and (b) true if client is in the same 
 7821: #  internet domain.
 7822: #
 7823: #  If called in scalar context, sets package variables for current client:
 7824: #
 7825: #  $clienthomedom    - LonCAPA domain of homeID for client.
 7826: #  $clientsamedom    - LonCAPA domain same for this host and client.
 7827: #  $clientintdom     - LonCAPA "internet domain" for client.
 7828: #  $clientsameinst   - LonCAPA "internet domain" same for this host & client.
 7829: #  $clientremoteok   - If current domain permits hosting on this client: 1
 7830: #  %clientprohibited - Commands prohibited for domain's users for this client.
 7831: #
 7832: #  if the host and client have the same "internet domain", then the value
 7833: #  of $clientremoteok is not used, and no commands are prohibited.
 7834: #
 7835: #  returns 1 to indicate package variables have been set for current client.
 7836: #
 7837: 
 7838: sub set_client_info {
 7839:     my ($lonhost) = @_;
 7840:     $lonhost ||= $clientname;
 7841:     my $clienthost = &Apache::lonnet::hostname($lonhost);
 7842:     my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
 7843:     my $homedom = &Apache::lonnet::host_domain($clientserverhomeID);
 7844:     my $samedom = 0;
 7845:     if ($perlvar{'lonDefDomain'} eq $homedom) {
 7846:         $samedom = 1;
 7847:     }
 7848:     my $intdom = &Apache::lonnet::internet_dom($clientserverhomeID);
 7849:     my $sameinst = 0;
 7850:     if ($intdom ne '') {
 7851:         my $internet_names = &Apache::lonnet::get_internet_names($currenthostid);
 7852:         if (ref($internet_names) eq 'ARRAY') {
 7853:             if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 7854:                 $sameinst = 1;
 7855:             }
 7856:         }
 7857:     }
 7858:     if (wantarray) {
 7859:         return ($samedom,$sameinst);
 7860:     } else {
 7861:         $clienthomedom = $homedom;
 7862:         $clientsamedom = $samedom;
 7863:         $clientintdom = $intdom;
 7864:         $clientsameinst = $sameinst;
 7865:         if ($clientsameinst) {
 7866:             undef($clientremoteok);
 7867:             undef(%clientprohibited);
 7868:         } else {
 7869:             $clientremoteok = &get_remote_hostable($currentdomainid);
 7870:             %clientprohibited = &get_prohibited($currentdomainid);
 7871:         }
 7872:         return 1;
 7873:     }
 7874: }
 7875: 
 7876: #
 7877: #   Determine if a user is an author for the indicated domain.
 7878: #
 7879: # Parameters:
 7880: #    domain          - domain to check in .
 7881: #    user            - Name of user to check.
 7882: #
 7883: # Return:
 7884: #     1             - User is an author for domain.
 7885: #     0             - User is not an author for domain.
 7886: sub is_author {
 7887:     my ($domain, $user) = @_;
 7888: 
 7889:     &Debug("is_author: $user @ $domain");
 7890: 
 7891:     my $hashref = &tie_user_hash($domain, $user, "roles",
 7892: 				 &GDBM_READER());
 7893: 
 7894:     #  Author role should show up as a key /domain/_au
 7895: 
 7896:     my $value;
 7897:     if ($hashref) {
 7898: 
 7899: 	my $key    = "/$domain/_au";
 7900: 	if (defined($hashref)) {
 7901: 	    $value = $hashref->{$key};
 7902: 	    if(!untie_user_hash($hashref)) {
 7903: 		return 'error: ' .  ($!+0)." untie (GDBM) Failed";
 7904: 	    }
 7905: 	}
 7906: 	
 7907: 	if(defined($value)) {
 7908: 	    &Debug("$user @ $domain is an author");
 7909: 	}
 7910:     } else {
 7911: 	return 'error: '.($!+0)." tie (GDBM) Failed";
 7912:     }
 7913: 
 7914:     return defined($value);
 7915: }
 7916: #
 7917: #   Checks to see if the input roleput request was to set
 7918: # an author role.  If so, creates construction space 
 7919: # Parameters:
 7920: #    request   - The request sent to the rolesput subchunk.
 7921: #                We're looking for  /domain/_au
 7922: #    domain    - The domain in which the user is having roles doctored.
 7923: #    user      - Name of the user for which the role is being put.
 7924: #    authtype  - The authentication type associated with the user.
 7925: #
 7926: sub manage_permissions {
 7927:     my ($request, $domain, $user, $authtype) = @_;
 7928:     # See if the request is of the form /$domain/_au
 7929:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
 7930:         my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
 7931:         unless (-e $path) {        
 7932:            mkdir($path);
 7933:         }
 7934:         unless (-e $path.'/'.$user) {
 7935:            mkdir($path.'/'.$user);
 7936:         }
 7937:     }
 7938: }
 7939: 
 7940: 
 7941: #
 7942: #  Return the full path of a user password file, whether it exists or not.
 7943: # Parameters:
 7944: #   domain     - Domain in which the password file lives.
 7945: #   user       - name of the user.
 7946: # Returns:
 7947: #    Full passwd path:
 7948: #
 7949: sub password_path {
 7950:     my ($domain, $user) = @_;
 7951:     return &propath($domain, $user).'/passwd';
 7952: }
 7953: 
 7954: #   Password Filename
 7955: #   Returns the path to a passwd file given domain and user... only if
 7956: #  it exists.
 7957: # Parameters:
 7958: #   domain    - Domain in which to search.
 7959: #   user      - username.
 7960: # Returns:
 7961: #   - If the password file exists returns its path.
 7962: #   - If the password file does not exist, returns undefined.
 7963: #
 7964: sub password_filename {
 7965:     my ($domain, $user) = @_;
 7966: 
 7967:     Debug ("PasswordFilename called: dom = $domain user = $user");
 7968: 
 7969:     my $path  = &password_path($domain, $user);
 7970:     Debug("PasswordFilename got path: $path");
 7971:     if(-e $path) {
 7972: 	return $path;
 7973:     } else {
 7974: 	return undef;
 7975:     }
 7976: }
 7977: 
 7978: #
 7979: #   Rewrite the contents of the user's passwd file.
 7980: #  Parameters:
 7981: #    domain    - domain of the user.
 7982: #    name      - User's name.
 7983: #    contents  - New contents of the file.
 7984: #    saveold   - (optional). If true save old file in a passwd.bak file.
 7985: # Returns:
 7986: #   0    - Failed.
 7987: #   1    - Success.
 7988: #
 7989: sub rewrite_password_file {
 7990:     my ($domain, $user, $contents, $saveold) = @_;
 7991: 
 7992:     my $file = &password_filename($domain, $user);
 7993:     if (defined $file) {
 7994:         if ($saveold) {
 7995:             my $bakfile = $file.'.bak';
 7996:             if (CopyFile($file,$bakfile)) {
 7997:                 chmod(0400,$bakfile);
 7998:                 &logthis("Old password saved in passwd.bak for internally authenticated user: $user:$domain");
 7999:             } else {
 8000:                 &logthis("Failed to save old password in passwd.bak for internally authenticated user: $user:$domain");
 8001:             }
 8002:         }
 8003: 	my $pf = IO::File->new(">$file");
 8004: 	if($pf) {
 8005: 	    print $pf "$contents\n";
 8006: 	    return 1;
 8007: 	} else {
 8008: 	    return 0;
 8009: 	}
 8010:     } else {
 8011: 	return 0;
 8012:     }
 8013: 
 8014: }
 8015: 
 8016: #
 8017: #   get_auth_type - Determines the authorization type of a user in a domain.
 8018: 
 8019: #     Returns the authorization type or nouser if there is no such user.
 8020: #
 8021: sub get_auth_type {
 8022:     my ($domain, $user)  = @_;
 8023: 
 8024:     Debug("get_auth_type( $domain, $user ) \n");
 8025:     my $proname    = &propath($domain, $user); 
 8026:     my $passwdfile = "$proname/passwd";
 8027:     if( -e $passwdfile ) {
 8028: 	my $pf = IO::File->new($passwdfile);
 8029: 	my $realpassword = <$pf>;
 8030: 	chomp($realpassword);
 8031: 	Debug("Password info = $realpassword\n");
 8032: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
 8033: 	Debug("Authtype = $authtype, content = $contentpwd\n");
 8034: 	return "$authtype:$contentpwd";     
 8035:     } else {
 8036: 	Debug("Returning nouser");
 8037: 	return "nouser";
 8038:     }
 8039: }
 8040: 
 8041: #
 8042: #  Validate a user given their domain, name and password.  This utility
 8043: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
 8044: #  to validate the login credentials of a user.
 8045: # Parameters:
 8046: #    $domain    - The domain being logged into (this is required due to
 8047: #                 the capability for multihomed systems.
 8048: #    $user      - The name of the user being validated.
 8049: #    $password  - The user's propoposed password.
 8050: #
 8051: # Returns:
 8052: #     1        - The domain,user,pasword triplet corresponds to a valid
 8053: #                user.
 8054: #     0        - The domain,user,password triplet is not a valid user.
 8055: #
 8056: sub validate_user {
 8057:     my ($domain, $user, $password, $checkdefauth) = @_;
 8058: 
 8059:     # Why negative ~pi you may well ask?  Well this function is about
 8060:     # authentication, and therefore very important to get right.
 8061:     # I've initialized the flag that determines whether or not I've 
 8062:     # validated correctly to a value it's not supposed to get.
 8063:     # At the end of this function. I'll ensure that it's not still that
 8064:     # value so we don't just wind up returning some accidental value
 8065:     # as a result of executing an unforseen code path that
 8066:     # did not set $validated.  At the end of valid execution paths,
 8067:     # validated shoule be 1 for success or 0 for failuer.
 8068: 
 8069:     my $validated = -3.14159;
 8070: 
 8071:     #  How we authenticate is determined by the type of authentication
 8072:     #  the user has been assigned.  If the authentication type is
 8073:     #  "nouser", the user does not exist so we will return 0.
 8074: 
 8075:     my $contents = &get_auth_type($domain, $user);
 8076:     my ($howpwd, $contentpwd) = split(/:/, $contents);
 8077: 
 8078:     my $null = pack("C",0);	# Used by kerberos auth types.
 8079: 
 8080:     if ($howpwd eq 'nouser') {
 8081:         if ($checkdefauth) {
 8082:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 8083:             if ($domdefaults{'auth_def'} eq 'localauth') {
 8084:                 $howpwd = $domdefaults{'auth_def'};
 8085:                 $contentpwd = $domdefaults{'auth_arg_def'};
 8086:             } elsif ((($domdefaults{'auth_def'} eq 'krb4') || 
 8087:                       ($domdefaults{'auth_def'} eq 'krb5')) &&
 8088:                      ($domdefaults{'auth_arg_def'} ne '')) {
 8089:                 $howpwd = $domdefaults{'auth_def'};
 8090:                 $contentpwd = $domdefaults{'auth_arg_def'}; 
 8091:             }
 8092:         }
 8093:     }
 8094:     if ($howpwd ne 'nouser') {
 8095: 	if($howpwd eq "internal") { # Encrypted is in local password file.
 8096:             if (length($contentpwd) == 13) {
 8097:                 $validated = (crypt($password,$contentpwd) eq $contentpwd);
 8098:                 if ($validated) {
 8099:                     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 8100:                     if ($domdefaults{'intauth_switch'}) {
 8101:                         my $ncpass = &hash_passwd($domain,$password);
 8102:                         my $saveold;
 8103:                         if ($domdefaults{'intauth_switch'} == 2) {
 8104:                             $saveold = 1;
 8105:                         }
 8106:                         if (&rewrite_password_file($domain,$user,"$howpwd:$ncpass",$saveold)) {
 8107:                             &update_passwd_history($user,$domain,$howpwd,'conversion');
 8108:                             &logthis("Validated password hashed with bcrypt for $user:$domain");
 8109:                         }
 8110:                     }
 8111:                 }
 8112:             } else {
 8113:                 $validated = &check_internal_passwd($password,$contentpwd,$domain,$user);
 8114:             }
 8115: 	}
 8116: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
 8117: 	    $contentpwd = (getpwnam($user))[1];
 8118: 	    if($contentpwd) {
 8119: 		if($contentpwd eq 'x') { # Shadow password file...
 8120: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
 8121: 		    open PWAUTH,  "|$pwauth_path" or
 8122: 			die "Cannot invoke authentication";
 8123: 		    print PWAUTH "$user\n$password\n";
 8124: 		    close PWAUTH;
 8125: 		    $validated = ! $?;
 8126: 
 8127: 		} else { 	         # Passwords in /etc/passwd. 
 8128: 		    $validated = (crypt($password,
 8129: 					$contentpwd) eq $contentpwd);
 8130: 		}
 8131: 	    } else {
 8132: 		$validated = 0;
 8133: 	    }
 8134: 	} elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
 8135:             my $checkwithkrb5 = 0;
 8136:             if ($dist =~/^fedora(\d+)$/) {
 8137:                 if ($1 > 11) {
 8138:                     $checkwithkrb5 = 1;
 8139:                 }
 8140:             } elsif ($dist =~ /^suse([\d.]+)$/) {
 8141:                 if ($1 > 11.1) {
 8142:                     $checkwithkrb5 = 1; 
 8143:                 }
 8144:             }
 8145:             if ($checkwithkrb5) {
 8146:                 $validated = &krb5_authen($password,$null,$user,$contentpwd);
 8147:             } else {
 8148:                 $validated = &krb4_authen($password,$null,$user,$contentpwd);
 8149:             }
 8150: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
 8151:             $validated = &krb5_authen($password,$null,$user,$contentpwd);
 8152: 	} elsif ($howpwd eq "localauth") { 
 8153: 	    #  Authenticate via installation specific authentcation method:
 8154: 	    $validated = &localauth::localauth($user, 
 8155: 					       $password, 
 8156: 					       $contentpwd,
 8157: 					       $domain);
 8158: 	    if ($validated < 0) {
 8159: 		&logthis("localauth for $contentpwd $user:$domain returned a $validated");
 8160: 		$validated = 0;
 8161: 	    }
 8162: 	} else {			# Unrecognized auth is also bad.
 8163: 	    $validated = 0;
 8164: 	}
 8165:     } else {
 8166: 	$validated = 0;
 8167:     }
 8168:     #
 8169:     #  $validated has the correct stat of the authentication:
 8170:     #
 8171: 
 8172:     unless ($validated != -3.14159) {
 8173: 	#  I >really really< want to know if this happens.
 8174: 	#  since it indicates that user authentication is badly
 8175: 	#  broken in some code path.
 8176:         #
 8177: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
 8178:     }
 8179:     return $validated;
 8180: }
 8181: 
 8182: sub check_internal_passwd {
 8183:     my ($plainpass,$stored,$domain,$user) = @_;
 8184:     my (undef,$method,@rest) = split(/!/,$stored);
 8185:     if ($method eq 'bcrypt') {
 8186:         my $result = &hash_passwd($domain,$plainpass,@rest);
 8187:         if ($result ne $stored) {
 8188:             return 0;
 8189:         }
 8190:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 8191:         if ($domdefaults{'intauth_check'}) {
 8192:             # Upgrade to a larger number of rounds if necessary
 8193:             my $defaultcost = $domdefaults{'intauth_cost'};
 8194:             if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
 8195:                 $defaultcost = 10;
 8196:             }
 8197:             if (int($rest[0])<int($defaultcost)) {
 8198:                 if ($domdefaults{'intauth_check'} == 1) { 
 8199:                     my $ncpass = &hash_passwd($domain,$plainpass);
 8200:                     if (&rewrite_password_file($domain,$user,"internal:$ncpass")) {
 8201:                         &update_passwd_history($user,$domain,'internal','update cost');
 8202:                         &logthis("Validated password hashed with bcrypt for $user:$domain");
 8203:                     }
 8204:                     return 1;
 8205:                 } elsif ($domdefaults{'intauth_check'} == 2) {
 8206:                     return 0;
 8207:                 }
 8208:             }
 8209:         } else {
 8210:             return 1;
 8211:         }
 8212:     }
 8213:     return 0;
 8214: }
 8215: 
 8216: sub get_last_authchg {
 8217:     my ($domain,$user) = @_;
 8218:     my $lastmod;
 8219:     my $logname = &propath($domain,$user).'/passwd.log';
 8220:     if (-e "$logname") {
 8221:         $lastmod = (stat("$logname"))[9];
 8222:     }
 8223:     return $lastmod;
 8224: }
 8225: 
 8226: sub krb4_authen {
 8227:     my ($password,$null,$user,$contentpwd) = @_;
 8228:     my $validated = 0;
 8229:     if (!($password =~ /$null/) ) {  # Null password not allowed.
 8230:         eval {
 8231:             require Authen::Krb4;
 8232:         };
 8233:         if (!$@) {
 8234:             my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
 8235:                                                        "",
 8236:                                                        $contentpwd,,
 8237:                                                        'krbtgt',
 8238:                                                        $contentpwd,
 8239:                                                        1,
 8240:                                                        $password);
 8241:             if(!$k4error) {
 8242:                 $validated = 1;
 8243:             } else {
 8244:                 $validated = 0;
 8245:                 &logthis('krb4: '.$user.', '.$contentpwd.', '.
 8246:                           &Authen::Krb4::get_err_txt($Authen::Krb4::error));
 8247:             }
 8248:         } else {
 8249:             $validated = krb5_authen($password,$null,$user,$contentpwd);
 8250:         }
 8251:     }
 8252:     return $validated;
 8253: }
 8254: 
 8255: sub krb5_authen {
 8256:     my ($password,$null,$user,$contentpwd) = @_;
 8257:     my $validated = 0;
 8258:     if(!($password =~ /$null/)) { # Null password not allowed.
 8259:         my $krbclient = &Authen::Krb5::parse_name($user.'@'
 8260:                                                   .$contentpwd);
 8261:         my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
 8262:         my $krbserver  = &Authen::Krb5::parse_name($krbservice);
 8263:         my $credentials= &Authen::Krb5::cc_default();
 8264:         $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
 8265:                                                             .$contentpwd));
 8266:         my $krbreturn;
 8267:         if (exists(&Authen::Krb5::get_init_creds_password)) {
 8268:             $krbreturn =
 8269:                 &Authen::Krb5::get_init_creds_password($krbclient,$password,
 8270:                                                           $krbservice);
 8271:             $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
 8272:         } else {
 8273:             $krbreturn  =
 8274:                 &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
 8275:                                                          $password,$credentials);
 8276:             $validated = ($krbreturn == 1);
 8277:         }
 8278:         if (!$validated) {
 8279:             &logthis('krb5: '.$user.', '.$contentpwd.', '.
 8280:                      &Authen::Krb5::error());
 8281:         }
 8282:     }
 8283:     return $validated;
 8284: }
 8285: 
 8286: sub addline {
 8287:     my ($fname,$hostid,$ip,$newline)=@_;
 8288:     my $contents;
 8289:     my $found=0;
 8290:     my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
 8291:     my $sh;
 8292:     if ($sh=IO::File->new("$fname.subscription")) {
 8293: 	while (my $subline=<$sh>) {
 8294: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
 8295: 	}
 8296: 	$sh->close();
 8297:     }
 8298:     $sh=IO::File->new(">$fname.subscription");
 8299:     if ($contents) { print $sh $contents; }
 8300:     if ($newline) { print $sh $newline; }
 8301:     $sh->close();
 8302:     return $found;
 8303: }
 8304: 
 8305: sub get_chat {
 8306:     my ($cdom,$cname,$udom,$uname,$group)=@_;
 8307: 
 8308:     my @entries=();
 8309:     my $namespace = 'nohist_chatroom';
 8310:     my $namespace_inroom = 'nohist_inchatroom';
 8311:     if ($group ne '') {
 8312:         $namespace .= '_'.$group;
 8313:         $namespace_inroom .= '_'.$group;
 8314:     }
 8315:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
 8316: 				 &GDBM_READER());
 8317:     if ($hashref) {
 8318: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
 8319: 	&untie_user_hash($hashref);
 8320:     }
 8321:     my @participants=();
 8322:     my $cutoff=time-60;
 8323:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
 8324: 			      &GDBM_WRCREAT());
 8325:     if ($hashref) {
 8326:         $hashref->{$uname.':'.$udom}=time;
 8327:         foreach my $user (sort(keys(%$hashref))) {
 8328: 	    if ($hashref->{$user}>$cutoff) {
 8329: 		push(@participants, 'active_participant:'.$user);
 8330:             }
 8331:         }
 8332:         &untie_user_hash($hashref);
 8333:     }
 8334:     return (@participants,@entries);
 8335: }
 8336: 
 8337: sub chat_add {
 8338:     my ($cdom,$cname,$newchat,$group)=@_;
 8339:     my @entries=();
 8340:     my $time=time;
 8341:     my $namespace = 'nohist_chatroom';
 8342:     my $logfile = 'chatroom.log';
 8343:     if ($group ne '') {
 8344:         $namespace .= '_'.$group;
 8345:         $logfile = 'chatroom_'.$group.'.log';
 8346:     }
 8347:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
 8348: 				 &GDBM_WRCREAT());
 8349:     if ($hashref) {
 8350: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
 8351: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
 8352: 	my ($thentime,$idnum)=split(/\_/,$lastid);
 8353: 	my $newid=$time.'_000000';
 8354: 	if ($thentime==$time) {
 8355: 	    $idnum=~s/^0+//;
 8356: 	    $idnum++;
 8357: 	    $idnum=substr('000000'.$idnum,-6,6);
 8358: 	    $newid=$time.'_'.$idnum;
 8359: 	}
 8360: 	$hashref->{$newid}=$newchat;
 8361: 	my $expired=$time-3600;
 8362: 	foreach my $comment (keys(%$hashref)) {
 8363: 	    my ($thistime) = ($comment=~/(\d+)\_/);
 8364: 	    if ($thistime<$expired) {
 8365: 		delete $hashref->{$comment};
 8366: 	    }
 8367: 	}
 8368: 	{
 8369: 	    my $proname=&propath($cdom,$cname);
 8370: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
 8371: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
 8372: 	    }
 8373: 	    close(CHATLOG);
 8374: 	}
 8375: 	&untie_user_hash($hashref);
 8376:     }
 8377: }
 8378: 
 8379: sub unsub {
 8380:     my ($fname,$clientip)=@_;
 8381:     my $result;
 8382:     my $unsubs = 0;		# Number of successful unsubscribes:
 8383: 
 8384: 
 8385:     # An old way subscriptions were handled was to have a 
 8386:     # subscription marker file:
 8387: 
 8388:     Debug("Attempting unlink of $fname.$clientname");
 8389:     if (unlink("$fname.$clientname")) {
 8390: 	$unsubs++;		# Successful unsub via marker file.
 8391:     } 
 8392: 
 8393:     # The more modern way to do it is to have a subscription list
 8394:     # file:
 8395: 
 8396:     if (-e "$fname.subscription") {
 8397: 	my $found=&addline($fname,$clientname,$clientip,'');
 8398: 	if ($found) { 
 8399: 	    $unsubs++;
 8400: 	}
 8401:     } 
 8402: 
 8403:     #  If either or both of these mechanisms succeeded in unsubscribing a 
 8404:     #  resource we can return ok:
 8405: 
 8406:     if($unsubs) {
 8407: 	$result = "ok\n";
 8408:     } else {
 8409: 	$result = "not_subscribed\n";
 8410:     }
 8411: 
 8412:     return $result;
 8413: }
 8414: 
 8415: sub currentversion {
 8416:     my $fname=shift;
 8417:     my $version=-1;
 8418:     my $ulsdir='';
 8419:     if ($fname=~/^(.+)\/[^\/]+$/) {
 8420:        $ulsdir=$1;
 8421:     }
 8422:     my ($fnamere1,$fnamere2);
 8423:     # remove version if already specified
 8424:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
 8425:     # get the bits that go before and after the version number
 8426:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
 8427: 	$fnamere1=$1;
 8428: 	$fnamere2='.'.$2;
 8429:     }
 8430:     if (-e $fname) { $version=1; }
 8431:     if (-e $ulsdir) {
 8432: 	if(-d $ulsdir) {
 8433: 	    if (opendir(LSDIR,$ulsdir)) {
 8434: 		my $ulsfn;
 8435: 		while ($ulsfn=readdir(LSDIR)) {
 8436: # see if this is a regular file (ignore links produced earlier)
 8437: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
 8438: 		    unless (-l $thisfile) {
 8439: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
 8440: 			    if ($1>$version) { $version=$1; }
 8441: 			}
 8442: 		    }
 8443: 		}
 8444: 		closedir(LSDIR);
 8445: 		$version++;
 8446: 	    }
 8447: 	}
 8448:     }
 8449:     return $version;
 8450: }
 8451: 
 8452: sub thisversion {
 8453:     my $fname=shift;
 8454:     my $version=-1;
 8455:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
 8456: 	$version=$1;
 8457:     }
 8458:     return $version;
 8459: }
 8460: 
 8461: sub subscribe {
 8462:     my ($userinput,$clientip)=@_;
 8463:     my $result;
 8464:     my ($cmd,$fname)=split(/:/,$userinput,2);
 8465:     my $ownership=&ishome($fname);
 8466:     if ($ownership eq 'owner') {
 8467: # explitly asking for the current version?
 8468:         unless (-e $fname) {
 8469:             my $currentversion=&currentversion($fname);
 8470: 	    if (&thisversion($fname)==$currentversion) {
 8471:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
 8472: 		    my $root=$1;
 8473:                     my $extension=$2;
 8474:                     symlink($root.'.'.$extension,
 8475:                             $root.'.'.$currentversion.'.'.$extension);
 8476:                     unless ($extension=~/\.meta$/) {
 8477:                        symlink($root.'.'.$extension.'.meta',
 8478:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
 8479: 		    }
 8480:                 }
 8481:             }
 8482:         }
 8483: 	if (-e $fname) {
 8484: 	    if (-d $fname) {
 8485: 		$result="directory\n";
 8486: 	    } else {
 8487: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
 8488: 		my $now=time;
 8489: 		my $found=&addline($fname,$clientname,$clientip,
 8490: 				   "$clientname:$clientip:$now\n");
 8491: 		if ($found) { $result="$fname\n"; }
 8492: 		# if they were subscribed to only meta data, delete that
 8493:                 # subscription, when you subscribe to a file you also get
 8494:                 # the metadata
 8495: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
 8496: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
 8497:                 my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
 8498:                 $protocol = 'http' if ($protocol ne 'https');
 8499: 		$fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
 8500: 		$result="$fname\n";
 8501: 	    }
 8502: 	} else {
 8503: 	    $result="not_found\n";
 8504: 	}
 8505:     } else {
 8506: 	$result="rejected\n";
 8507:     }
 8508:     return $result;
 8509: }
 8510: #  Change the passwd of a unix user.  The caller must have
 8511: #  first verified that the user is a loncapa user.
 8512: #
 8513: # Parameters:
 8514: #    user      - Unix user name to change.
 8515: #    pass      - New password for the user.
 8516: # Returns:
 8517: #    ok    - if success
 8518: #    other - Some meaningfule error message string.
 8519: # NOTE:
 8520: #    invokes a setuid script to change the passwd.
 8521: sub change_unix_password {
 8522:     my ($user, $pass) = @_;
 8523: 
 8524:     &Debug("change_unix_password");
 8525:     my $execdir=$perlvar{'lonDaemons'};
 8526:     &Debug("Opening lcpasswd pipeline");
 8527:     my $pf = IO::File->new("|$execdir/lcpasswd > "
 8528: 			   ."$perlvar{'lonDaemons'}"
 8529: 			   ."/logs/lcpasswd.log");
 8530:     print $pf "$user\n$pass\n$pass\n";
 8531:     close $pf;
 8532:     my $err = $?;
 8533:     return ($err < @passwderrors) ? $passwderrors[$err] : 
 8534: 	"pwchange_falure - unknown error";
 8535: 
 8536:     
 8537: }
 8538: 
 8539: 
 8540: sub make_passwd_file {
 8541:     my ($uname,$udom,$umode,$npass,$passfilename,$action)=@_;
 8542:     my $result="ok";
 8543:     if ($umode eq 'krb4' or $umode eq 'krb5') {
 8544: 	{
 8545: 	    my $pf = IO::File->new(">$passfilename");
 8546: 	    if ($pf) {
 8547: 		print $pf "$umode:$npass\n";
 8548:                 &update_passwd_history($uname,$udom,$umode,$action);
 8549: 	    } else {
 8550: 		$result = "pass_file_failed_error";
 8551: 	    }
 8552: 	}
 8553:     } elsif ($umode eq 'internal') {
 8554:         my $ncpass = &hash_passwd($udom,$npass);
 8555: 	{
 8556: 	    &Debug("Creating internal auth");
 8557: 	    my $pf = IO::File->new(">$passfilename");
 8558: 	    if($pf) {
 8559: 		print $pf "internal:$ncpass\n";
 8560:                 &update_passwd_history($uname,$udom,$umode,$action); 
 8561: 	    } else {
 8562: 		$result = "pass_file_failed_error";
 8563: 	    }
 8564: 	}
 8565:     } elsif ($umode eq 'localauth') {
 8566: 	{
 8567: 	    my $pf = IO::File->new(">$passfilename");
 8568: 	    if($pf) {
 8569: 		print $pf "localauth:$npass\n";
 8570:                 &update_passwd_history($uname,$udom,$umode,$action);
 8571: 	    } else {
 8572: 		$result = "pass_file_failed_error";
 8573: 	    }
 8574: 	}
 8575:     } elsif ($umode eq 'unix') {
 8576: 	&logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
 8577: 	$result="no_new_unix_accounts";
 8578:     } elsif ($umode eq 'none') {
 8579: 	{
 8580: 	    my $pf = IO::File->new("> $passfilename");
 8581: 	    if($pf) {
 8582: 		print $pf "none:\n";
 8583: 	    } else {
 8584: 		$result = "pass_file_failed_error";
 8585: 	    }
 8586: 	}
 8587:     } elsif ($umode eq 'lti') {
 8588:         my $pf = IO::File->new(">$passfilename");
 8589:         if($pf) {
 8590:             print $pf "lti:\n";
 8591:             &update_passwd_history($uname,$udom,$umode,$action);
 8592:         } else {
 8593:             $result = "pass_file_failed_error";
 8594:         }
 8595:     } else {
 8596: 	$result="auth_mode_error";
 8597:     }
 8598:     return $result;
 8599: }
 8600: 
 8601: sub convert_photo {
 8602:     my ($start,$dest)=@_;
 8603:     system("convert $start $dest");
 8604: }
 8605: 
 8606: sub sethost {
 8607:     my ($remotereq) = @_;
 8608:     my (undef,$hostid)=split(/:/,$remotereq);
 8609:     # ignore sethost if we are already correct
 8610:     if ($hostid eq $currenthostid) {
 8611: 	return 'ok';
 8612:     }
 8613: 
 8614:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
 8615:     if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'}) 
 8616: 	eq &Apache::lonnet::get_host_ip($hostid)) {
 8617: 	$currenthostid  =$hostid;
 8618: 	$currentdomainid=&Apache::lonnet::host_domain($hostid);
 8619:         &set_client_info();
 8620: #	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
 8621:     } else {
 8622: 	&logthis("Requested host id $hostid not an alias of ".
 8623: 		 $perlvar{'lonHostID'}." refusing connection");
 8624: 	return 'unable_to_set';
 8625:     }
 8626:     return 'ok';
 8627: }
 8628: 
 8629: sub version {
 8630:     my ($userinput)=@_;
 8631:     $remoteVERSION=(split(/:/,$userinput))[1];
 8632:     return "version:$VERSION";
 8633: }
 8634: 
 8635: sub get_usersession_config {
 8636:     my ($dom,$name) = @_;
 8637:     my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
 8638:     if (defined($cached)) {
 8639:         return $usersessionconf;
 8640:     } else {
 8641:         my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
 8642:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
 8643:         return $domconfig{'usersessions'};
 8644:     }
 8645:     return;
 8646: }
 8647: 
 8648: sub get_usersearch_config {
 8649:     my ($dom,$name) = @_;
 8650:     my ($usersearchconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
 8651:     if (defined($cached)) {
 8652:         return $usersearchconf;
 8653:     } else {
 8654:         my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$dom);
 8655:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'directorysrch'},600);
 8656:         return $domconfig{'directorysrch'};
 8657:     }
 8658:     return;
 8659: }
 8660: 
 8661: sub get_prohibited {
 8662:     my ($dom) = @_;
 8663:     my $name = 'trust';
 8664:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
 8665:     unless (defined($cached)) {
 8666:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$dom);
 8667:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'trust'},3600);
 8668:         $trustconfig = $domconfig{'trust'};
 8669:     }
 8670:     my %prohibited;
 8671:     if (ref($trustconfig)) {
 8672:         foreach my $prefix (keys(%{$trustconfig})) {
 8673:             if (ref($trustconfig->{$prefix}) eq 'HASH') {
 8674:                 my $reject;
 8675:                 if (ref($trustconfig->{$prefix}->{'exc'}) eq 'ARRAY') {
 8676:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'exc'}})) {
 8677:                         $reject = 1;
 8678:                     }
 8679:                 }
 8680:                 if (ref($trustconfig->{$prefix}->{'inc'}) eq 'ARRAY') {
 8681:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'inc'}})) {
 8682:                         $reject = 0;
 8683:                     } else {
 8684:                         $reject = 1;
 8685:                     }
 8686:                 }
 8687:                 if ($reject) {
 8688:                     $prohibited{$prefix} = 1;
 8689:                 }
 8690:             }
 8691:         }
 8692:     }
 8693:     return %prohibited;
 8694: }
 8695: 
 8696: sub get_remote_hostable {
 8697:     my ($dom) = @_;
 8698:     my $result;
 8699:     if ($clientintdom) {
 8700:         $result = 1;
 8701:         my $remsessconf = &get_usersession_config($dom,'remotesession');
 8702:         if (ref($remsessconf) eq 'HASH') {
 8703:             if (ref($remsessconf->{'remote'}) eq 'HASH') {
 8704:                 if (ref($remsessconf->{'remote'}->{'excludedomain'}) eq 'ARRAY') {
 8705:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'excludedomain'}})) {
 8706:                         $result = 0;
 8707:                     }
 8708:                 }
 8709:                 if (ref($remsessconf->{'remote'}->{'includedomain'}) eq 'ARRAY') {
 8710:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'includedomain'}})) {
 8711:                         $result = 1;
 8712:                     } else {
 8713:                         $result = 0;
 8714:                     }
 8715:                 }
 8716:             }
 8717:         }
 8718:     }
 8719:     return $result;
 8720: }
 8721: 
 8722: sub distro_and_arch {
 8723:     return $dist.':'.$arch;
 8724: }
 8725: 
 8726: # ----------------------------------- POD (plain old documentation, CPAN style)
 8727: 
 8728: =head1 NAME
 8729: 
 8730: lond - "LON Daemon" Server (port "LOND" 5663)
 8731: 
 8732: =head1 SYNOPSIS
 8733: 
 8734: Usage: B<lond>
 8735: 
 8736: Should only be run as user=www.  This is a command-line script which
 8737: is invoked by B<loncron>.  There is no expectation that a typical user
 8738: will manually start B<lond> from the command-line.  (In other words,
 8739: DO NOT START B<lond> YOURSELF.)
 8740: 
 8741: =head1 DESCRIPTION
 8742: 
 8743: There are two characteristics associated with the running of B<lond>,
 8744: PROCESS MANAGEMENT (starting, stopping, handling child processes)
 8745: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
 8746: subscriptions, etc).  These are described in two large
 8747: sections below.
 8748: 
 8749: B<PROCESS MANAGEMENT>
 8750: 
 8751: Preforker - server who forks first. Runs as a daemon. HUPs.
 8752: Uses IDEA encryption
 8753: 
 8754: B<lond> forks off children processes that correspond to the other servers
 8755: in the network.  Management of these processes can be done at the
 8756: parent process level or the child process level.
 8757: 
 8758: B<logs/lond.log> is the location of log messages.
 8759: 
 8760: The process management is now explained in terms of linux shell commands,
 8761: subroutines internal to this code, and signal assignments:
 8762: 
 8763: =over 4
 8764: 
 8765: =item *
 8766: 
 8767: PID is stored in B<logs/lond.pid>
 8768: 
 8769: This is the process id number of the parent B<lond> process.
 8770: 
 8771: =item *
 8772: 
 8773: SIGTERM and SIGINT
 8774: 
 8775: Parent signal assignment:
 8776:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 8777: 
 8778: Child signal assignment:
 8779:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
 8780: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
 8781:  to restart a new child.)
 8782: 
 8783: Command-line invocations:
 8784:  B<kill> B<-s> SIGTERM I<PID>
 8785:  B<kill> B<-s> SIGINT I<PID>
 8786: 
 8787: Subroutine B<HUNTSMAN>:
 8788:  This is only invoked for the B<lond> parent I<PID>.
 8789: This kills all the children, and then the parent.
 8790: The B<lonc.pid> file is cleared.
 8791: 
 8792: =item *
 8793: 
 8794: SIGHUP
 8795: 
 8796: Current bug:
 8797:  This signal can only be processed the first time
 8798: on the parent process.  Subsequent SIGHUP signals
 8799: have no effect.
 8800: 
 8801: Parent signal assignment:
 8802:  $SIG{HUP}  = \&HUPSMAN;
 8803: 
 8804: Child signal assignment:
 8805:  none (nothing happens)
 8806: 
 8807: Command-line invocations:
 8808:  B<kill> B<-s> SIGHUP I<PID>
 8809: 
 8810: Subroutine B<HUPSMAN>:
 8811:  This is only invoked for the B<lond> parent I<PID>,
 8812: This kills all the children, and then the parent.
 8813: The B<lond.pid> file is cleared.
 8814: 
 8815: =item *
 8816: 
 8817: SIGUSR1
 8818: 
 8819: Parent signal assignment:
 8820:  $SIG{USR1} = \&USRMAN;
 8821: 
 8822: Child signal assignment:
 8823:  $SIG{USR1}= \&logstatus;
 8824: 
 8825: Command-line invocations:
 8826:  B<kill> B<-s> SIGUSR1 I<PID>
 8827: 
 8828: Subroutine B<USRMAN>:
 8829:  When invoked for the B<lond> parent I<PID>,
 8830: SIGUSR1 is sent to all the children, and the status of
 8831: each connection is logged.
 8832: 
 8833: =item *
 8834: 
 8835: SIGUSR2
 8836: 
 8837: Parent Signal assignment:
 8838:     $SIG{USR2} = \&UpdateHosts
 8839: 
 8840: Child signal assignment:
 8841:     NONE
 8842: 
 8843: 
 8844: =item *
 8845: 
 8846: SIGCHLD
 8847: 
 8848: Parent signal assignment:
 8849:  $SIG{CHLD} = \&REAPER;
 8850: 
 8851: Child signal assignment:
 8852:  none
 8853: 
 8854: Command-line invocations:
 8855:  B<kill> B<-s> SIGCHLD I<PID>
 8856: 
 8857: Subroutine B<REAPER>:
 8858:  This is only invoked for the B<lond> parent I<PID>.
 8859: Information pertaining to the child is removed.
 8860: The socket port is cleaned up.
 8861: 
 8862: =back
 8863: 
 8864: B<SERVER-SIDE ACTIVITIES>
 8865: 
 8866: Server-side information can be accepted in an encrypted or non-encrypted
 8867: method.
 8868: 
 8869: =over 4
 8870: 
 8871: =item ping
 8872: 
 8873: Query a client in the hosts.tab table; "Are you there?"
 8874: 
 8875: =item pong
 8876: 
 8877: Respond to a ping query.
 8878: 
 8879: =item ekey
 8880: 
 8881: Read in encrypted key, make cipher.  Respond with a buildkey.
 8882: 
 8883: =item load
 8884: 
 8885: Respond with CPU load based on a computation upon /proc/loadavg.
 8886: 
 8887: =item currentauth
 8888: 
 8889: Reply with current authentication information (only over an
 8890: encrypted channel).
 8891: 
 8892: =item auth
 8893: 
 8894: Only over an encrypted channel, reply as to whether a user's
 8895: authentication information can be validated.
 8896: 
 8897: =item passwd
 8898: 
 8899: Allow for a password to be set.
 8900: 
 8901: =item makeuser
 8902: 
 8903: Make a user.
 8904: 
 8905: =item changeuserauth
 8906: 
 8907: Allow for authentication mechanism and password to be changed.
 8908: 
 8909: =item home
 8910: 
 8911: Respond to a question "are you the home for a given user?"
 8912: 
 8913: =item update
 8914: 
 8915: Update contents of a subscribed resource.
 8916: 
 8917: =item unsubscribe
 8918: 
 8919: The server is unsubscribing from a resource.
 8920: 
 8921: =item subscribe
 8922: 
 8923: The server is subscribing to a resource.
 8924: 
 8925: =item log
 8926: 
 8927: Place in B<logs/lond.log>
 8928: 
 8929: =item put
 8930: 
 8931: stores hash in namespace
 8932: 
 8933: =item rolesput
 8934: 
 8935: put a role into a user's environment
 8936: 
 8937: =item get
 8938: 
 8939: returns hash with keys from array
 8940: reference filled in from namespace
 8941: 
 8942: =item eget
 8943: 
 8944: returns hash with keys from array
 8945: reference filled in from namesp (encrypts the return communication)
 8946: 
 8947: =item rolesget
 8948: 
 8949: get a role from a user's environment
 8950: 
 8951: =item del
 8952: 
 8953: deletes keys out of array from namespace
 8954: 
 8955: =item keys
 8956: 
 8957: returns namespace keys
 8958: 
 8959: =item dump
 8960: 
 8961: dumps the complete (or key matching regexp) namespace into a hash
 8962: 
 8963: =item store
 8964: 
 8965: stores hash permanently
 8966: for this url; hashref needs to be given and should be a \%hashname; the
 8967: remaining args aren't required and if they aren't passed or are '' they will
 8968: be derived from the ENV
 8969: 
 8970: =item restore
 8971: 
 8972: returns a hash for a given url
 8973: 
 8974: =item querysend
 8975: 
 8976: Tells client about the lonsql process that has been launched in response
 8977: to a sent query.
 8978: 
 8979: =item queryreply
 8980: 
 8981: Accept information from lonsql and make appropriate storage in temporary
 8982: file space.
 8983: 
 8984: =item idput
 8985: 
 8986: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
 8987: for each student, defined perhaps by the institutional Registrar.)
 8988: 
 8989: =item idget
 8990: 
 8991: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
 8992: for each student, defined perhaps by the institutional Registrar.)
 8993: 
 8994: =item iddel
 8995: 
 8996: Deletes one or more ids in a domain's id database.
 8997: 
 8998: =item tmpput
 8999: 
 9000: Accept and store information in temporary space.
 9001: 
 9002: =item tmpget
 9003: 
 9004: Send along temporarily stored information.
 9005: 
 9006: =item ls
 9007: 
 9008: List part of a user's directory.
 9009: 
 9010: =item pushtable
 9011: 
 9012: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
 9013: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
 9014: must be restored manually in case of a problem with the new table file.
 9015: pushtable requires that the request be encrypted and validated via
 9016: ValidateManager.  The form of the command is:
 9017: enc:pushtable tablename <tablecontents> \n
 9018: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
 9019: cleartext newline.
 9020: 
 9021: =item Hanging up (exit or init)
 9022: 
 9023: What to do when a client tells the server that they (the client)
 9024: are leaving the network.
 9025: 
 9026: =item unknown command
 9027: 
 9028: If B<lond> is sent an unknown command (not in the list above),
 9029: it replys to the client "unknown_cmd".
 9030: 
 9031: 
 9032: =item UNKNOWN CLIENT
 9033: 
 9034: If the anti-spoofing algorithm cannot verify the client,
 9035: the client is rejected (with a "refused" message sent
 9036: to the client, and the connection is closed.
 9037: 
 9038: =back
 9039: 
 9040: =head1 PREREQUISITES
 9041: 
 9042: IO::Socket
 9043: IO::File
 9044: Apache::File
 9045: POSIX
 9046: Crypt::IDEA
 9047: GDBM_File
 9048: Authen::Krb4
 9049: Authen::Krb5
 9050: 
 9051: =head1 COREQUISITES
 9052: 
 9053: none
 9054: 
 9055: =head1 OSNAMES
 9056: 
 9057: linux
 9058: 
 9059: =head1 SCRIPT CATEGORIES
 9060: 
 9061: Server/Process
 9062: 
 9063: =cut
 9064: 
 9065: 
 9066: =pod
 9067: 
 9068: =head1 LOG MESSAGES
 9069: 
 9070: The messages below can be emitted in the lond log.  This log is located
 9071: in ~httpd/perl/logs/lond.log  Many log messages have HTML encapsulation
 9072: to provide coloring if examined from inside a web page. Some do not.
 9073: Where color is used, the colors are; Red for sometihhng to get excited
 9074: about and to follow up on. Yellow for something to keep an eye on to
 9075: be sure it does not get worse, Green,and Blue for informational items.
 9076: 
 9077: In the discussions below, sometimes reference is made to ~httpd
 9078: when describing file locations.  There isn't really an httpd 
 9079: user, however there is an httpd directory that gets installed in the
 9080: place that user home directories go.  On linux, this is usually
 9081: (always?) /home/httpd.
 9082: 
 9083: 
 9084: Some messages are colorless.  These are usually (not always)
 9085: Green/Blue color level messages.
 9086: 
 9087: =over 2
 9088: 
 9089: =item (Red)  LocalConnection rejecting non local: <ip> ne 127.0.0.1
 9090: 
 9091: A local connection negotiation was attempted by
 9092: a host whose IP address was not 127.0.0.1.
 9093: The socket is closed and the child will exit.
 9094: lond has three ways to establish an encyrption
 9095: key with a client:
 9096: 
 9097: =over 2
 9098: 
 9099: =item local 
 9100: 
 9101: The key is written and read from a file.
 9102: This is only valid for connections from localhost.
 9103: 
 9104: =item insecure 
 9105: 
 9106: The key is generated by the server and
 9107: transmitted to the client.
 9108: 
 9109: =item  ssl (secure)
 9110: 
 9111: An ssl connection is negotiated with the client,
 9112: the key is generated by the server and sent to the 
 9113: client across this ssl connection before the
 9114: ssl connectionis terminated and clear text
 9115: transmission resumes.
 9116: 
 9117: =back
 9118: 
 9119: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
 9120: 
 9121: The client is local but has not sent an initialization
 9122: string that is the literal "init:local"  The connection
 9123: is closed and the child exits.
 9124: 
 9125: =item Red CRITICAL Can't get key file <error>        
 9126: 
 9127: SSL key negotiation is being attempted but the call to
 9128: lonssl::KeyFile failed.  This usually means that the
 9129: configuration file is not correctly defining or protecting
 9130: the directories/files lonCertificateDirectory or
 9131: lonnetPrivateKey
 9132: <error> is a string that describes the reason that
 9133: the key file could not be located.
 9134: 
 9135: =item (Red) CRITICAL  Can't get certificates <error>  
 9136: 
 9137: SSL key negotiation failed because we were not able to retrives our certificate
 9138: or the CA's certificate in the call to lonssl::CertificateFile
 9139: <error> is the textual reason this failed.  Usual reasons:
 9140: 
 9141: =over 2
 9142: 
 9143: =item Apache config file for loncapa  incorrect:
 9144: 
 9145: one of the variables 
 9146: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
 9147: undefined or incorrect
 9148: 
 9149: =item Permission error:
 9150: 
 9151: The directory pointed to by lonCertificateDirectory is not readable by lond
 9152: 
 9153: =item Permission error:
 9154: 
 9155: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
 9156: 
 9157: =item Installation error:                         
 9158: 
 9159: Either the certificate authority file or the certificate have not
 9160: been installed in lonCertificateDirectory.
 9161: 
 9162: =item (Red) CRITICAL SSL Socket promotion failed:  <err> 
 9163: 
 9164: The promotion of the connection from plaintext to SSL failed
 9165: <err> is the reason for the failure.  There are two
 9166: system calls involved in the promotion (one of which failed), 
 9167: a dup to produce
 9168: a second fd on the raw socket over which the encrypted data
 9169: will flow and IO::SOcket::SSL->new_from_fd which creates
 9170: the SSL connection on the duped fd.
 9171: 
 9172: =item (Blue)   WARNING client did not respond to challenge 
 9173: 
 9174: This occurs on an insecure (non SSL) connection negotiation request.
 9175: lond generates some number from the time, the PID and sends it to
 9176: the client.  The client must respond by echoing this information back.
 9177: If the client does not do so, that's a violation of the challenge
 9178: protocols and the connection will be failed.
 9179: 
 9180: =item (Red) No manager table. Nobody can manage!!    
 9181: 
 9182: lond has the concept of privileged hosts that
 9183: can perform remote management function such
 9184: as update the hosts.tab.   The manager hosts
 9185: are described in the 
 9186: ~httpd/lonTabs/managers.tab file.
 9187: this message is logged if this file is missing.
 9188: 
 9189: 
 9190: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
 9191: 
 9192: Reports the successful parse and registration
 9193: of a specific manager. 
 9194: 
 9195: =item Green existing host <clustername:dnsname>  
 9196: 
 9197: The manager host is already defined in the hosts.tab
 9198: the information in that table, rather than the info in the
 9199: manager table will be used to determine the manager's ip.
 9200: 
 9201: =item (Red) Unable to craete <filename>                 
 9202: 
 9203: lond has been asked to create new versions of an administrative
 9204: file (by a manager).  When this is done, the new file is created
 9205: in a temp file and then renamed into place so that there are always
 9206: usable administrative files, even if the update fails.  This failure
 9207: message means that the temp file could not be created.
 9208: The update is abandoned, and the old file is available for use.
 9209: 
 9210: =item (Green) CopyFile from <oldname> to <newname> failed
 9211: 
 9212: In an update of administrative files, the copy of the existing file to a
 9213: backup file failed.  The installation of the new file may still succeed,
 9214: but there will not be a back up file to rever to (this should probably
 9215: be yellow).
 9216: 
 9217: =item (Green) Pushfile: backed up <oldname> to <newname>
 9218: 
 9219: See above, the backup of the old administrative file succeeded.
 9220: 
 9221: =item (Red)  Pushfile: Unable to install <filename> <reason>
 9222: 
 9223: The new administrative file could not be installed.  In this case,
 9224: the old administrative file is still in use.
 9225: 
 9226: =item (Green) Installed new < filename>.                      
 9227: 
 9228: The new administrative file was successfullly installed.                                               
 9229: 
 9230: =item (Red) Reinitializing lond pid=<pid>                    
 9231: 
 9232: The lonc child process <pid> will be sent a USR2 
 9233: signal.
 9234: 
 9235: =item (Red) Reinitializing self                                    
 9236: 
 9237: We've been asked to re-read our administrative files,and
 9238: are doing so.
 9239: 
 9240: =item (Yellow) error:Invalid process identifier <ident>  
 9241: 
 9242: A reinit command was received, but the target part of the 
 9243: command was not valid.  It must be either
 9244: 'lond' or 'lonc' but was <ident>
 9245: 
 9246: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
 9247: 
 9248: Checking to see if lond has been handed a valid edit
 9249: command.  It is possible the edit command is not valid
 9250: in that case there are no log messages to indicate that.
 9251: 
 9252: =item Result of password change for  <username> pwchange_success
 9253: 
 9254: The password for <username> was
 9255: successfully changed.
 9256: 
 9257: =item Unable to open <user> passwd to change password
 9258: 
 9259: Could not rewrite the 
 9260: internal password file for a user
 9261: 
 9262: =item Result of password change for <user> : <result>
 9263: 
 9264: A unix password change for <user> was attempted 
 9265: and the pipe returned <result>  
 9266: 
 9267: =item LWP GET: <message> for <fname> (<remoteurl>)
 9268: 
 9269: The lightweight process fetch for a resource failed
 9270: with <message> the local filename that should
 9271: have existed/been created was  <fname> the
 9272: corresponding URI: <remoteurl>  This is emitted in several
 9273: places.
 9274: 
 9275: =item Unable to move <transname> to <destname>     
 9276: 
 9277: From fetch_user_file_handler - the user file was replicated but could not
 9278: be mv'd to its final location.
 9279: 
 9280: =item Looking for <domain> <username>              
 9281: 
 9282: From user_has_session_handler - This should be a Debug call instead
 9283: it indicates lond is about to check whether the specified user has a 
 9284: session active on the specified domain on the local host.
 9285: 
 9286: =item Client <ip> (<name>) hanging up: <input>     
 9287: 
 9288: lond has been asked to exit by its client.  The <ip> and <name> identify the
 9289: client systemand <input> is the full exit command sent to the server.
 9290: 
 9291: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
 9292: 
 9293: A lond child terminated.  NOte that this termination can also occur when the
 9294: child receives the QUIT or DIE signals.  <pid> is the process id of the child,
 9295: <hostname> the host lond is working for, and <message> the reason the child died
 9296: to the best of our ability to get it (I would guess that any numeric value
 9297: represents and errno value).  This is immediately followed by
 9298: 
 9299: =item  Famous last words: Catching exception - <log> 
 9300: 
 9301: Where log is some recent information about the state of the child.
 9302: 
 9303: =item Red CRITICAL: TIME OUT <pid>                     
 9304: 
 9305: Some timeout occured for server <pid>.  THis is normally a timeout on an LWP
 9306: doing an HTTP::GET.
 9307: 
 9308: =item child <pid> died                              
 9309: 
 9310: The reaper caught a SIGCHILD for the lond child process <pid>
 9311: This should be modified to also display the IP of the dying child
 9312: $children{$pid}
 9313: 
 9314: =item Unknown child 0 died                           
 9315: A child died but the wait for it returned a pid of zero which really should not
 9316: ever happen. 
 9317: 
 9318: =item Child <which> - <pid> looks like we missed it's death 
 9319: 
 9320: When a sigchild is received, the reaper process checks all children to see if they are
 9321: alive.  If children are dying quite quickly, the lack of signal queuing can mean
 9322: that a signal hearalds the death of more than one child.  If so this message indicates
 9323: which other one died. <which> is the ip of a dead child
 9324: 
 9325: =item Free socket: <shutdownretval>                
 9326: 
 9327: The HUNTSMAN sub was called due to a SIGINT in a child process.  The socket is being shutdown.
 9328: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
 9329: to return anything. This is followed by: 
 9330: 
 9331: =item Red CRITICAL: Shutting down                       
 9332: 
 9333: Just prior to exit.
 9334: 
 9335: =item Free socket: <shutdownretval>                 
 9336: 
 9337: The HUPSMAN sub was called due to a SIGHUP.  all children get killsed, and lond execs itself.
 9338: This is followed by:
 9339: 
 9340: =item (Red) CRITICAL: Restarting                         
 9341: 
 9342: lond is about to exec itself to restart.
 9343: 
 9344: =item (Blue) Updating connections                        
 9345: 
 9346: (In response to a USR2).  All the children (except the one for localhost)
 9347: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
 9348: 
 9349: =item (Blue) UpdateHosts killing child <pid> for ip <ip>   
 9350: 
 9351: Due to USR2 as above.
 9352: 
 9353: =item (Green) keeping child for ip <ip> (pid = <pid>)    
 9354: 
 9355: In response to USR2 as above, the child indicated is not being restarted because
 9356: it's assumed that we'll always need a child for the localhost.
 9357: 
 9358: 
 9359: =item Going to check on the children                
 9360: 
 9361: Parent is about to check on the health of the child processes.
 9362: Note that this is in response to a USR1 sent to the parent lond.
 9363: there may be one or more of the next two messages:
 9364: 
 9365: =item <pid> is dead                                 
 9366: 
 9367: A child that we have in our child hash as alive has evidently died.
 9368: 
 9369: =item  Child <pid> did not respond                   
 9370: 
 9371: In the health check the child <pid> did not update/produce a pid_.txt
 9372: file when sent it's USR1 signal.  That process is killed with a 9 signal, as it's
 9373: assumed to be hung in some un-fixable way.
 9374: 
 9375: =item Finished checking children                   
 9376: 
 9377: Master processs's USR1 processing is cojmplete.
 9378: 
 9379: =item (Red) CRITICAL: ------- Starting ------            
 9380: 
 9381: (There are more '-'s on either side).  Lond has forked itself off to 
 9382: form a new session and is about to start actual initialization.
 9383: 
 9384: =item (Green) Attempting to start child (<client>)       
 9385: 
 9386: Started a new child process for <client>.  Client is IO::Socket object
 9387: connected to the child.  This was as a result of a TCP/IP connection from a client.
 9388: 
 9389: =item Unable to determine who caller was, getpeername returned nothing
 9390: 
 9391: In child process initialization.  either getpeername returned undef or
 9392: a zero sized object was returned.  Processing continues, but in my opinion,
 9393: this should be cause for the child to exit.
 9394: 
 9395: =item Unable to determine clientip                  
 9396: 
 9397: In child process initialization.  The peer address from getpeername was not defined.
 9398: The client address is stored as "Unavailable" and processing continues.
 9399: 
 9400: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
 9401: 
 9402: In child initialization.  A good connectionw as received from <ip>.
 9403: 
 9404: =over 2
 9405: 
 9406: =item <name> 
 9407: 
 9408: is the name of the client from hosts.tab.
 9409: 
 9410: =item <type> 
 9411: 
 9412: Is the connection type which is either 
 9413: 
 9414: =over 2
 9415: 
 9416: =item manager 
 9417: 
 9418: The connection is from a manager node, not in hosts.tab
 9419: 
 9420: =item client  
 9421: 
 9422: the connection is from a non-manager in the hosts.tab
 9423: 
 9424: =item both
 9425: 
 9426: The connection is from a manager in the hosts.tab.
 9427: 
 9428: =back
 9429: 
 9430: =back
 9431: 
 9432: =item (Blue) Certificates not installed -- trying insecure auth
 9433: 
 9434: One of the certificate file, key file or
 9435: certificate authority file could not be found for a client attempting
 9436: SSL connection intiation.  COnnection will be attemptied in in-secure mode.
 9437: (this would be a system with an up to date lond that has not gotten a 
 9438: certificate from us).
 9439: 
 9440: =item (Green)  Successful local authentication            
 9441: 
 9442: A local connection successfully negotiated the encryption key. 
 9443: In this case the IDEA key is in a file (that is hopefully well protected).
 9444: 
 9445: =item (Green) Successful ssl authentication with <client>  
 9446: 
 9447: The client (<client> is the peer's name in hosts.tab), has successfully
 9448: negotiated an SSL connection with this child process.
 9449: 
 9450: =item (Green) Successful insecure authentication with <client>
 9451: 
 9452: 
 9453: The client has successfully negotiated an  insecure connection withthe child process.
 9454: 
 9455: =item (Yellow) Attempted insecure connection disallowed    
 9456: 
 9457: The client attempted and failed to successfully negotiate a successful insecure
 9458: connection.  This can happen either because the variable londAllowInsecure is false
 9459: or undefined, or becuse the child did not successfully echo back the challenge
 9460: string.
 9461: 
 9462: 
 9463: =back
 9464: 
 9465: =back
 9466: 
 9467: 
 9468: =cut

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