File:  [LON-CAPA] / loncom / lond
Revision 1.566: download - view: text, annotated - select for diffs
Wed Mar 31 02:19:58 2021 UTC (3 years ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Support institutional policies which allow a Course Coordinator affiliated
  with a cross-listed course to be automatically listed as a co-owner in a
  course.

    1: #!/usr/bin/perl
    2: # The LearningOnline Network
    3: # lond "LON Daemon" Server (port "LOND" 5663)
    4: #
    5: # $Id: lond,v 1.566 2021/03/31 02:19:58 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.566 $'; #' stupid emacs
   69: my $remoteVERSION;
   70: my $currenthostid="default";
   71: my $currentdomainid;
   72: 
   73: my $client;
   74: my $clientip;			# IP address of client.
   75: my $clientname;			# LonCAPA name of client.
   76: my $clientversion;              # LonCAPA version running on client.
   77: my $clienthomedom;              # LonCAPA domain of homeID for client. 
   78: my $clientintdom;               # LonCAPA "internet domain" for client.
   79: my $clientsamedom;              # LonCAPA domain same for this host 
   80:                                 # and client.
   81: my $clientsameinst;             # LonCAPA "internet domain" same for 
   82:                                 # this host and client.
   83: my $clientremoteok;             # Current domain permits hosting on client
   84:                                 # (not set if host and client share "internet domain").
   85:                                 # Values are 0 or 1; 1 if allowed.
   86: my %clientprohibited;           # Commands from client prohibited for domain's
   87:                                 # users.
   88: 
   89: my $server;
   90: 
   91: my $keymode;
   92: 
   93: my $cipher;			# Cipher key negotiated with client
   94: my $tmpsnum = 0;		# Id of tmpputs.
   95: 
   96: # 
   97: #   Connection type is:
   98: #      client                   - All client actions are allowed
   99: #      manager                  - only management functions allowed.
  100: #      both                     - Both management and client actions are allowed
  101: #
  102: 
  103: my $ConnectionType;
  104: 
  105: my %managers;			# Ip -> manager names
  106: 
  107: my %perlvar;			# Will have the apache conf defined perl vars.
  108: 
  109: my %secureconf;                 # Will have requirements for security 
  110:                                 # of lond connections
  111: 
  112: my %crlchecked;                 # Will contain clients for which the client's SSL
  113:                                 # has been checked against the cluster's Certificate
  114:                                 # Revocation List.
  115: 
  116: my $dist;
  117: 
  118: #
  119: #   The hash below is used for command dispatching, and is therefore keyed on the request keyword.
  120: #    Each element of the hash contains a reference to an array that contains:
  121: #          A reference to a sub that executes the request corresponding to the keyword.
  122: #          A flag that is true if the request must be encoded to be acceptable.
  123: #          A mask with bits as follows:
  124: #                      CLIENT_OK    - Set when the function is allowed by ordinary clients
  125: #                      MANAGER_OK   - Set when the function is allowed to manager clients.
  126: #
  127: my $CLIENT_OK  = 1;
  128: my $MANAGER_OK = 2;
  129: my %Dispatcher;
  130: 
  131: 
  132: #
  133: #  The array below are password error strings."
  134: #
  135: my $lastpwderror    = 13;		# Largest error number from lcpasswd.
  136: my @passwderrors = ("ok",
  137: 		   "pwchange_failure - lcpasswd must be run as user 'www'",
  138: 		   "pwchange_failure - lcpasswd got incorrect number of arguments",
  139: 		   "pwchange_failure - lcpasswd did not get the right nubmer of input text lines",
  140: 		   "pwchange_failure - lcpasswd too many simultaneous pwd changes in progress",
  141: 		   "pwchange_failure - lcpasswd User does not exist.",
  142: 		   "pwchange_failure - lcpasswd Incorrect current passwd",
  143: 		   "pwchange_failure - lcpasswd Unable to su to root.",
  144: 		   "pwchange_failure - lcpasswd Cannot set new passwd.",
  145: 		   "pwchange_failure - lcpasswd Username has invalid characters",
  146: 		   "pwchange_failure - lcpasswd Invalid characters in password",
  147: 		   "pwchange_failure - lcpasswd User already exists", 
  148:                    "pwchange_failure - lcpasswd Something went wrong with user addition.",
  149: 		   "pwchange_failure - lcpasswd Password mismatch",
  150: 		   "pwchange_failure - lcpasswd Error filename is invalid");
  151: 
  152: 
  153: # This array are the errors from lcinstallfile:
  154: 
  155: my @installerrors = ("ok",
  156: 		     "Initial user id of client not that of www",
  157: 		     "Usage error, not enough command line arguments",
  158: 		     "Source filename does not exist",
  159: 		     "Destination filename does not exist",
  160: 		     "Some file operation failed",
  161: 		     "Invalid table filename."
  162: 		     );
  163: 
  164: #
  165: # The %trust hash classifies commands according to type of trust 
  166: # required for execution of the command.
  167: #
  168: # When clients from a different institution request execution of a
  169: # particular command, the trust settings for that institution set
  170: # for this domain (or default domain for a multi-domain server) will
  171: # be checked to see if running the command is allowed.
  172: #
  173: # Trust types which depend on the "Trust" domain configuration
  174: # for the machine's default domain are:
  175: #
  176: # content   ("Access to this domain's content by others")
  177: # shared    ("Access to other domain's content by this domain")
  178: # enroll    ("Enrollment in this domain's courses by others")
  179: # coaurem   ("Co-author roles for this domain's users elsewhere")
  180: # othcoau   ("Co-author roles in this domain for others")
  181: # domroles  ("Domain roles in this domain assignable to others")
  182: # catalog   ("Course Catalog for this domain displayed elsewhere")
  183: # reqcrs    ("Requests for creation of courses in this domain by others")
  184: # msg       ("Users in other domains can send messages to this domain")
  185: # 
  186: # Trust type which depends on the User Session Hosting (remote) 
  187: # domain configuration for machine's default domain is: "remote".
  188: #
  189: # Trust types which depend on contents of manager.tab in 
  190: # /home/httpd/lonTabs is: "manageronly".
  191: # 
  192: # Trust type which requires client to share the same LON-CAPA
  193: # "internet domain" (i.e., same institution as this server) is:
  194: # "institutiononly".
  195: #
  196: 
  197: my %trust = (
  198:                auth => {remote => 1},
  199:                autocreatepassword => {remote => 1},
  200:                autocrsreqchecks => {remote => 1, reqcrs => 1},
  201:                autocrsrequpdate => {remote => 1},
  202:                autocrsreqvalidation => {remote => 1},
  203:                autogetsections => {remote => 1},
  204:                autoinstcodedefaults => {remote => 1, catalog => 1},
  205:                autoinstcodeformat => {remote => 1, catalog => 1},
  206:                autonewcourse => {remote => 1, reqcrs => 1},
  207:                autophotocheck => {remote => 1, enroll => 1},
  208:                autophotochoice => {remote => 1},
  209:                autophotopermission => {remote => 1, enroll => 1},
  210:                autopossibleinstcodes => {remote => 1, reqcrs => 1},
  211:                autoretrieve => {remote => 1, enroll => 1, catalog => 1},
  212:                autorun => {remote => 1, enroll => 1, reqcrs => 1},
  213:                autovalidateclass_sec => {catalog => 1},
  214:                autovalidatecourse => {remote => 1, enroll => 1},
  215:                autovalidateinstcode => {domroles => 1, remote => 1, enroll => 1},
  216:                autovalidateinstcrosslist => {remote => 1, enroll => 1},
  217:                changeuserauth => {remote => 1, domroles => 1},
  218:                chatretr => {remote => 1, enroll => 1},
  219:                chatsend => {remote => 1, enroll => 1},
  220:                courseiddump => {remote => 1, domroles => 1, enroll => 1},
  221:                courseidput => {remote => 1, domroles => 1, enroll => 1},
  222:                courseidputhash => {remote => 1, domroles => 1, enroll => 1},
  223:                courselastaccess => {remote => 1, domroles => 1, enroll => 1},
  224:                coursesessions => {institutiononly => 1},
  225:                currentauth => {remote => 1, domroles => 1, enroll => 1},
  226:                currentdump => {remote => 1, enroll => 1},
  227:                currentversion => {remote=> 1, content => 1},
  228:                dcmaildump => {remote => 1, domroles => 1},
  229:                dcmailput => {remote => 1, domroles => 1},
  230:                del => {remote => 1, domroles => 1, enroll => 1, content => 1},
  231:                delbalcookie => {institutiononly => 1},
  232:                delusersession => {institutiononly => 1},
  233:                deldom => {remote => 1, domroles => 1}, # not currently used
  234:                devalidatecache => {institutiononly => 1},
  235:                domroleput => {remote => 1, enroll => 1},
  236:                domrolesdump => {remote => 1, catalog => 1},
  237:                du => {remote => 1, enroll => 1},
  238:                du2 => {remote => 1, enroll => 1},
  239:                dump => {remote => 1, enroll => 1, domroles => 1},
  240:                edit => {institutiononly => 1},  #not used currently
  241:                eget => {remote => 1, domroles => 1, enroll => 1}, #not used currently
  242:                egetdom => {remote => 1, domroles => 1, enroll => 1, },
  243:                ekey => {anywhere => 1},
  244:                exit => {anywhere => 1},
  245:                fetchuserfile => {remote => 1, enroll => 1},
  246:                get => {remote => 1, domroles => 1, enroll => 1},
  247:                getdom => {anywhere => 1},
  248:                home => {anywhere => 1},
  249:                iddel => {remote => 1, enroll => 1},
  250:                idget => {remote => 1, enroll => 1},
  251:                idput => {remote => 1, domroles => 1, enroll => 1},
  252:                inc => {remote => 1, enroll => 1},
  253:                init => {anywhere => 1},
  254:                inst_usertypes => {remote => 1, domroles => 1, enroll => 1},
  255:                instemailrules => {remote => 1, domroles => 1},
  256:                instidrulecheck => {remote => 1, domroles => 1,},
  257:                instidrules => {remote => 1, domroles => 1,},
  258:                instrulecheck => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
  259:                instselfcreatecheck => {institutiononly => 1},
  260:                instuserrules => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
  261:                keys => {remote => 1,},
  262:                load => {anywhere => 1},
  263:                log => {anywhere => 1},
  264:                ls => {remote => 1, enroll => 1, content => 1,},
  265:                ls2 => {remote => 1, enroll => 1, content => 1,},
  266:                ls3 => {remote => 1, enroll => 1, content => 1,},
  267:                makeuser => {remote => 1, enroll => 1, domroles => 1,},
  268:                mkdiruserfile => {remote => 1, enroll => 1,},
  269:                newput => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1,},
  270:                passwd => {remote => 1},
  271:                ping => {anywhere => 1},
  272:                pong => {anywhere => 1},
  273:                pushfile => {manageronly => 1},
  274:                put => {remote => 1, enroll => 1, domroles => 1, msg => 1, content => 1, shared => 1},
  275:                putdom => {remote => 1, domroles => 1,},
  276:                putstore => {remote => 1, enroll => 1},
  277:                queryreply => {anywhere => 1},
  278:                querysend => {anywhere => 1},
  279:                querysend_activitylog => {remote => 1},
  280:                querysend_allusers => {remote => 1, domroles => 1},
  281:                querysend_courselog => {remote => 1},
  282:                querysend_fetchenrollment => {remote => 1},
  283:                querysend_getinstuser => {remote => 1},
  284:                querysend_getmultinstusers => {remote => 1},
  285:                querysend_instdirsearch => {remote => 1, domroles => 1, coaurem => 1},
  286:                querysend_institutionalphotos => {remote => 1},
  287:                querysend_portfolio_metadata => {remote => 1, content => 1},
  288:                querysend_userlog => {remote => 1, domroles => 1},
  289:                querysend_usersearch => {remote => 1, enroll => 1, coaurem => 1},
  290:                quit => {anywhere => 1},
  291:                readlonnetglobal => {institutiononly => 1},
  292:                reinit => {manageronly => 1}, #not used currently
  293:                removeuserfile => {remote => 1, enroll => 1},
  294:                renameuserfile => {remote => 1,},
  295:                restore => {remote => 1, enroll => 1, reqcrs => 1,},
  296:                rolesdel => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
  297:                rolesput => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
  298:                servercerts => {institutiononly => 1},
  299:                serverdistarch => {anywhere => 1},
  300:                serverhomeID => {anywhere => 1},
  301:                serverloncaparev => {anywhere => 1},
  302:                servertimezone => {remote => 1, enroll => 1},
  303:                setannounce => {remote => 1, domroles => 1},
  304:                sethost => {anywhere => 1},
  305:                store => {remote => 1, enroll => 1, reqcrs => 1,},
  306:                studentphoto => {remote => 1, enroll => 1},
  307:                sub => {content => 1,},
  308:                tmpdel => {institutiononly => 1},
  309:                tmpget => {institutiononly => 1},
  310:                tmpput => {remote => 1, othcoau => 1},
  311:                tokenauthuserfile => {anywhere => 1},
  312:                unsub => {content => 1,},
  313:                update => {shared => 1},
  314:                updatebalcookie => {institutiononly => 1},
  315:                updateclickers => {remote => 1},
  316:                userhassession => {anywhere => 1},
  317:                userload => {anywhere => 1},
  318:                version => {anywhere => 1}, #not used
  319:             );
  320: 
  321: #
  322: #   Statistics that are maintained and dislayed in the status line.
  323: #
  324: my $Transactions = 0;		# Number of attempted transactions.
  325: my $Failures     = 0;		# Number of transcations failed.
  326: 
  327: #   ResetStatistics: 
  328: #      Resets the statistics counters:
  329: #
  330: sub ResetStatistics {
  331:     $Transactions = 0;
  332:     $Failures     = 0;
  333: }
  334: 
  335: #------------------------------------------------------------------------
  336: #
  337: #   LocalConnection
  338: #     Completes the formation of a locally authenticated connection.
  339: #     This function will ensure that the 'remote' client is really the
  340: #     local host.  If not, the connection is closed, and the function fails.
  341: #     If so, initcmd is parsed for the name of a file containing the
  342: #     IDEA session key.  The fie is opened, read, deleted and the session
  343: #     key returned to the caller.
  344: #
  345: # Parameters:
  346: #   $Socket      - Socket open on client.
  347: #   $initcmd     - The full text of the init command.
  348: #
  349: # Returns:
  350: #     IDEA session key on success.
  351: #     undef on failure.
  352: #
  353: sub LocalConnection {
  354:     my ($Socket, $initcmd) = @_;
  355:     Debug("Attempting local connection: $initcmd client: $clientip");
  356:     if($clientip ne "127.0.0.1") {
  357: 	&logthis('<font color="red"> LocalConnection rejecting non local: '
  358: 		 ."$clientip ne 127.0.0.1 </font>");
  359: 	close $Socket;
  360: 	return undef;
  361:     }  else {
  362: 	chomp($initcmd);	# Get rid of \n in filename.
  363: 	my ($init, $type, $name) = split(/:/, $initcmd);
  364: 	Debug(" Init command: $init $type $name ");
  365: 
  366: 	# Require that $init = init, and $type = local:  Otherwise
  367: 	# the caller is insane:
  368: 
  369: 	if(($init ne "init") && ($type ne "local")) {
  370: 	    &logthis('<font color = "red"> LocalConnection: caller is insane! '
  371: 		     ."init = $init, and type = $type </font>");
  372: 	    close($Socket);;
  373: 	    return undef;
  374: 		
  375: 	}
  376: 	#  Now get the key filename:
  377: 
  378: 	my $IDEAKey = lonlocal::ReadKeyFile($name);
  379: 	return $IDEAKey;
  380:     }
  381: }
  382: #------------------------------------------------------------------------------
  383: #
  384: #  SSLConnection
  385: #   Completes the formation of an ssh authenticated connection. The
  386: #   socket is promoted to an ssl socket.  If this promotion and the associated
  387: #   certificate exchange are successful, the IDEA key is generated and sent
  388: #   to the remote peer via the SSL tunnel. The IDEA key is also returned to
  389: #   the caller after the SSL tunnel is torn down.
  390: #
  391: # Parameters:
  392: #   Name              Type             Purpose
  393: #   $Socket          IO::Socket::INET  Plaintext socket.
  394: #
  395: # Returns:
  396: #    IDEA key on success.
  397: #    undef on failure.
  398: #
  399: sub SSLConnection {
  400:     my $Socket   = shift;
  401: 
  402:     Debug("SSLConnection: ");
  403:     my $KeyFile         = lonssl::KeyFile();
  404:     if(!$KeyFile) {
  405: 	my $err = lonssl::LastError();
  406: 	&logthis("<font color=\"red\"> CRITICAL"
  407: 		 ."Can't get key file $err </font>");
  408: 	return undef;
  409:     }
  410:     my ($CACertificate,
  411: 	$Certificate) = lonssl::CertificateFile();
  412: 
  413: 
  414:     # If any of the key, certificate or certificate authority 
  415:     # certificate filenames are not defined, this can't work.
  416: 
  417:     if((!$Certificate) || (!$CACertificate)) {
  418: 	my $err = lonssl::LastError();
  419: 	&logthis("<font color=\"red\"> CRITICAL"
  420: 		 ."Can't get certificates: $err </font>");
  421: 
  422: 	return undef;
  423:     }
  424:     Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
  425: 
  426:     # Indicate to our peer that we can procede with
  427:     # a transition to ssl authentication:
  428: 
  429:     print $Socket "ok:ssl\n";
  430: 
  431:     Debug("Approving promotion -> ssl");
  432:     #  And do so:
  433: 
  434:     my $CRLFile;
  435:     unless ($crlchecked{$clientname}) {
  436:         $CRLFile = lonssl::CRLFile();
  437:         $crlchecked{$clientname} = 1;
  438:     }
  439: 
  440:     my $SSLSocket = lonssl::PromoteServerSocket($Socket,
  441: 						$CACertificate,
  442: 						$Certificate,
  443: 						$KeyFile,
  444: 						$clientname,
  445:                                                 $CRLFile,
  446:                                                 $clientversion);
  447:     if(! ($SSLSocket) ) {	# SSL socket promotion failed.
  448: 	my $err = lonssl::LastError();
  449: 	&logthis("<font color=\"red\"> CRITICAL "
  450: 		 ."SSL Socket promotion failed: $err </font>");
  451: 	return undef;
  452:     }
  453:     Debug("SSL Promotion successful");
  454: 
  455:     # 
  456:     #  The only thing we'll use the socket for is to send the IDEA key
  457:     #  to the peer:
  458: 
  459:     my $Key = lonlocal::CreateCipherKey();
  460:     print $SSLSocket "$Key\n";
  461: 
  462:     lonssl::Close($SSLSocket); 
  463: 
  464:     Debug("Key exchange complete: $Key");
  465: 
  466:     return $Key;
  467: }
  468: #
  469: #     InsecureConnection: 
  470: #        If insecure connections are allowd,
  471: #        exchange a challenge with the client to 'validate' the
  472: #        client (not really, but that's the protocol):
  473: #        We produce a challenge string that's sent to the client.
  474: #        The client must then echo the challenge verbatim to us.
  475: #
  476: #  Parameter:
  477: #      Socket      - Socket open on the client.
  478: #  Returns:
  479: #      1           - success.
  480: #      0           - failure (e.g.mismatch or insecure not allowed).
  481: #
  482: sub InsecureConnection {
  483:     my $Socket  =  shift;
  484: 
  485:     #   Don't even start if insecure connections are not allowed.
  486:     #   return 0 if Insecure connections not allowed.
  487:     #
  488:     if (ref($secureconf{'connfrom'}) eq 'HASH') {
  489:         if ($clientsamedom) {
  490:             if ($secureconf{'connfrom'}{'dom'} eq 'req') {
  491:                 return 0;
  492:             } 
  493:         } elsif ($clientsameinst) {
  494:             if ($secureconf{'connfrom'}{'intdom'} eq 'req') {
  495:                 return 0;
  496:             }
  497:         } else {
  498:             if ($secureconf{'connfrom'}{'other'} eq 'req') {
  499:                 return 0;
  500:             }
  501:         }
  502:     } elsif (!$perlvar{londAllowInsecure}) {
  503: 	return 0;
  504:     }
  505: 
  506:     #   Fabricate a challenge string and send it..
  507: 
  508:     my $challenge = "$$".time;	# pid + time.
  509:     print $Socket "$challenge\n";
  510:     &status("Waiting for challenge reply");
  511: 
  512:     my $answer = <$Socket>;
  513:     $answer    =~s/\W//g;
  514:     if($challenge eq $answer) {
  515: 	return 1;
  516:     } else {
  517: 	logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
  518: 	&status("No challenge reqply");
  519: 	return 0;
  520:     }
  521:     
  522: 
  523: }
  524: #
  525: #   Safely execute a command (as long as it's not a shel command and doesn
  526: #   not require/rely on shell escapes.   The function operates by doing a
  527: #   a pipe based fork and capturing stdout and stderr  from the pipe.
  528: #
  529: # Formal Parameters:
  530: #     $line                    - A line of text to be executed as a command.
  531: # Returns:
  532: #     The output from that command.  If the output is multiline the caller
  533: #     must know how to split up the output.
  534: #
  535: #
  536: sub execute_command {
  537:     my ($line)    = @_;
  538:     my @words     = split(/\s/, $line);	# Bust the command up into words.
  539:     my $output    = "";
  540: 
  541:     my $pid = open(CHILD, "-|");
  542:     
  543:     if($pid) {			# Parent process
  544: 	Debug("In parent process for execute_command");
  545: 	my @data = <CHILD>;	# Read the child's outupt...
  546: 	close CHILD;
  547: 	foreach my $output_line (@data) {
  548: 	    Debug("Adding $output_line");
  549: 	    $output .= $output_line; # Presumably has a \n on it.
  550: 	}
  551: 
  552:     } else {			# Child process
  553: 	close (STDERR);
  554: 	open  (STDERR, ">&STDOUT");# Combine stderr, and stdout...
  555: 	exec(@words);		# won't return.
  556:     }
  557:     return $output;
  558: }
  559: 
  560: 
  561: #   GetCertificate: Given a transaction that requires a certificate,
  562: #   this function will extract the certificate from the transaction
  563: #   request.  Note that at this point, the only concept of a certificate
  564: #   is the hostname to which we are connected.
  565: #
  566: #   Parameter:
  567: #      request   - The request sent by our client (this parameterization may
  568: #                  need to change when we really use a certificate granting
  569: #                  authority.
  570: #
  571: sub GetCertificate {
  572:     my $request = shift;
  573: 
  574:     return $clientip;
  575: }
  576: 
  577: #
  578: #   Return true if client is a manager.
  579: #
  580: sub isManager {
  581:     return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
  582: }
  583: #
  584: #   Return tru if client can do client functions
  585: #
  586: sub isClient {
  587:     return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
  588: }
  589: 
  590: 
  591: #
  592: #   ReadManagerTable: Reads in the current manager table. For now this is
  593: #                     done on each manager authentication because:
  594: #                     - These authentications are not frequent
  595: #                     - This allows dynamic changes to the manager table
  596: #                       without the need to signal to the lond.
  597: #
  598: sub ReadManagerTable {
  599: 
  600:     &Debug("Reading manager table");
  601:     #   Clean out the old table first..
  602: 
  603:    foreach my $key (keys %managers) {
  604:       delete $managers{$key};
  605:    }
  606: 
  607:    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
  608:    if (!open (MANAGERS, $tablename)) {
  609:        my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
  610:        if (&Apache::lonnet::is_LC_dns($hostname)) {
  611:            &logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
  612:        }
  613:        return;
  614:    }
  615:    while(my $host = <MANAGERS>) {
  616:       chomp($host);
  617:       if ($host =~ "^#") {                  # Comment line.
  618:          next;
  619:       }
  620:       if (!defined &Apache::lonnet::get_host_ip($host)) { # This is a non cluster member
  621: 	    #  The entry is of the form:
  622: 	    #    cluname:hostname
  623: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
  624: 	    #            the host key.
  625: 	    #  hostname- The dns name of the host.
  626: 	    #
  627:           my($cluname, $dnsname) = split(/:/, $host);
  628:           
  629:           my $ip = gethostbyname($dnsname);
  630:           if(defined($ip)) {                 # bad names don't deserve entry.
  631:             my $hostip = inet_ntoa($ip);
  632:             $managers{$hostip} = $cluname;
  633:             logthis('<font color="green"> registering manager '.
  634:                     "$dnsname as $cluname with $hostip </font>\n");
  635:          }
  636:       } else {
  637:          logthis('<font color="green"> existing host'." $host</font>\n");
  638:          $managers{&Apache::lonnet::get_host_ip($host)} = $host;  # Use info from cluster tab if cluster memeber
  639:       }
  640:    }
  641: }
  642: 
  643: #
  644: #  ValidManager: Determines if a given certificate represents a valid manager.
  645: #                in this primitive implementation, the 'certificate' is
  646: #                just the connecting loncapa client name.  This is checked
  647: #                against a valid client list in the configuration.
  648: #
  649: #                  
  650: sub ValidManager {
  651:     my $certificate = shift; 
  652: 
  653:     return isManager;
  654: }
  655: #
  656: #  CopyFile:  Called as part of the process of installing a 
  657: #             new configuration file.  This function copies an existing
  658: #             file to a backup file.
  659: # Parameters:
  660: #     oldfile  - Name of the file to backup.
  661: #     newfile  - Name of the backup file.
  662: # Return:
  663: #     0   - Failure (errno has failure reason).
  664: #     1   - Success.
  665: #
  666: sub CopyFile {
  667: 
  668:     my ($oldfile, $newfile) = @_;
  669: 
  670:     if (! copy($oldfile,$newfile)) {
  671:         return 0;
  672:     }
  673:     chmod(0660, $newfile);
  674:     return 1;
  675: }
  676: #
  677: #  Host files are passed out with externally visible host IPs.
  678: #  If, for example, we are behind a fire-wall or NAT host, our 
  679: #  internally visible IP may be different than the externally
  680: #  visible IP.  Therefore, we always adjust the contents of the
  681: #  host file so that the entry for ME is the IP that we believe
  682: #  we have.  At present, this is defined as the entry that
  683: #  DNS has for us.  If by some chance we are not able to get a
  684: #  DNS translation for us, then we assume that the host.tab file
  685: #  is correct.  
  686: #    BUGBUGBUG - in the future, we really should see if we can
  687: #       easily query the interface(s) instead.
  688: # Parameter(s):
  689: #     contents    - The contents of the host.tab to check.
  690: # Returns:
  691: #     newcontents - The adjusted contents.
  692: #
  693: #
  694: sub AdjustHostContents {
  695:     my $contents  = shift;
  696:     my $adjusted;
  697:     my $me        = $perlvar{'lonHostID'};
  698: 
  699:     foreach my $line (split(/\n/,$contents)) {
  700: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/) ||
  701:              ($line =~ /^\s*\^/))) {
  702: 	    chomp($line);
  703: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
  704: 	    if ($id eq $me) {
  705: 		my $ip = gethostbyname($name);
  706: 		my $ipnew = inet_ntoa($ip);
  707: 		$ip = $ipnew;
  708: 		#  Reconstruct the host line and append to adjusted:
  709: 		
  710: 		my $newline = "$id:$domain:$role:$name:$ip";
  711: 		if($maxcon ne "") { # Not all hosts have loncnew tuning params
  712: 		    $newline .= ":$maxcon:$idleto:$mincon";
  713: 		}
  714: 		$adjusted .= $newline."\n";
  715: 		
  716: 	    } else {		# Not me, pass unmodified.
  717: 		$adjusted .= $line."\n";
  718: 	    }
  719: 	} else {                  # Blank or comment never re-written.
  720: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
  721: 	}
  722:     }
  723:     return $adjusted;
  724: }
  725: #
  726: #   InstallFile: Called to install an administrative file:
  727: #       - The file is created int a temp directory called <name>.tmp
  728: #       - lcinstall file is called to install the file.
  729: #         since the web app has no direct write access to the table directory
  730: #
  731: #  Parameters:
  732: #       Name of the file
  733: #       File Contents.
  734: #  Return:
  735: #      nonzero - success.
  736: #      0       - failure and $! has an errno.
  737: # Assumptions:
  738: #    File installtion is a relatively infrequent
  739: #
  740: sub InstallFile {
  741: 
  742:     my ($Filename, $Contents) = @_;
  743: #     my $TempFile = $Filename.".tmp";
  744:     my $exedir = $perlvar{'lonDaemons'};
  745:     my $tmpdir = $exedir.'/tmp/';
  746:     my $TempFile = $tmpdir."TempTableFile.tmp";
  747: 
  748:     #  Open the file for write:
  749: 
  750:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
  751:     if(!(defined $fh)) {
  752: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
  753: 	return 0;
  754:     }
  755:     #  write the contents of the file:
  756: 
  757:     print $fh ($Contents); 
  758:     $fh->close;			# In case we ever have a filesystem w. locking
  759: 
  760:     chmod(0664, $TempFile);	# Everyone can write it.
  761: 
  762:     # Use lcinstall file to put the file in the table directory...
  763: 
  764:     &Debug("Opening pipe to $exedir/lcinstallfile $TempFile $Filename");
  765:     my $pf = IO::File->new("| $exedir/lcinstallfile   $TempFile $Filename > $exedir/logs/lcinstallfile.log");
  766:     close $pf;
  767:     my $err = $?;
  768:     &Debug("Status is $err");
  769:     if ($err != 0) {
  770: 	my $msg = $err;
  771: 	if ($err < @installerrors) {
  772: 	    $msg = $installerrors[$err];
  773: 	}
  774: 	&logthis("Install failed for table file $Filename : $msg");
  775: 	return 0;
  776:     }
  777: 
  778:     # Remove the temp file:
  779: 
  780:     unlink($TempFile);
  781: 
  782:     return 1;
  783: }
  784: 
  785: 
  786: #
  787: #   ConfigFileFromSelector: converts a configuration file selector
  788: #                 into a configuration file pathname.
  789: #                 Supports the following file selectors: 
  790: #                 hosts, domain, dns_hosts, dns_domain  
  791: #
  792: #
  793: #  Parameters:
  794: #      selector  - Configuration file selector.
  795: #  Returns:
  796: #      Full path to the file or undef if the selector is invalid.
  797: #
  798: sub ConfigFileFromSelector {
  799:     my $selector   = shift;
  800:     my $tablefile;
  801: 
  802:     if ($selector eq 'loncapaCAcrl') {
  803:         my $tabledir = $perlvar{'lonCertificateDirectory'};
  804:         if (-d $tabledir) {
  805:             $tablefile =  $tabledir.'/'.$selector.'.pem';
  806:         }
  807:     } else {
  808:         my $tabledir = $perlvar{'lonTabDir'}.'/';
  809:         if (($selector eq "hosts") || ($selector eq "domain") || 
  810:             ($selector eq "dns_hosts") || ($selector eq "dns_domain")) {
  811: 	    $tablefile =  $tabledir.$selector.'.tab';
  812:         }
  813:     }
  814:     return $tablefile;
  815: }
  816: #
  817: #   PushFile:  Called to do an administrative push of a file.
  818: #              - Ensure the file being pushed is one we support.
  819: #              - Backup the old file to <filename.saved>
  820: #              - Separate the contents of the new file out from the
  821: #                rest of the request.
  822: #              - Write the new file.
  823: #  Parameter:
  824: #     Request - The entire user request.  This consists of a : separated
  825: #               string pushfile:tablename:contents.
  826: #     NOTE:  The contents may have :'s in it as well making things a bit
  827: #            more interesting... but not much.
  828: #  Returns:
  829: #     String to send to client ("ok" or "refused" if bad file).
  830: #
  831: sub PushFile {
  832:     my $request = shift;
  833:     my ($command, $filename, $contents) = split(":", $request, 3);
  834:     &Debug("PushFile");
  835:     
  836:     #  At this point in time, pushes for only the following tables and
  837:     #  CRL file are supported:
  838:     #   hosts.tab  ($filename eq host).
  839:     #   domain.tab ($filename eq domain).
  840:     #   dns_hosts.tab ($filename eq dns_host).
  841:     #   dns_domain.tab ($filename eq dns_domain).
  842:     #   loncapaCAcrl.pem ($filename eq loncapaCAcrl).
  843:     # Construct the destination filename or reject the request.
  844:     #
  845:     # lonManage is supposed to ensure this, however this session could be
  846:     # part of some elaborate spoof that managed somehow to authenticate.
  847:     #
  848: 
  849: 
  850:     my $tablefile = ConfigFileFromSelector($filename);
  851:     if(! (defined $tablefile)) {
  852: 	return "refused";
  853:     }
  854: 
  855:     #  If the file being pushed is the host file, we adjust the entry for ourself so that the
  856:     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
  857:     #  to conceive of conditions where we don't have a DNS entry locally.  This is possible in a 
  858:     #  network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
  859:     #  that possibilty.
  860: 
  861:     if($filename eq "host") {
  862: 	$contents = AdjustHostContents($contents);
  863:     } elsif (($filename eq 'dns_host') || ($filename eq 'dns_domain') ||
  864:              ($filename eq 'loncapaCAcrl')) {
  865:         if ($contents eq '') {
  866:             &logthis('<font color="red"> Pushfile: unable to install '
  867:                     .$tablefile." - no data received from push. </font>");
  868:             return 'error: push had no data';
  869:         }
  870:         if (&Apache::lonnet::get_host_ip($clientname)) {
  871:             my $clienthost = &Apache::lonnet::hostname($clientname);
  872:             if ($managers{$clientip} eq $clientname) {
  873:                 my $clientprotocol = $Apache::lonnet::protocol{$clientname};
  874:                 $clientprotocol = 'http' if ($clientprotocol ne 'https');
  875:                 my $url;
  876:                 if ($filename eq 'loncapaCAcrl') {
  877:                     $url = '/adm/dns/loncapaCRL';
  878:                 } else {
  879:                     $url = '/adm/'.$filename;
  880:                     $url =~ s{_}{/};
  881:                 }
  882:                 my $request=new HTTP::Request('GET',"$clientprotocol://$clienthost$url");
  883:                 my $response = LONCAPA::LWPReq::makerequest($clientname,$request,'',\%perlvar,60,0);
  884:                 if ($response->is_error()) {
  885:                     &logthis('<font color="red"> Pushfile: unable to install '
  886:                             .$tablefile." - error attempting to pull data. </font>");
  887:                     return 'error: pull failed';
  888:                 } else {
  889:                     my $result = $response->content;
  890:                     chomp($result);
  891:                     unless ($result eq $contents) {
  892:                         &logthis('<font color="red"> Pushfile: unable to install '
  893:                                 .$tablefile." - pushed data and pulled data differ. </font>");
  894:                         my $pushleng = length($contents);
  895:                         my $pullleng = length($result);
  896:                         if ($pushleng != $pullleng) {
  897:                             return "error: $pushleng vs $pullleng bytes";
  898:                         } else {
  899:                             return "error: mismatch push and pull";
  900:                         }
  901:                     }
  902:                 }
  903:             }
  904:         }
  905:     }
  906: 
  907:     #  Install the new file:
  908: 
  909:     &logthis("Installing new $tablefile contents:\n$contents");
  910:     if(!InstallFile($tablefile, $contents)) {
  911: 	&logthis('<font color="red"> Pushfile: unable to install '
  912: 	 .$tablefile." $! </font>");
  913: 	return "error:$!";
  914:     } else {
  915: 	&logthis('<font color="green"> Installed new '.$tablefile
  916: 		 ." - transaction by: $clientname ($clientip)</font>");
  917:         my $adminmail = $perlvar{'lonAdmEMail'};
  918:         my $admindom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
  919:         if ($admindom ne '') {
  920:             my %domconfig =
  921:                 &Apache::lonnet::get_dom('configuration',['contacts'],$admindom);
  922:             if (ref($domconfig{'contacts'}) eq 'HASH') {
  923:                 if ($domconfig{'contacts'}{'adminemail'} ne '') {
  924:                     $adminmail = $domconfig{'contacts'}{'adminemail'};
  925:                 }
  926:             }
  927:         }
  928:         if ($adminmail =~ /^[^\@]+\@[^\@]+$/) {
  929:             my $msg = new Mail::Send;
  930:             $msg->to($adminmail);
  931:             $msg->subject('LON-CAPA DNS update on '.$perlvar{'lonHostID'});
  932:             $msg->add('Content-type','text/plain; charset=UTF-8');
  933:             if (my $fh = $msg->open()) {
  934:                 print $fh 'Update to '.$tablefile.' from Cluster Manager '.
  935:                           "$clientname ($clientip)\n";
  936:                 $fh->close;
  937:             }
  938:         }
  939:     }
  940: 
  941:     #  Indicate success:
  942:  
  943:     return "ok";
  944: 
  945: }
  946: 
  947: #
  948: #  Called to re-init either lonc or lond.
  949: #
  950: #  Parameters:
  951: #    request   - The full request by the client.  This is of the form
  952: #                reinit:<process>  
  953: #                where <process> is allowed to be either of 
  954: #                lonc or lond
  955: #
  956: #  Returns:
  957: #     The string to be sent back to the client either:
  958: #   ok         - Everything worked just fine.
  959: #   error:why  - There was a failure and why describes the reason.
  960: #
  961: #
  962: sub ReinitProcess {
  963:     my $request = shift;
  964: 
  965: 
  966:     # separate the request (reinit) from the process identifier and
  967:     # validate it producing the name of the .pid file for the process.
  968:     #
  969:     #
  970:     my ($junk, $process) = split(":", $request);
  971:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
  972:     if($process eq 'lonc') {
  973: 	$processpidfile = $processpidfile."lonc.pid";
  974: 	if (!open(PIDFILE, "< $processpidfile")) {
  975: 	    return "error:Open failed for $processpidfile";
  976: 	}
  977: 	my $loncpid = <PIDFILE>;
  978: 	close(PIDFILE);
  979: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
  980: 		."</font>");
  981: 	kill("USR2", $loncpid);
  982:     } elsif ($process eq 'lond') {
  983: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
  984: 	&UpdateHosts;			# Lond is us!!
  985:     } else {
  986: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
  987: 		 ."</font>");
  988: 	return "error:Invalid process identifier $process";
  989:     }
  990:     return 'ok';
  991: }
  992: #   Validate a line in a configuration file edit script:
  993: #   Validation includes:
  994: #     - Ensuring the command is valid.
  995: #     - Ensuring the command has sufficient parameters
  996: #   Parameters:
  997: #     scriptline - A line to validate (\n has been stripped for what it's worth).
  998: #
  999: #   Return:
 1000: #      0     - Invalid scriptline.
 1001: #      1     - Valid scriptline
 1002: #  NOTE:
 1003: #     Only the command syntax is checked, not the executability of the
 1004: #     command.
 1005: #
 1006: sub isValidEditCommand {
 1007:     my $scriptline = shift;
 1008: 
 1009:     #   Line elements are pipe separated:
 1010: 
 1011:     my ($command, $key, $newline)  = split(/\|/, $scriptline);
 1012:     &logthis('<font color="green"> isValideditCommand checking: '.
 1013: 	     "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
 1014:     
 1015:     if ($command eq "delete") {
 1016: 	#
 1017: 	#   key with no newline.
 1018: 	#
 1019: 	if( ($key eq "") || ($newline ne "")) {
 1020: 	    return 0;		# Must have key but no newline.
 1021: 	} else {
 1022: 	    return 1;		# Valid syntax.
 1023: 	}
 1024:     } elsif ($command eq "replace") {
 1025: 	#
 1026: 	#   key and newline:
 1027: 	#
 1028: 	if (($key eq "") || ($newline eq "")) {
 1029: 	    return 0;
 1030: 	} else {
 1031: 	    return 1;
 1032: 	}
 1033:     } elsif ($command eq "append") {
 1034: 	if (($key ne "") && ($newline eq "")) {
 1035: 	    return 1;
 1036: 	} else {
 1037: 	    return 0;
 1038: 	}
 1039:     } else {
 1040: 	return 0;		# Invalid command.
 1041:     }
 1042:     return 0;			# Should not get here!!!
 1043: }
 1044: #
 1045: #   ApplyEdit - Applies an edit command to a line in a configuration 
 1046: #               file.  It is the caller's responsiblity to validate the
 1047: #               edit line.
 1048: #   Parameters:
 1049: #      $directive - A single edit directive to apply.  
 1050: #                   Edit directives are of the form:
 1051: #                  append|newline      - Appends a new line to the file.
 1052: #                  replace|key|newline - Replaces the line with key value 'key'
 1053: #                  delete|key          - Deletes the line with key value 'key'.
 1054: #      $editor   - A config file editor object that contains the
 1055: #                  file being edited.
 1056: #
 1057: sub ApplyEdit {
 1058: 
 1059:     my ($directive, $editor) = @_;
 1060: 
 1061:     # Break the directive down into its command and its parameters
 1062:     # (at most two at this point.  The meaning of the parameters, if in fact
 1063:     #  they exist depends on the command).
 1064: 
 1065:     my ($command, $p1, $p2) = split(/\|/, $directive);
 1066: 
 1067:     if($command eq "append") {
 1068: 	$editor->Append($p1);	          # p1 - key p2 null.
 1069:     } elsif ($command eq "replace") {
 1070: 	$editor->ReplaceLine($p1, $p2);   # p1 - key p2 = newline.
 1071:     } elsif ($command eq "delete") {
 1072: 	$editor->DeleteLine($p1);         # p1 - key p2 null.
 1073:     } else {			          # Should not get here!!!
 1074: 	die "Invalid command given to ApplyEdit $command"
 1075:     }
 1076: }
 1077: #
 1078: # AdjustOurHost:
 1079: #           Adjusts a host file stored in a configuration file editor object
 1080: #           for the true IP address of this host. This is necessary for hosts
 1081: #           that live behind a firewall.
 1082: #           Those hosts have a publicly distributed IP of the firewall, but
 1083: #           internally must use their actual IP.  We assume that a given
 1084: #           host only has a single IP interface for now.
 1085: # Formal Parameters:
 1086: #     editor   - The configuration file editor to adjust.  This
 1087: #                editor is assumed to contain a hosts.tab file.
 1088: # Strategy:
 1089: #    - Figure out our hostname.
 1090: #    - Lookup the entry for this host.
 1091: #    - Modify the line to contain our IP
 1092: #    - Do a replace for this host.
 1093: sub AdjustOurHost {
 1094:     my $editor        = shift;
 1095: 
 1096:     # figure out who I am.
 1097: 
 1098:     my $myHostName    = $perlvar{'lonHostID'}; # LonCAPA hostname.
 1099: 
 1100:     #  Get my host file entry.
 1101: 
 1102:     my $ConfigLine    = $editor->Find($myHostName);
 1103:     if(! (defined $ConfigLine)) {
 1104: 	die "AdjustOurHost - no entry for me in hosts file $myHostName";
 1105:     }
 1106:     # figure out my IP:
 1107:     #   Use the config line to get my hostname.
 1108:     #   Use gethostbyname to translate that into an IP address.
 1109:     #
 1110:     my ($id,$domain,$role,$name,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
 1111:     #
 1112:     #  Reassemble the config line from the elements in the list.
 1113:     #  Note that if the loncnew items were not present before, they will
 1114:     #  be now even if they would be empty
 1115:     #
 1116:     my $newConfigLine = $id;
 1117:     foreach my $item ($domain, $role, $name, $maxcon, $idleto, $mincon) {
 1118: 	$newConfigLine .= ":".$item;
 1119:     }
 1120:     #  Replace the line:
 1121: 
 1122:     $editor->ReplaceLine($id, $newConfigLine);
 1123:     
 1124: }
 1125: #
 1126: #   ReplaceConfigFile:
 1127: #              Replaces a configuration file with the contents of a
 1128: #              configuration file editor object.
 1129: #              This is done by:
 1130: #              - Copying the target file to <filename>.old
 1131: #              - Writing the new file to <filename>.tmp
 1132: #              - Moving <filename.tmp>  -> <filename>
 1133: #              This laborious process ensures that the system is never without
 1134: #              a configuration file that's at least valid (even if the contents
 1135: #              may be dated).
 1136: #   Parameters:
 1137: #        filename   - Name of the file to modify... this is a full path.
 1138: #        editor     - Editor containing the file.
 1139: #
 1140: sub ReplaceConfigFile {
 1141:     
 1142:     my ($filename, $editor) = @_;
 1143: 
 1144:     CopyFile ($filename, $filename.".old");
 1145: 
 1146:     my $contents  = $editor->Get(); # Get the contents of the file.
 1147: 
 1148:     InstallFile($filename, $contents);
 1149: }
 1150: #   
 1151: #
 1152: #   Called to edit a configuration table  file
 1153: #   Parameters:
 1154: #      request           - The entire command/request sent by lonc or lonManage
 1155: #   Return:
 1156: #      The reply to send to the client.
 1157: #
 1158: sub EditFile {
 1159:     my $request = shift;
 1160: 
 1161:     #  Split the command into it's pieces:  edit:filetype:script
 1162: 
 1163:     my ($cmd, $filetype, $script) = split(/:/, $request,3);	# : in script
 1164: 
 1165:     #  Check the pre-coditions for success:
 1166: 
 1167:     if($cmd != "edit") {	# Something is amiss afoot alack.
 1168: 	return "error:edit request detected, but request != 'edit'\n";
 1169:     }
 1170:     if( ($filetype ne "hosts")  &&
 1171: 	($filetype ne "domain")) {
 1172: 	return "error:edit requested with invalid file specifier: $filetype \n";
 1173:     }
 1174: 
 1175:     #   Split the edit script and check it's validity.
 1176: 
 1177:     my @scriptlines = split(/\n/, $script);  # one line per element.
 1178:     my $linecount   = scalar(@scriptlines);
 1179:     for(my $i = 0; $i < $linecount; $i++) {
 1180: 	chomp($scriptlines[$i]);
 1181: 	if(!isValidEditCommand($scriptlines[$i])) {
 1182: 	    return "error:edit with bad script line: '$scriptlines[$i]' \n";
 1183: 	}
 1184:     }
 1185: 
 1186:     #   Execute the edit operation.
 1187:     #   - Create a config file editor for the appropriate file and 
 1188:     #   - execute each command in the script:
 1189:     #
 1190:     my $configfile = ConfigFileFromSelector($filetype);
 1191:     if (!(defined $configfile)) {
 1192: 	return "refused\n";
 1193:     }
 1194:     my $editor = ConfigFileEdit->new($configfile);
 1195: 
 1196:     for (my $i = 0; $i < $linecount; $i++) {
 1197: 	ApplyEdit($scriptlines[$i], $editor);
 1198:     }
 1199:     # If the file is the host file, ensure that our host is
 1200:     # adjusted to have our ip:
 1201:     #
 1202:     if($filetype eq "host") {
 1203: 	AdjustOurHost($editor);
 1204:     }
 1205:     #  Finally replace the current file with our file.
 1206:     #
 1207:     ReplaceConfigFile($configfile, $editor);
 1208: 
 1209:     return "ok\n";
 1210: }
 1211: 
 1212: #   read_profile
 1213: #
 1214: #   Returns a set of specific entries from a user's profile file.
 1215: #   this is a utility function that is used by both get_profile_entry and
 1216: #   get_profile_entry_encrypted.
 1217: #
 1218: # Parameters:
 1219: #    udom       - Domain in which the user exists.
 1220: #    uname      - User's account name (loncapa account)
 1221: #    namespace  - The profile namespace to open.
 1222: #    what       - A set of & separated queries.
 1223: # Returns:
 1224: #    If all ok: - The string that needs to be shipped back to the user.
 1225: #    If failure - A string that starts with error: followed by the failure
 1226: #                 reason.. note that this probabyl gets shipped back to the
 1227: #                 user as well.
 1228: #
 1229: sub read_profile {
 1230:     my ($udom, $uname, $namespace, $what) = @_;
 1231:     
 1232:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 1233: 				 &GDBM_READER());
 1234:     if ($hashref) {
 1235:         my @queries=split(/\&/,$what);
 1236:         if ($namespace eq 'roles') {
 1237:             @queries = map { &unescape($_); } @queries; 
 1238:         }
 1239:         my $qresult='';
 1240: 	
 1241: 	for (my $i=0;$i<=$#queries;$i++) {
 1242: 	    $qresult.="$hashref->{$queries[$i]}&";    # Presumably failure gives empty string.
 1243: 	}
 1244: 	$qresult=~s/\&$//;              # Remove trailing & from last lookup.
 1245: 	if (&untie_user_hash($hashref)) {
 1246: 	    return $qresult;
 1247: 	} else {
 1248: 	    return "error: ".($!+0)." untie (GDBM) Failed";
 1249: 	}
 1250:     } else {
 1251: 	if ($!+0 == 2) {
 1252: 	    return "error:No such file or GDBM reported bad block error";
 1253: 	} else {
 1254: 	    return "error: ".($!+0)." tie (GDBM) Failed";
 1255: 	}
 1256:     }
 1257: 
 1258: }
 1259: #--------------------- Request Handlers --------------------------------------------
 1260: #
 1261: #   By convention each request handler registers itself prior to the sub 
 1262: #   declaration:
 1263: #
 1264: 
 1265: #++
 1266: #
 1267: #  Handles ping requests.
 1268: #  Parameters:
 1269: #      $cmd    - the actual keyword that invoked us.
 1270: #      $tail   - the tail of the request that invoked us.
 1271: #      $replyfd- File descriptor connected to the client
 1272: #  Implicit Inputs:
 1273: #      $currenthostid - Global variable that carries the name of the host we are
 1274: #                       known as.
 1275: #  Returns:
 1276: #      1       - Ok to continue processing.
 1277: #      0       - Program should exit.
 1278: #  Side effects:
 1279: #      Reply information is sent to the client.
 1280: sub ping_handler {
 1281:     my ($cmd, $tail, $client) = @_;
 1282:     Debug("$cmd $tail $client .. $currenthostid:");
 1283:    
 1284:     Reply( $client,\$currenthostid,"$cmd:$tail");
 1285:    
 1286:     return 1;
 1287: }
 1288: &register_handler("ping", \&ping_handler, 0, 1, 1);       # Ping unencoded, client or manager.
 1289: 
 1290: #++
 1291: #
 1292: # Handles pong requests.  Pong replies with our current host id, and
 1293: #                         the results of a ping sent to us via our lonc.
 1294: #
 1295: # Parameters:
 1296: #      $cmd    - the actual keyword that invoked us.
 1297: #      $tail   - the tail of the request that invoked us.
 1298: #      $replyfd- File descriptor connected to the client
 1299: #  Implicit Inputs:
 1300: #      $currenthostid - Global variable that carries the name of the host we are
 1301: #                       connected to.
 1302: #  Returns:
 1303: #      1       - Ok to continue processing.
 1304: #      0       - Program should exit.
 1305: #  Side effects:
 1306: #      Reply information is sent to the client.
 1307: sub pong_handler {
 1308:     my ($cmd, $tail, $replyfd) = @_;
 1309: 
 1310:     my $reply=&Apache::lonnet::reply("ping",$clientname);
 1311:     &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail"); 
 1312:     return 1;
 1313: }
 1314: &register_handler("pong", \&pong_handler, 0, 1, 1);       # Pong unencoded, client or manager
 1315: 
 1316: #++
 1317: #      Called to establish an encrypted session key with the remote client.
 1318: #      Note that with secure lond, in most cases this function is never
 1319: #      invoked.  Instead, the secure session key is established either
 1320: #      via a local file that's locked down tight and only lives for a short
 1321: #      time, or via an ssl tunnel...and is generated from a bunch-o-random
 1322: #      bits from /dev/urandom, rather than the predictable pattern used by
 1323: #      by this sub.  This sub is only used in the old-style insecure
 1324: #      key negotiation.
 1325: # Parameters:
 1326: #      $cmd    - the actual keyword that invoked us.
 1327: #      $tail   - the tail of the request that invoked us.
 1328: #      $replyfd- File descriptor connected to the client
 1329: #  Implicit Inputs:
 1330: #      $currenthostid - Global variable that carries the name of the host
 1331: #                       known as.
 1332: #      $clientname    - Global variable that carries the name of the host we're connected to.
 1333: #  Returns:
 1334: #      1       - Ok to continue processing.
 1335: #      0       - Program should exit.
 1336: #  Implicit Outputs:
 1337: #      Reply information is sent to the client.
 1338: #      $cipher is set with a reference to a new IDEA encryption object.
 1339: #
 1340: sub establish_key_handler {
 1341:     my ($cmd, $tail, $replyfd) = @_;
 1342: 
 1343:     my $buildkey=time.$$.int(rand 100000);
 1344:     $buildkey=~tr/1-6/A-F/;
 1345:     $buildkey=int(rand 100000).$buildkey.int(rand 100000);
 1346:     my $key=$currenthostid.$clientname;
 1347:     $key=~tr/a-z/A-Z/;
 1348:     $key=~tr/G-P/0-9/;
 1349:     $key=~tr/Q-Z/0-9/;
 1350:     $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
 1351:     $key=substr($key,0,32);
 1352:     my $cipherkey=pack("H32",$key);
 1353:     $cipher=new IDEA $cipherkey;
 1354:     &Reply($replyfd, \$buildkey, "$cmd:$tail"); 
 1355:    
 1356:     return 1;
 1357: 
 1358: }
 1359: &register_handler("ekey", \&establish_key_handler, 0, 1,1);
 1360: 
 1361: #     Handler for the load command.  Returns the current system load average
 1362: #     to the requestor.
 1363: #
 1364: # Parameters:
 1365: #      $cmd    - the actual keyword that invoked us.
 1366: #      $tail   - the tail of the request that invoked us.
 1367: #      $replyfd- File descriptor connected to the client
 1368: #  Implicit Inputs:
 1369: #      $currenthostid - Global variable that carries the name of the host
 1370: #                       known as.
 1371: #      $clientname    - Global variable that carries the name of the host we're connected to.
 1372: #  Returns:
 1373: #      1       - Ok to continue processing.
 1374: #      0       - Program should exit.
 1375: #  Side effects:
 1376: #      Reply information is sent to the client.
 1377: sub load_handler {
 1378:     my ($cmd, $tail, $replyfd) = @_;
 1379: 
 1380: 
 1381: 
 1382:    # Get the load average from /proc/loadavg and calculate it as a percentage of
 1383:    # the allowed load limit as set by the perl global variable lonLoadLim
 1384: 
 1385:     my $loadavg;
 1386:     my $loadfile=IO::File->new('/proc/loadavg');
 1387:    
 1388:     $loadavg=<$loadfile>;
 1389:     $loadavg =~ s/\s.*//g;                      # Extract the first field only.
 1390:    
 1391:     my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
 1392: 
 1393:     &Reply( $replyfd, \$loadpercent, "$cmd:$tail");
 1394:    
 1395:     return 1;
 1396: }
 1397: &register_handler("load", \&load_handler, 0, 1, 0);
 1398: 
 1399: #
 1400: #   Process the userload request.  This sub returns to the client the current
 1401: #  user load average.  It can be invoked either by clients or managers.
 1402: #
 1403: # Parameters:
 1404: #      $cmd    - the actual keyword that invoked us.
 1405: #      $tail   - the tail of the request that invoked us.
 1406: #      $replyfd- File descriptor connected to the client
 1407: #  Implicit Inputs:
 1408: #      $currenthostid - Global variable that carries the name of the host
 1409: #                       known as.
 1410: #      $clientname    - Global variable that carries the name of the host we're connected to.
 1411: #  Returns:
 1412: #      1       - Ok to continue processing.
 1413: #      0       - Program should exit
 1414: # Implicit inputs:
 1415: #     whatever the userload() function requires.
 1416: #  Implicit outputs:
 1417: #     the reply is written to the client.
 1418: #
 1419: sub user_load_handler {
 1420:     my ($cmd, $tail, $replyfd) = @_;
 1421: 
 1422:     my $userloadpercent=&Apache::lonnet::userload();
 1423:     &Reply($replyfd, \$userloadpercent, "$cmd:$tail");
 1424:     
 1425:     return 1;
 1426: }
 1427: &register_handler("userload", \&user_load_handler, 0, 1, 0);
 1428: 
 1429: #   Process a request for the authorization type of a user:
 1430: #   (userauth).
 1431: #
 1432: # Parameters:
 1433: #      $cmd    - the actual keyword that invoked us.
 1434: #      $tail   - the tail of the request that invoked us.
 1435: #      $replyfd- File descriptor connected to the client
 1436: #  Returns:
 1437: #      1       - Ok to continue processing.
 1438: #      0       - Program should exit
 1439: # Implicit outputs:
 1440: #    The user authorization type is written to the client.
 1441: #
 1442: sub user_authorization_type {
 1443:     my ($cmd, $tail, $replyfd) = @_;
 1444:    
 1445:     my $userinput = "$cmd:$tail";
 1446:    
 1447:     #  Pull the domain and username out of the command tail.
 1448:     # and call get_auth_type to determine the authentication type.
 1449:    
 1450:     my ($udom,$uname)=split(/:/,$tail);
 1451:     my $result = &get_auth_type($udom, $uname);
 1452:     if($result eq "nouser") {
 1453: 	&Failure( $replyfd, "unknown_user\n", $userinput);
 1454:     } else {
 1455: 	#
 1456: 	# We only want to pass the second field from get_auth_type
 1457: 	# for ^krb.. otherwise we'll be handing out the encrypted
 1458: 	# password for internals e.g.
 1459: 	#
 1460: 	my ($type,$otherinfo) = split(/:/,$result);
 1461: 	if($type =~ /^krb/) {
 1462: 	    $type = $result;
 1463: 	} else {
 1464:             $type .= ':';
 1465:         }
 1466: 	&Reply( $replyfd, \$type, $userinput);
 1467:     }
 1468:   
 1469:     return 1;
 1470: }
 1471: &register_handler("currentauth", \&user_authorization_type, 1, 1, 0);
 1472: 
 1473: #   Process a request by a manager to push a hosts or domain table 
 1474: #   to us.  We pick apart the command and pass it on to the subs
 1475: #   that already exist to do this.
 1476: #
 1477: # Parameters:
 1478: #      $cmd    - the actual keyword that invoked us.
 1479: #      $tail   - the tail of the request that invoked us.
 1480: #      $client - File descriptor connected to the client
 1481: #  Returns:
 1482: #      1       - Ok to continue processing.
 1483: #      0       - Program should exit
 1484: # Implicit Output:
 1485: #    a reply is written to the client.
 1486: sub push_file_handler {
 1487:     my ($cmd, $tail, $client) = @_;
 1488:     &Debug("In push file handler");
 1489:     my $userinput = "$cmd:$tail";
 1490: 
 1491:     # At this time we only know that the IP of our partner is a valid manager
 1492:     # the code below is a hook to do further authentication (e.g. to resolve
 1493:     # spoofing).
 1494: 
 1495:     my $cert = &GetCertificate($userinput);
 1496:     if(&ValidManager($cert)) {
 1497: 	&Debug("Valid manager: $client");
 1498: 
 1499: 	# Now presumably we have the bona fides of both the peer host and the
 1500: 	# process making the request.
 1501:       
 1502: 	my $reply = &PushFile($userinput);
 1503: 	&Reply($client, \$reply, $userinput);
 1504: 
 1505:     } else {
 1506: 	&logthis("push_file_handler $client is not valid");
 1507: 	&Failure( $client, "refused\n", $userinput);
 1508:     } 
 1509:     return 1;
 1510: }
 1511: &register_handler("pushfile", \&push_file_handler, 1, 0, 1);
 1512: 
 1513: # The du_handler routine should be considered obsolete and is retained
 1514: # for communication with legacy servers.  Please see the du2_handler.
 1515: #
 1516: #   du  - list the disk usage of a directory recursively. 
 1517: #    
 1518: #   note: stolen code from the ls file handler
 1519: #   under construction by Rick Banghart 
 1520: #    .
 1521: # Parameters:
 1522: #    $cmd        - The command that dispatched us (du).
 1523: #    $ududir     - The directory path to list... I'm not sure what this
 1524: #                  is relative as things like ls:. return e.g.
 1525: #                  no_such_dir.
 1526: #    $client     - Socket open on the client.
 1527: # Returns:
 1528: #     1 - indicating that the daemon should not disconnect.
 1529: # Side Effects:
 1530: #   The reply is written to  $client.
 1531: #
 1532: sub du_handler {
 1533:     my ($cmd, $ududir, $client) = @_;
 1534:     ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
 1535:     my $userinput = "$cmd:$ududir";
 1536: 
 1537:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
 1538: 	&Failure($client,"refused\n","$cmd:$ududir");
 1539: 	return 1;
 1540:     }
 1541:     #  Since $ududir could have some nasties in it,
 1542:     #  we will require that ududir is a valid
 1543:     #  directory.  Just in case someone tries to
 1544:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
 1545:     #  etc.
 1546:     #
 1547:     if (-d $ududir) {
 1548: 	my $total_size=0;
 1549: 	my $code=sub { 
 1550: 	    if ($_=~/\.\d+\./) { return;} 
 1551: 	    if ($_=~/\.meta$/) { return;}
 1552: 	    if (-d $_)         { return;}
 1553: 	    $total_size+=(stat($_))[7];
 1554: 	};
 1555: 	chdir($ududir);
 1556: 	find($code,$ududir);
 1557: 	$total_size=int($total_size/1024);
 1558: 	&Reply($client,\$total_size,"$cmd:$ududir");
 1559:     } else {
 1560: 	&Failure($client, "bad_directory:$ududir\n","$cmd:$ududir"); 
 1561:     }
 1562:     return 1;
 1563: }
 1564: &register_handler("du", \&du_handler, 0, 1, 0);
 1565: 
 1566: # Please also see the du_handler, which is obsoleted by du2. 
 1567: # du2_handler differs from du_handler in that required path to directory
 1568: # provided by &propath() is prepended in the handler instead of on the 
 1569: # client side.
 1570: #
 1571: #   du2  - list the disk usage of a directory recursively.
 1572: #
 1573: # Parameters:
 1574: #    $cmd        - The command that dispatched us (du).
 1575: #    $tail       - The tail of the request that invoked us.
 1576: #                  $tail is a : separated list of the following:
 1577: #                   - $ududir - directory path to list (before prepending)
 1578: #                   - $getpropath = 1 if &propath() should prepend
 1579: #                   - $uname - username to use for &propath or user dir
 1580: #                   - $udom - domain to use for &propath or user dir
 1581: #                   All are escaped.
 1582: #    $client     - Socket open on the client.
 1583: # Returns:
 1584: #     1 - indicating that the daemon should not disconnect.
 1585: # Side Effects:
 1586: #   The reply is written to $client.
 1587: #
 1588: 
 1589: sub du2_handler {
 1590:     my ($cmd, $tail, $client) = @_;
 1591:     my ($ududir,$getpropath,$uname,$udom) = map { &unescape($_) } (split(/:/, $tail));
 1592:     my $userinput = "$cmd:$tail";
 1593:     if (($ududir=~/\.\./) || (($ududir!~m|^/home/httpd/|) && (!$getpropath))) {
 1594:         &Failure($client,"refused\n","$cmd:$tail");
 1595:         return 1;
 1596:     }
 1597:     if ($getpropath) {
 1598:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
 1599:             $ududir = &propath($udom,$uname).'/'.$ududir;
 1600:         } else {
 1601:             &Failure($client,"refused\n","$cmd:$tail");
 1602:             return 1;
 1603:         }
 1604:     }
 1605:     #  Since $ududir could have some nasties in it,
 1606:     #  we will require that ududir is a valid
 1607:     #  directory.  Just in case someone tries to
 1608:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
 1609:     #  etc.
 1610:     #
 1611:     if (-d $ududir) {
 1612:         my $total_size=0;
 1613:         my $code=sub {
 1614:             if ($_=~/\.\d+\./) { return;}
 1615:             if ($_=~/\.meta$/) { return;}
 1616:             if (-d $_)         { return;}
 1617:             $total_size+=(stat($_))[7];
 1618:         };
 1619:         chdir($ududir);
 1620:         find($code,$ududir);
 1621:         $total_size=int($total_size/1024);
 1622:         &Reply($client,\$total_size,"$cmd:$ududir");
 1623:     } else {
 1624:         &Failure($client, "bad_directory:$ududir\n","$cmd:$tail");
 1625:     }
 1626:     return 1;
 1627: }
 1628: &register_handler("du2", \&du2_handler, 0, 1, 0);
 1629: 
 1630: #
 1631: # The ls_handler routine should be considered obsolete and is retained
 1632: # for communication with legacy servers.  Please see the ls3_handler.
 1633: #
 1634: #   ls  - list the contents of a directory.  For each file in the
 1635: #    selected directory the filename followed by the full output of
 1636: #    the stat function is returned.  The returned info for each
 1637: #    file are separated by ':'.  The stat fields are separated by &'s.
 1638: #
 1639: #    If the requested path contains /../ or is:
 1640: #
 1641: #    1. for a directory, and the path does not begin with one of:
 1642: #        (a) /home/httpd/html/res/<domain>
 1643: #        (b) /home/httpd/html/userfiles/
 1644: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
 1645: #    or is:
 1646: #
 1647: #    2. for a file, and the path (after prepending) does not begin with one of:
 1648: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
 1649: #        (b) /home/httpd/html/res/<domain>/<username>/
 1650: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
 1651: #
 1652: #    the response will be "refused".
 1653: #
 1654: # Parameters:
 1655: #    $cmd        - The command that dispatched us (ls).
 1656: #    $ulsdir     - The directory path to list... I'm not sure what this
 1657: #                  is relative as things like ls:. return e.g.
 1658: #                  no_such_dir.
 1659: #    $client     - Socket open on the client.
 1660: # Returns:
 1661: #     1 - indicating that the daemon should not disconnect.
 1662: # Side Effects:
 1663: #   The reply is written to  $client.
 1664: #
 1665: sub ls_handler {
 1666:     # obsoleted by ls2_handler
 1667:     my ($cmd, $ulsdir, $client) = @_;
 1668: 
 1669:     my $userinput = "$cmd:$ulsdir";
 1670: 
 1671:     my $obs;
 1672:     my $rights;
 1673:     my $ulsout='';
 1674:     my $ulsfn;
 1675:     if ($ulsdir =~m{/\.\./}) {
 1676:         &Failure($client,"refused\n",$userinput);
 1677:         return 1;
 1678:     }
 1679:     if (-e $ulsdir) {
 1680: 	if(-d $ulsdir) {
 1681:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
 1682:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
 1683:                 &Failure($client,"refused\n",$userinput);
 1684:                 return 1;
 1685:             }
 1686: 	    if (opendir(LSDIR,$ulsdir)) {
 1687: 		while ($ulsfn=readdir(LSDIR)) {
 1688: 		    undef($obs);
 1689: 		    undef($rights); 
 1690: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1691: 		    #We do some obsolete checking here
 1692: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
 1693: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
 1694: 			my @obsolete=<FILE>;
 1695: 			foreach my $obsolete (@obsolete) {
 1696: 			    if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
 1697: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
 1698: 			}
 1699: 		    }
 1700: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
 1701: 		    if($obs eq '1') { $ulsout.="&1"; }
 1702: 		    else { $ulsout.="&0"; }
 1703: 		    if($rights eq '1') { $ulsout.="&1:"; }
 1704: 		    else { $ulsout.="&0:"; }
 1705: 		}
 1706: 		closedir(LSDIR);
 1707: 	    }
 1708: 	} else {
 1709:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
 1710:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
 1711:                 &Failure($client,"refused\n",$userinput);
 1712:                 return 1;
 1713:             }
 1714: 	    my @ulsstats=stat($ulsdir);
 1715: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1716: 	}
 1717:     } else {
 1718: 	$ulsout='no_such_dir';
 1719:     }
 1720:     if ($ulsout eq '') { $ulsout='empty'; }
 1721:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
 1722:     
 1723:     return 1;
 1724: 
 1725: }
 1726: &register_handler("ls", \&ls_handler, 0, 1, 0);
 1727: 
 1728: # The ls2_handler routine should be considered obsolete and is retained
 1729: # for communication with legacy servers.  Please see the ls3_handler.
 1730: # Please also see the ls_handler, which was itself obsoleted by ls2.
 1731: # ls2_handler differs from ls_handler in that it escapes its return 
 1732: # values before concatenating them together with ':'s.
 1733: #
 1734: #   ls2  - list the contents of a directory.  For each file in the
 1735: #    selected directory the filename followed by the full output of
 1736: #    the stat function is returned.  The returned info for each
 1737: #    file are separated by ':'.  The stat fields are separated by &'s.
 1738: #
 1739: #    If the requested path contains /../ or is:
 1740: #
 1741: #    1. for a directory, and the path does not begin with one of:
 1742: #        (a) /home/httpd/html/res/<domain>
 1743: #        (b) /home/httpd/html/userfiles/
 1744: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
 1745: #    or is:
 1746: #
 1747: #    2. for a file, and the path (after prepending) does not begin with one of:
 1748: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
 1749: #        (b) /home/httpd/html/res/<domain>/<username>/
 1750: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
 1751: #
 1752: #    the response will be "refused".
 1753: #
 1754: # Parameters:
 1755: #    $cmd        - The command that dispatched us (ls).
 1756: #    $ulsdir     - The directory path to list... I'm not sure what this
 1757: #                  is relative as things like ls:. return e.g.
 1758: #                  no_such_dir.
 1759: #    $client     - Socket open on the client.
 1760: # Returns:
 1761: #     1 - indicating that the daemon should not disconnect.
 1762: # Side Effects:
 1763: #   The reply is written to  $client.
 1764: #
 1765: sub ls2_handler {
 1766:     my ($cmd, $ulsdir, $client) = @_;
 1767: 
 1768:     my $userinput = "$cmd:$ulsdir";
 1769: 
 1770:     my $obs;
 1771:     my $rights;
 1772:     my $ulsout='';
 1773:     my $ulsfn;
 1774:     if ($ulsdir =~m{/\.\./}) {
 1775:         &Failure($client,"refused\n",$userinput);
 1776:         return 1;
 1777:     }
 1778:     if (-e $ulsdir) {
 1779:         if(-d $ulsdir) {
 1780:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
 1781:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
 1782:                 &Failure($client,"refused\n","$userinput");
 1783:                 return 1;
 1784:             }
 1785:             if (opendir(LSDIR,$ulsdir)) {
 1786:                 while ($ulsfn=readdir(LSDIR)) {
 1787:                     undef($obs);
 1788: 		    undef($rights); 
 1789:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1790:                     #We do some obsolete checking here
 1791:                     if(-e $ulsdir.'/'.$ulsfn.".meta") { 
 1792:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
 1793:                         my @obsolete=<FILE>;
 1794:                         foreach my $obsolete (@obsolete) {
 1795:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
 1796:                             if($obsolete =~ m|(<copyright>)(default)|) {
 1797:                                 $rights = 1;
 1798:                             }
 1799:                         }
 1800:                     }
 1801:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
 1802:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1803:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1804:                     $ulsout.= &escape($tmp).':';
 1805:                 }
 1806:                 closedir(LSDIR);
 1807:             }
 1808:         } else {
 1809:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
 1810:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
 1811:                 &Failure($client,"refused\n",$userinput);
 1812:                 return 1;
 1813:             }
 1814:             my @ulsstats=stat($ulsdir);
 1815:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1816:         }
 1817:     } else {
 1818:         $ulsout='no_such_dir';
 1819:    }
 1820:    if ($ulsout eq '') { $ulsout='empty'; }
 1821:    &Reply($client, \$ulsout, $userinput); # This supports debug logging.
 1822:    return 1;
 1823: }
 1824: &register_handler("ls2", \&ls2_handler, 0, 1, 0);
 1825: #
 1826: #   ls3  - list the contents of a directory.  For each file in the
 1827: #    selected directory the filename followed by the full output of
 1828: #    the stat function is returned.  The returned info for each
 1829: #    file are separated by ':'.  The stat fields are separated by &'s.
 1830: #
 1831: #    If the requested path (after prepending) contains /../ or is:
 1832: #
 1833: #    1. for a directory, and the path does not begin with one of:
 1834: #        (a) /home/httpd/html/res/<domain>
 1835: #        (b) /home/httpd/html/userfiles/
 1836: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
 1837: #        (d) /home/httpd/html/priv/<domain> and client is the homeserver
 1838: #
 1839: #    or is:
 1840: #
 1841: #    2. for a file, and the path (after prepending) does not begin with one of:
 1842: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
 1843: #        (b) /home/httpd/html/res/<domain>/<username>/
 1844: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
 1845: #        (d) /home/httpd/html/priv/<domain>/<username>/ and client is the homeserver
 1846: #
 1847: #    the response will be "refused".
 1848: #
 1849: # Parameters:
 1850: #    $cmd        - The command that dispatched us (ls).
 1851: #    $tail       - The tail of the request that invoked us.
 1852: #                  $tail is a : separated list of the following:
 1853: #                   - $ulsdir - directory path to list (before prepending)
 1854: #                   - $getpropath = 1 if &propath() should prepend
 1855: #                   - $getuserdir = 1 if path to user dir in lonUsers should
 1856: #                                     prepend
 1857: #                   - $alternate_root - path to prepend
 1858: #                   - $uname - username to use for &propath or user dir
 1859: #                   - $udom - domain to use for &propath or user dir
 1860: #            All of these except $getpropath and &getuserdir are escaped.    
 1861: #                  no_such_dir.
 1862: #    $client     - Socket open on the client.
 1863: # Returns:
 1864: #     1 - indicating that the daemon should not disconnect.
 1865: # Side Effects:
 1866: #   The reply is written to $client.
 1867: #
 1868: 
 1869: sub ls3_handler {
 1870:     my ($cmd, $tail, $client) = @_;
 1871:     my $userinput = "$cmd:$tail";
 1872:     my ($ulsdir,$getpropath,$getuserdir,$alternate_root,$uname,$udom) =
 1873:         split(/:/,$tail);
 1874:     if (defined($ulsdir)) {
 1875:         $ulsdir = &unescape($ulsdir);
 1876:     }
 1877:     if (defined($alternate_root)) {
 1878:         $alternate_root = &unescape($alternate_root);
 1879:     }
 1880:     if (defined($uname)) {
 1881:         $uname = &unescape($uname);
 1882:     }
 1883:     if (defined($udom)) {
 1884:         $udom = &unescape($udom);
 1885:     }
 1886: 
 1887:     my $dir_root = $perlvar{'lonDocRoot'};
 1888:     if (($getpropath) || ($getuserdir)) {
 1889:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
 1890:             $dir_root = &propath($udom,$uname);
 1891:             $dir_root =~ s/\/$//;
 1892:         } else {
 1893:             &Failure($client,"refused\n",$userinput);
 1894:             return 1;
 1895:         }
 1896:     } elsif ($alternate_root ne '') {
 1897:         $dir_root = $alternate_root;
 1898:     }
 1899:     if (($dir_root ne '') && ($dir_root ne '/')) {
 1900:         if ($ulsdir =~ /^\//) {
 1901:             $ulsdir = $dir_root.$ulsdir;
 1902:         } else {
 1903:             $ulsdir = $dir_root.'/'.$ulsdir;
 1904:         }
 1905:     }
 1906:     if ($ulsdir =~m{/\.\./}) {
 1907:         &Failure($client,"refused\n",$userinput);
 1908:         return 1;
 1909:     }
 1910:     my $islocal;
 1911:     my @machine_ids = &Apache::lonnet::current_machine_ids();
 1912:     if (grep(/^\Q$clientname\E$/,@machine_ids)) {
 1913:         $islocal = 1;
 1914:     }
 1915:     my $obs;
 1916:     my $rights;
 1917:     my $ulsout='';
 1918:     my $ulsfn;
 1919: 
 1920:     my ($crscheck,$toplevel,$currdom,$currnum,$skip);
 1921:     unless ($islocal) {
 1922:         my ($major,$minor) = split(/\./,$clientversion);
 1923:         if (($major < 2) || ($major == 2 && $minor < 12)) {
 1924:             $crscheck = 1;
 1925:         }
 1926:     }
 1927:     if (-e $ulsdir) {
 1928:         if(-d $ulsdir) {
 1929:             unless (($getpropath) || ($getuserdir) ||
 1930:                     ($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
 1931:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles}) ||
 1932:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain}) && ($islocal))) {
 1933:                 &Failure($client,"refused\n",$userinput);
 1934:                 return 1;
 1935:             }
 1936:             if (($crscheck) &&
 1937:                 ($ulsdir =~ m{^/home/httpd/html/res/($LONCAPA::match_domain)(/?$|/$LONCAPA::match_courseid)})) {
 1938:                 ($currdom,my $posscnum) = ($1,$2);
 1939:                 if (($posscnum eq '') || ($posscnum eq '/')) {
 1940:                     $toplevel = 1;
 1941:                 } else {
 1942:                     $posscnum =~ s{^/+}{};
 1943:                     if (&LONCAPA::Lond::is_course($currdom,$posscnum)) {
 1944:                         $skip = 1;
 1945:                     }
 1946:                 }
 1947:             }
 1948:             if ((!$skip) && (opendir(LSDIR,$ulsdir))) {
 1949:                 while ($ulsfn=readdir(LSDIR)) {
 1950:                     if (($crscheck) && ($toplevel) && ($currdom ne '') &&
 1951:                         ($ulsfn =~ /^$LONCAPA::match_courseid$/) && (-d "$ulsdir/$ulsfn")) {
 1952:                         if (&LONCAPA::Lond::is_course($currdom,$ulsfn)) {
 1953:                             next;
 1954:                         }
 1955:                     }
 1956:                     undef($obs);
 1957:                     undef($rights);
 1958:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1959:                     #We do some obsolete checking here
 1960:                     if(-e $ulsdir.'/'.$ulsfn.".meta") {
 1961:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
 1962:                         my @obsolete=<FILE>;
 1963:                         foreach my $obsolete (@obsolete) {
 1964:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
 1965:                             if($obsolete =~ m|(<copyright>)(default)|) {
 1966:                                 $rights = 1;
 1967:                             }
 1968:                         }
 1969:                     }
 1970:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
 1971:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1972:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1973:                     $ulsout.= &escape($tmp).':';
 1974:                 }
 1975:                 closedir(LSDIR);
 1976:             }
 1977:         } else {
 1978:             unless (($getpropath) || ($getuserdir) ||
 1979:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
 1980:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/}) ||
 1981:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain/$LONCAPA::match_name/}) && ($islocal))) {
 1982:                 &Failure($client,"refused\n",$userinput);
 1983:                 return 1;
 1984:             }
 1985:             my @ulsstats=stat($ulsdir);
 1986:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1987:         }
 1988:     } else {
 1989:         $ulsout='no_such_dir';
 1990:     }
 1991:     if ($ulsout eq '') { $ulsout='empty'; }
 1992:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
 1993:     return 1;
 1994: }
 1995: &register_handler("ls3", \&ls3_handler, 0, 1, 0);
 1996: 
 1997: sub read_lonnet_global {
 1998:     my ($cmd,$tail,$client) = @_;
 1999:     my $userinput = "$cmd:$tail";
 2000:     my $requested = &Apache::lonnet::thaw_unescape($tail);
 2001:     my $result;
 2002:     my %packagevars = (
 2003:                         spareid => \%Apache::lonnet::spareid,
 2004:                         perlvar => \%Apache::lonnet::perlvar,
 2005:                       );
 2006:     my %limit_to = (
 2007:                     perlvar => {
 2008:                                  lonOtherAuthen  => 1,
 2009:                                  lonBalancer     => 1,
 2010:                                  lonVersion      => 1,
 2011:                                  lonAdmEMail     => 1,
 2012:                                  lonSupportEMail => 1,  
 2013:                                  lonSysEMail     => 1,
 2014:                                  lonHostID       => 1,
 2015:                                  lonRole         => 1,
 2016:                                  lonDefDomain    => 1,
 2017:                                  lonLoadLim      => 1,
 2018:                                  lonUserLoadLim  => 1,
 2019:                                }
 2020:                   );
 2021:     if (ref($requested) eq 'HASH') {
 2022:         foreach my $what (keys(%{$requested})) {
 2023:             my $response;
 2024:             my $items = {};
 2025:             if (exists($packagevars{$what})) {
 2026:                 if (ref($limit_to{$what}) eq 'HASH') {
 2027:                     foreach my $varname (keys(%{$packagevars{$what}})) {
 2028:                         if ($limit_to{$what}{$varname}) {
 2029:                             $items->{$varname} = $packagevars{$what}{$varname};
 2030:                         }
 2031:                     }
 2032:                 } else {
 2033:                     $items = $packagevars{$what};
 2034:                 }
 2035:                 if ($what eq 'perlvar') {
 2036:                     if (!exists($packagevars{$what}{'lonBalancer'})) {
 2037:                         if ($dist =~ /^(centos|rhes|fedora|scientific|oracle)/) {
 2038:                             my $othervarref=LONCAPA::Configuration::read_conf('httpd.conf');
 2039:                             if (ref($othervarref) eq 'HASH') {
 2040:                                 $items->{'lonBalancer'} = $othervarref->{'lonBalancer'};
 2041:                             }
 2042:                         }
 2043:                     }
 2044:                 }
 2045:                 $response = &Apache::lonnet::freeze_escape($items);
 2046:             }
 2047:             $result .= &escape($what).'='.$response.'&';
 2048:         }
 2049:     }
 2050:     $result =~ s/\&$//;
 2051:     &Reply($client,\$result,$userinput);
 2052:     return 1;
 2053: }
 2054: &register_handler("readlonnetglobal", \&read_lonnet_global, 0, 1, 0);
 2055: 
 2056: sub server_devalidatecache_handler {
 2057:     my ($cmd,$tail,$client) = @_;
 2058:     my $userinput = "$cmd:$tail";
 2059:     my $items = &unescape($tail);
 2060:     my @cached = split(/\&/,$items);
 2061:     foreach my $key (@cached) {
 2062:         if ($key =~ /:/) {
 2063:             my ($name,$id) = map { &unescape($_); } split(/:/,$key);
 2064:             &Apache::lonnet::devalidate_cache_new($name,$id);
 2065:         }
 2066:     }
 2067:     my $result = 'ok';
 2068:     &Reply($client,\$result,$userinput);
 2069:     return 1;
 2070: }
 2071: &register_handler("devalidatecache", \&server_devalidatecache_handler, 0, 1, 0);
 2072: 
 2073: sub server_timezone_handler {
 2074:     my ($cmd,$tail,$client) = @_;
 2075:     my $userinput = "$cmd:$tail";
 2076:     my $timezone;
 2077:     my $clockfile = '/etc/sysconfig/clock'; # Fedora/CentOS/SuSE
 2078:     my $tzfile = '/etc/timezone'; # Debian/Ubuntu
 2079:     if (-e $clockfile) {
 2080:         if (open(my $fh,"<$clockfile")) {
 2081:             while (<$fh>) {
 2082:                 next if (/^[\#\s]/);
 2083:                 if (/^(?:TIME)?ZONE\s*=\s*['"]?\s*([\w\/]+)/) {
 2084:                     $timezone = $1;
 2085:                     last;
 2086:                 }
 2087:             }
 2088:             close($fh);
 2089:         }
 2090:     } elsif (-e $tzfile) {
 2091:         if (open(my $fh,"<$tzfile")) {
 2092:             $timezone = <$fh>;
 2093:             close($fh);
 2094:             chomp($timezone);
 2095:             if ($timezone =~ m{^Etc/(\w+)$}) {
 2096:                 $timezone = $1;
 2097:             }
 2098:         }
 2099:     }
 2100:     &Reply($client,\$timezone,$userinput); # This supports debug logging.
 2101:     return 1;
 2102: }
 2103: &register_handler("servertimezone", \&server_timezone_handler, 0, 1, 0);
 2104: 
 2105: sub server_loncaparev_handler {
 2106:     my ($cmd,$tail,$client) = @_;
 2107:     my $userinput = "$cmd:$tail";
 2108:     &Reply($client,\$perlvar{'lonVersion'},$userinput);
 2109:     return 1;
 2110: }
 2111: &register_handler("serverloncaparev", \&server_loncaparev_handler, 0, 1, 0);
 2112: 
 2113: sub server_homeID_handler {
 2114:     my ($cmd,$tail,$client) = @_;
 2115:     my $userinput = "$cmd:$tail";
 2116:     &Reply($client,\$perlvar{'lonHostID'},$userinput);
 2117:     return 1;
 2118: }
 2119: &register_handler("serverhomeID", \&server_homeID_handler, 0, 1, 0);
 2120: 
 2121: sub server_distarch_handler {
 2122:     my ($cmd,$tail,$client) = @_;
 2123:     my $userinput = "$cmd:$tail";
 2124:     my $reply = &distro_and_arch();
 2125:     &Reply($client,\$reply,$userinput);
 2126:     return 1;
 2127: }
 2128: &register_handler("serverdistarch", \&server_distarch_handler, 0, 1, 0);
 2129: 
 2130: sub server_certs_handler {
 2131:     my ($cmd,$tail,$client) = @_;
 2132:     my $userinput = "$cmd:$tail";
 2133:     my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
 2134:     my $result = &LONCAPA::Lond::server_certs(\%perlvar,$perlvar{'lonHostID'},$hostname);
 2135:     &Reply($client,\$result,$userinput);
 2136:     return;
 2137: }
 2138: &register_handler("servercerts", \&server_certs_handler, 0, 1, 0);
 2139: 
 2140: #   Process a reinit request.  Reinit requests that either
 2141: #   lonc or lond be reinitialized so that an updated 
 2142: #   host.tab or domain.tab can be processed.
 2143: #
 2144: # Parameters:
 2145: #      $cmd    - the actual keyword that invoked us.
 2146: #      $tail   - the tail of the request that invoked us.
 2147: #      $client - File descriptor connected to the client
 2148: #  Returns:
 2149: #      1       - Ok to continue processing.
 2150: #      0       - Program should exit
 2151: #  Implicit output:
 2152: #     a reply is sent to the client.
 2153: #
 2154: sub reinit_process_handler {
 2155:     my ($cmd, $tail, $client) = @_;
 2156:    
 2157:     my $userinput = "$cmd:$tail";
 2158:    
 2159:     my $cert = &GetCertificate($userinput);
 2160:     if(&ValidManager($cert)) {
 2161: 	chomp($userinput);
 2162: 	my $reply = &ReinitProcess($userinput);
 2163: 	&Reply( $client,  \$reply, $userinput);
 2164:     } else {
 2165: 	&Failure( $client, "refused\n", $userinput);
 2166:     }
 2167:     return 1;
 2168: }
 2169: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
 2170: 
 2171: #  Process the editing script for a table edit operation.
 2172: #  the editing operation must be encrypted and requested by
 2173: #  a manager host.
 2174: #
 2175: # Parameters:
 2176: #      $cmd    - the actual keyword that invoked us.
 2177: #      $tail   - the tail of the request that invoked us.
 2178: #      $client - File descriptor connected to the client
 2179: #  Returns:
 2180: #      1       - Ok to continue processing.
 2181: #      0       - Program should exit
 2182: #  Implicit output:
 2183: #     a reply is sent to the client.
 2184: #
 2185: sub edit_table_handler {
 2186:     my ($command, $tail, $client) = @_;
 2187:    
 2188:     my $userinput = "$command:$tail";
 2189: 
 2190:     my $cert = &GetCertificate($userinput);
 2191:     if(&ValidManager($cert)) {
 2192: 	my($filetype, $script) = split(/:/, $tail);
 2193: 	if (($filetype eq "hosts") || 
 2194: 	    ($filetype eq "domain")) {
 2195: 	    if($script ne "") {
 2196: 		&Reply($client,              # BUGBUG - EditFile
 2197: 		      &EditFile($userinput), #   could fail.
 2198: 		      $userinput);
 2199: 	    } else {
 2200: 		&Failure($client,"refused\n",$userinput);
 2201: 	    }
 2202: 	} else {
 2203: 	    &Failure($client,"refused\n",$userinput);
 2204: 	}
 2205:     } else {
 2206: 	&Failure($client,"refused\n",$userinput);
 2207:     }
 2208:     return 1;
 2209: }
 2210: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
 2211: 
 2212: #
 2213: #   Authenticate a user against the LonCAPA authentication
 2214: #   database.  Note that there are several authentication
 2215: #   possibilities:
 2216: #   - unix     - The user can be authenticated against the unix
 2217: #                password file.
 2218: #   - internal - The user can be authenticated against a purely 
 2219: #                internal per user password file.
 2220: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
 2221: #                ticket granting authority.
 2222: #   - user     - The person tailoring LonCAPA can supply a user authentication
 2223: #                mechanism that is per system.
 2224: #
 2225: # Parameters:
 2226: #    $cmd      - The command that got us here.
 2227: #    $tail     - Tail of the command (remaining parameters).
 2228: #    $client   - File descriptor connected to client.
 2229: # Returns
 2230: #     0        - Requested to exit, caller should shut down.
 2231: #     1        - Continue processing.
 2232: # Implicit inputs:
 2233: #    The authentication systems describe above have their own forms of implicit
 2234: #    input into the authentication process that are described above.
 2235: #
 2236: sub authenticate_handler {
 2237:     my ($cmd, $tail, $client) = @_;
 2238: 
 2239:     
 2240:     #  Regenerate the full input line 
 2241:     
 2242:     my $userinput  = $cmd.":".$tail;
 2243:     
 2244:     #  udom    - User's domain.
 2245:     #  uname   - Username.
 2246:     #  upass   - User's password.
 2247:     #  checkdefauth - Pass to validate_user() to try authentication
 2248:     #                 with default auth type(s) if no user account.
 2249:     #  clientcancheckhost - Passed by clients with functionality in lonauth.pm
 2250:     #                       to check if session can be hosted.
 2251:     
 2252:     my ($udom, $uname, $upass, $checkdefauth, $clientcancheckhost)=split(/:/,$tail);
 2253:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass,  checkdefauth = $checkdefauth");
 2254:     chomp($upass);
 2255:     $upass=&unescape($upass);
 2256: 
 2257:     my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
 2258:     if($pwdcorrect) {
 2259:         my $canhost = 1;
 2260:         unless ($clientcancheckhost) {
 2261:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 2262:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 2263:             my @intdoms;
 2264:             my $internet_names = &Apache::lonnet::get_internet_names($clientname);
 2265:             if (ref($internet_names) eq 'ARRAY') {
 2266:                 @intdoms = @{$internet_names};
 2267:             }
 2268:             unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
 2269:                 my ($remote,$hosted);
 2270:                 my $remotesession = &get_usersession_config($udom,'remotesession');
 2271:                 if (ref($remotesession) eq 'HASH') {
 2272:                     $remote = $remotesession->{'remote'};
 2273:                 }
 2274:                 my $hostedsession = &get_usersession_config($clienthomedom,'hostedsession');
 2275:                 if (ref($hostedsession) eq 'HASH') {
 2276:                     $hosted = $hostedsession->{'hosted'};
 2277:                 }
 2278:                 $canhost = &Apache::lonnet::can_host_session($udom,$clientname,
 2279:                                                              $clientversion,
 2280:                                                              $remote,$hosted);
 2281:             }
 2282:         }
 2283:         if ($canhost) {               
 2284:             &Reply( $client, "authorized\n", $userinput);
 2285:         } else {
 2286:             &Reply( $client, "not_allowed_to_host\n", $userinput);
 2287:         }
 2288: 	#
 2289: 	#  Bad credentials: Failed to authorize
 2290: 	#
 2291:     } else {
 2292: 	&Failure( $client, "non_authorized\n", $userinput);
 2293:     }
 2294: 
 2295:     return 1;
 2296: }
 2297: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
 2298: 
 2299: #
 2300: #   Change a user's password.  Note that this function is complicated by
 2301: #   the fact that a user may be authenticated in more than one way:
 2302: #   At present, we are not able to change the password for all types of
 2303: #   authentication methods.  Only for:
 2304: #      unix    - unix password or shadow passoword style authentication.
 2305: #      local   - Locally written authentication mechanism.
 2306: #   For now, kerb4 and kerb5 password changes are not supported and result
 2307: #   in an error.
 2308: # FUTURE WORK:
 2309: #    Support kerberos passwd changes?
 2310: # Parameters:
 2311: #    $cmd      - The command that got us here.
 2312: #    $tail     - Tail of the command (remaining parameters).
 2313: #    $client   - File descriptor connected to client.
 2314: # Returns
 2315: #     0        - Requested to exit, caller should shut down.
 2316: #     1        - Continue processing.
 2317: # Implicit inputs:
 2318: #    The authentication systems describe above have their own forms of implicit
 2319: #    input into the authentication process that are described above.
 2320: sub change_password_handler {
 2321:     my ($cmd, $tail, $client) = @_;
 2322: 
 2323:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
 2324: 
 2325:     #
 2326:     #  udom  - user's domain.
 2327:     #  uname - Username.
 2328:     #  upass - Current password.
 2329:     #  npass - New password.
 2330:     #  context - Context in which this was called 
 2331:     #            (preferences or reset_by_email).
 2332:     #  lonhost - HostID of server where request originated 
 2333:    
 2334:     my ($udom,$uname,$upass,$npass,$context,$lonhost)=split(/:/,$tail);
 2335: 
 2336:     $upass=&unescape($upass);
 2337:     $npass=&unescape($npass);
 2338:     &Debug("Trying to change password for $uname");
 2339: 
 2340:     # First require that the user can be authenticated with their
 2341:     # old password unless context was 'reset_by_email':
 2342:     
 2343:     my ($validated,$failure);
 2344:     if ($context eq 'reset_by_email') {
 2345:         if ($lonhost eq '') {
 2346:             $failure = 'invalid_client';
 2347:         } else {
 2348:             $validated = 1;
 2349:         }
 2350:     } else {
 2351:         $validated = &validate_user($udom, $uname, $upass);
 2352:     }
 2353:     if($validated) {
 2354: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
 2355: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
 2356:         my $notunique;
 2357: 	if ($howpwd eq 'internal') {
 2358: 	    &Debug("internal auth");
 2359:             my $ncpass = &hash_passwd($udom,$npass);
 2360:             my (undef,$method,@rest) = split(/!/,$contentpwd);
 2361:             if ($method eq 'bcrypt') {
 2362:                 my %passwdconf = &Apache::lonnet::get_passwdconf($udom);
 2363:                 if (($passwdconf{'numsaved'}) && ($passwdconf{'numsaved'} =~ /^\d+$/)) {
 2364:                     my @oldpasswds;
 2365:                     my $userpath = &propath($udom,$uname);
 2366:                     my $fullpath = $userpath.'/oldpasswds';
 2367:                     if (-d $userpath) {
 2368:                         my @oldfiles;
 2369:                         if (-e $fullpath) {
 2370:                             if (opendir(my $dir,$fullpath)) {
 2371:                                 (@oldfiles) = grep(/^\d+$/,readdir($dir));
 2372:                                 closedir($dir);
 2373:                             }
 2374:                             if (@oldfiles) {
 2375:                                 @oldfiles = sort { $b <=> $a } (@oldfiles);
 2376:                                 my $numremoved = 0;
 2377:                                 for (my $i=0; $i<@oldfiles; $i++) {
 2378:                                     if ($i>=$passwdconf{'numsaved'}) {
 2379:                                         if (-f "$fullpath/$oldfiles[$i]") {
 2380:                                             if (unlink("$fullpath/$oldfiles[$i]")) {
 2381:                                                 $numremoved ++;
 2382:                                             }
 2383:                                         }
 2384:                                     } elsif (open(my $fh,'<',"$fullpath/$oldfiles[$i]")) {
 2385:                                         while (my $line = <$fh>) {
 2386:                                             push(@oldpasswds,$line);
 2387:                                         }
 2388:                                         close($fh);
 2389:                                     }
 2390:                                 }
 2391:                                 if ($numremoved) {
 2392:                                     &logthis("unlinked $numremoved old password files for $uname:$udom");
 2393:                                 }
 2394:                             }
 2395:                         }
 2396:                         push(@oldpasswds,$contentpwd);
 2397:                         foreach my $item (@oldpasswds) {
 2398:                             my (undef,$method,@rest) = split(/!/,$item);
 2399:                             if ($method eq 'bcrypt') {
 2400:                                 my $result = &hash_passwd($udom,$npass,@rest);
 2401:                                 if ($result eq $item) {
 2402:                                     $notunique = 1;
 2403:                                     last;
 2404:                                 }
 2405:                             }
 2406:                         }
 2407:                         unless ($notunique) {
 2408:                             unless (-e $fullpath) {
 2409:                                 if (&mkpath("$fullpath/")) {
 2410:                                     chmod(0700,$fullpath);
 2411:                                 }
 2412:                             }
 2413:                             if (-d $fullpath) {
 2414:                                 my $now = time;
 2415:                                 if (open(my $fh,'>',"$fullpath/$now")) {
 2416:                                     print $fh $contentpwd;
 2417:                                     close($fh);
 2418:                                     chmod(0400,"$fullpath/$now");
 2419:                                 }
 2420:                             }
 2421:                         }
 2422:                     }
 2423:                 }
 2424:             }
 2425:             if ($notunique) {
 2426:                 my $msg="Result of password change for $uname:$udom - password matches one used before";
 2427:                 if ($lonhost) {
 2428:                     $msg .= " - request originated from: $lonhost";
 2429:                 }
 2430:                 &logthis($msg);
 2431:                 &Reply($client, "prioruse\n", $userinput);
 2432: 	    } elsif (&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
 2433: 		my $msg="Result of password change for $uname: pwchange_success";
 2434:                 if ($lonhost) {
 2435:                     $msg .= " - request originated from: $lonhost";
 2436:                 }
 2437:                 &logthis($msg);
 2438:                 &update_passwd_history($uname,$udom,$howpwd,$context);
 2439: 		&Reply($client, "ok\n", $userinput);
 2440: 	    } else {
 2441: 		&logthis("Unable to open $uname passwd "               
 2442: 			 ."to change password");
 2443: 		&Failure( $client, "non_authorized\n",$userinput);
 2444: 	    }
 2445: 	} elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
 2446: 	    my $result = &change_unix_password($uname, $npass);
 2447:             if ($result eq 'ok') {
 2448:                 &update_passwd_history($uname,$udom,$howpwd,$context);
 2449:             }
 2450: 	    &logthis("Result of password change for $uname: ".
 2451: 		     $result);
 2452: 	    &Reply($client, \$result, $userinput);
 2453: 	} else {
 2454: 	    # this just means that the current password mode is not
 2455: 	    # one we know how to change (e.g the kerberos auth modes or
 2456: 	    # locally written auth handler).
 2457: 	    #
 2458: 	    &Failure( $client, "auth_mode_error\n", $userinput);
 2459: 	}  
 2460:     } else {
 2461: 	if ($failure eq '') {
 2462: 	    $failure = 'non_authorized';
 2463: 	}
 2464: 	&Failure( $client, "$failure\n", $userinput);
 2465:     }
 2466: 
 2467:     return 1;
 2468: }
 2469: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
 2470: 
 2471: sub hash_passwd {
 2472:     my ($domain,$plainpass,@rest) = @_;
 2473:     my ($salt,$cost);
 2474:     if (@rest) {
 2475:         $cost = $rest[0];
 2476:         # salt is first 22 characters, base-64 encoded by bcrypt
 2477:         my $plainsalt = substr($rest[1],0,22);
 2478:         $salt = Crypt::Eksblowfish::Bcrypt::de_base64($plainsalt);
 2479:     } else {
 2480:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2481:         my $defaultcost = $domdefaults{'intauth_cost'};
 2482:         if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
 2483:             $cost = 10;
 2484:         } else {
 2485:             $cost = $defaultcost;
 2486:         }
 2487:         # Generate random 16-octet base64 salt
 2488:         $salt = "";
 2489:         $salt .= pack("C", int rand(256)) for 1..16;
 2490:     }
 2491:     my $hash = &Crypt::Eksblowfish::Bcrypt::bcrypt_hash({
 2492:         key_nul => 1,
 2493:         cost    => $cost,
 2494:         salt    => $salt,
 2495:     }, Digest::SHA::sha512(Encode::encode('UTF-8',$plainpass)));
 2496: 
 2497:     my $result = join("!", "", "bcrypt", sprintf("%02d",$cost),
 2498:                 &Crypt::Eksblowfish::Bcrypt::en_base64($salt).
 2499:                 &Crypt::Eksblowfish::Bcrypt::en_base64($hash));
 2500:     return $result;
 2501: }
 2502: 
 2503: #
 2504: #   Create a new user.  User in this case means a lon-capa user.
 2505: #   The user must either already exist in some authentication realm
 2506: #   like kerberos or the /etc/passwd.  If not, a user completely local to
 2507: #   this loncapa system is created.
 2508: #
 2509: # Parameters:
 2510: #    $cmd      - The command that got us here.
 2511: #    $tail     - Tail of the command (remaining parameters).
 2512: #    $client   - File descriptor connected to client.
 2513: # Returns
 2514: #     0        - Requested to exit, caller should shut down.
 2515: #     1        - Continue processing.
 2516: # Implicit inputs:
 2517: #    The authentication systems describe above have their own forms of implicit
 2518: #    input into the authentication process that are described above.
 2519: sub add_user_handler {
 2520: 
 2521:     my ($cmd, $tail, $client) = @_;
 2522: 
 2523: 
 2524:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
 2525:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
 2526: 
 2527:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
 2528: 
 2529: 
 2530:     if($udom eq $currentdomainid) { # Reject new users for other domains...
 2531: 	
 2532: 	my $oldumask=umask(0077);
 2533: 	chomp($npass);
 2534: 	$npass=&unescape($npass);
 2535: 	my $passfilename  = &password_path($udom, $uname);
 2536: 	&Debug("Password file created will be:".$passfilename);
 2537: 	if (-e $passfilename) {
 2538: 	    &Failure( $client, "already_exists\n", $userinput);
 2539: 	} else {
 2540: 	    my $fperror='';
 2541: 	    if (!&mkpath($passfilename)) {
 2542: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
 2543: 		    ."makeuser";
 2544: 	    }
 2545: 	    unless ($fperror) {
 2546: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
 2547:                                              $passfilename,'makeuser');
 2548: 		&Reply($client,\$result, $userinput);     #BUGBUG - could be fail
 2549: 	    } else {
 2550: 		&Failure($client, \$fperror, $userinput);
 2551: 	    }
 2552: 	}
 2553: 	umask($oldumask);
 2554:     }  else {
 2555: 	&Failure($client, "not_right_domain\n",
 2556: 		$userinput);	# Even if we are multihomed.
 2557:     
 2558:     }
 2559:     return 1;
 2560: 
 2561: }
 2562: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
 2563: 
 2564: #
 2565: #   Change the authentication method of a user.  Note that this may
 2566: #   also implicitly change the user's password if, for example, the user is
 2567: #   joining an existing authentication realm.  Known authentication realms at
 2568: #   this time are:
 2569: #    internal   - Purely internal password file (only loncapa knows this user)
 2570: #    local      - Institutionally written authentication module.
 2571: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
 2572: #    kerb4      - kerberos version 4
 2573: #    kerb5      - kerberos version 5
 2574: #
 2575: # Parameters:
 2576: #    $cmd      - The command that got us here.
 2577: #    $tail     - Tail of the command (remaining parameters).
 2578: #    $client   - File descriptor connected to client.
 2579: # Returns
 2580: #     0        - Requested to exit, caller should shut down.
 2581: #     1        - Continue processing.
 2582: # Implicit inputs:
 2583: #    The authentication systems describe above have their own forms of implicit
 2584: #    input into the authentication process that are described above.
 2585: # NOTE:
 2586: #   This is also used to change the authentication credential values (e.g. passwd).
 2587: #   
 2588: #
 2589: sub change_authentication_handler {
 2590: 
 2591:     my ($cmd, $tail, $client) = @_;
 2592:    
 2593:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
 2594: 
 2595:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
 2596:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
 2597:     if ($udom ne $currentdomainid) {
 2598: 	&Failure( $client, "not_right_domain\n", $client);
 2599:     } else {
 2600: 	
 2601: 	chomp($npass);
 2602: 	
 2603: 	$npass=&unescape($npass);
 2604: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
 2605: 	my $passfilename = &password_path($udom, $uname);
 2606: 	if ($passfilename) {	# Not allowed to create a new user!!
 2607: 	    # If just changing the unix passwd. need to arrange to run
 2608: 	    # passwd since otherwise make_passwd_file will fail as 
 2609: 	    # creation of unix authenticated users is no longer supported
 2610:             # except from the command line, when running make_domain_coordinator.pl
 2611: 
 2612: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
 2613: 		my $result = &change_unix_password($uname, $npass);
 2614: 		&logthis("Result of password change for $uname: ".$result);
 2615: 		if ($result eq "ok") {
 2616:                     &update_passwd_history($uname,$udom,$umode,'changeuserauth'); 
 2617: 		    &Reply($client, \$result);
 2618: 		} else {
 2619: 		    &Failure($client, \$result);
 2620: 		}
 2621: 	    } else {
 2622: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
 2623:                                              $passfilename,'changeuserauth');
 2624: 		#
 2625: 		#  If the current auth mode is internal, and the old auth mode was
 2626: 		#  unix, or krb*,  and the user is an author for this domain,
 2627: 		#  re-run manage_permissions for that role in order to be able
 2628: 		#  to take ownership of the construction space back to www:www
 2629: 		#
 2630: 
 2631: 
 2632: 		&Reply($client, \$result, $userinput);
 2633: 	    }
 2634: 	       
 2635: 
 2636: 	} else {	       
 2637: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
 2638: 	}
 2639:     }
 2640:     return 1;
 2641: }
 2642: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
 2643: 
 2644: sub update_passwd_history {
 2645:     my ($uname,$udom,$umode,$context) = @_;
 2646:     my $proname=&propath($udom,$uname);
 2647:     my $now = time;
 2648:     if (open(my $fh,">>$proname/passwd.log")) {
 2649:         print $fh "$now:$umode:$context\n";
 2650:         close($fh);
 2651:     }
 2652:     return;
 2653: }
 2654: 
 2655: #
 2656: #   Determines if this is the home server for a user.  The home server
 2657: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
 2658: #   to do is determine if this file exists.
 2659: #
 2660: # Parameters:
 2661: #    $cmd      - The command that got us here.
 2662: #    $tail     - Tail of the command (remaining parameters).
 2663: #    $client   - File descriptor connected to client.
 2664: # Returns
 2665: #     0        - Requested to exit, caller should shut down.
 2666: #     1        - Continue processing.
 2667: # Implicit inputs:
 2668: #    The authentication systems describe above have their own forms of implicit
 2669: #    input into the authentication process that are described above.
 2670: #
 2671: sub is_home_handler {
 2672:     my ($cmd, $tail, $client) = @_;
 2673:    
 2674:     my $userinput  = "$cmd:$tail";
 2675:    
 2676:     my ($udom,$uname)=split(/:/,$tail);
 2677:     chomp($uname);
 2678:     my $passfile = &password_filename($udom, $uname);
 2679:     if($passfile) {
 2680: 	&Reply( $client, "found\n", $userinput);
 2681:     } else {
 2682: 	&Failure($client, "not_found\n", $userinput);
 2683:     }
 2684:     return 1;
 2685: }
 2686: &register_handler("home", \&is_home_handler, 0,1,0);
 2687: 
 2688: #
 2689: #   Process an update request for a resource.
 2690: #   A resource has been modified that we hold a subscription to.
 2691: #   If the resource is not local, then we must update, or at least invalidate our
 2692: #   cached copy of the resource. 
 2693: # Parameters:
 2694: #    $cmd      - The command that got us here.
 2695: #    $tail     - Tail of the command (remaining parameters).
 2696: #    $client   - File descriptor connected to client.
 2697: # Returns
 2698: #     0        - Requested to exit, caller should shut down.
 2699: #     1        - Continue processing.
 2700: # Implicit inputs:
 2701: #    The authentication systems describe above have their own forms of implicit
 2702: #    input into the authentication process that are described above.
 2703: #
 2704: sub update_resource_handler {
 2705: 
 2706:     my ($cmd, $tail, $client) = @_;
 2707:    
 2708:     my $userinput = "$cmd:$tail";
 2709:    
 2710:     my $fname= $tail;		# This allows interactive testing
 2711: 
 2712: 
 2713:     my $ownership=ishome($fname);
 2714:     if ($ownership eq 'not_owner') {
 2715: 	if (-e $fname) {
 2716:             # Delete preview file, if exists
 2717:             unlink("$fname.tmp");
 2718:             # Get usage stats
 2719: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
 2720: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
 2721: 	    my $now=time;
 2722: 	    my $since=$now-$atime;
 2723:             # If the file has not been used within lonExpire seconds,
 2724:             # unsubscribe from it and delete local copy
 2725: 	    if ($since>$perlvar{'lonExpire'}) {
 2726: 		my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
 2727: 		&devalidate_meta_cache($fname);
 2728: 		unlink("$fname");
 2729: 		unlink("$fname.meta");
 2730: 	    } else {
 2731:             # Yes, this is in active use. Get a fresh copy. Since it might be in
 2732:             # very active use and huge (like a movie), copy it to "in.transfer" filename first.
 2733: 		my $transname="$fname.in.transfer";
 2734: 		my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
 2735: 		my $response;
 2736: # FIXME: cannot replicate files that take more than two minutes to transfer -- needs checking now 1200s timeout used
 2737: # for LWP request.
 2738: 		my $request=new HTTP::Request('GET',"$remoteurl");
 2739:                 $response=&LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,0,1);
 2740: 		if ($response->is_error()) {
 2741:                     my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
 2742:                     &devalidate_meta_cache($fname);
 2743:                     if (-e $transname) {
 2744:                         unlink($transname);
 2745:                     }
 2746:                     unlink($fname);
 2747: 		    my $message=$response->status_line;
 2748: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
 2749: 		} else {
 2750: 		    if ($remoteurl!~/\.meta$/) {
 2751: 			my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2752:                         my $mresponse = &LONCAPA::LWPReq::makerequest($clientname,$mrequest,$fname.'.meta',\%perlvar,120,0,1);
 2753: 			if ($mresponse->is_error()) {
 2754: 			    unlink($fname.'.meta');
 2755: 			}
 2756: 		    }
 2757:                     # we successfully transfered, copy file over to real name
 2758: 		    rename($transname,$fname);
 2759: 		    &devalidate_meta_cache($fname);
 2760: 		}
 2761: 	    }
 2762: 	    &Reply( $client, "ok\n", $userinput);
 2763: 	} else {
 2764: 	    &Failure($client, "not_found\n", $userinput);
 2765: 	}
 2766:     } else {
 2767: 	&Failure($client, "rejected\n", $userinput);
 2768:     }
 2769:     return 1;
 2770: }
 2771: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
 2772: 
 2773: sub devalidate_meta_cache {
 2774:     my ($url) = @_;
 2775:     use Cache::Memcached;
 2776:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
 2777:     $url = &Apache::lonnet::declutter($url);
 2778:     $url =~ s-\.meta$--;
 2779:     my $id = &escape('meta:'.$url);
 2780:     $memcache->delete($id);
 2781: }
 2782: 
 2783: #
 2784: #   Fetch a user file from a remote server to the user's home directory
 2785: #   userfiles subdir.
 2786: # Parameters:
 2787: #    $cmd      - The command that got us here.
 2788: #    $tail     - Tail of the command (remaining parameters).
 2789: #    $client   - File descriptor connected to client.
 2790: # Returns
 2791: #     0        - Requested to exit, caller should shut down.
 2792: #     1        - Continue processing.
 2793: #
 2794: sub fetch_user_file_handler {
 2795: 
 2796:     my ($cmd, $tail, $client) = @_;
 2797: 
 2798:     my $userinput = "$cmd:$tail";
 2799:     my $fname           = $tail;
 2800:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
 2801:     my $udir=&propath($udom,$uname).'/userfiles';
 2802:     unless (-e $udir) {
 2803: 	mkdir($udir,0770); 
 2804:     }
 2805:     Debug("fetch user file for $fname");
 2806:     if (-e $udir) {
 2807: 	$ufile=~s/^[\.\~]+//;
 2808: 
 2809: 	# IF necessary, create the path right down to the file.
 2810: 	# Note that any regular files in the way of this path are
 2811: 	# wiped out to deal with some earlier folly of mine.
 2812: 
 2813: 	if (!&mkpath($udir.'/'.$ufile)) {
 2814: 	    &Failure($client, "unable_to_create\n", $userinput);	    
 2815: 	}
 2816: 
 2817: 	my $destname=$udir.'/'.$ufile;
 2818: 	my $transname=$udir.'/'.$ufile.'.in.transit';
 2819:         my $clientprotocol=$Apache::lonnet::protocol{$clientname};
 2820:         $clientprotocol = 'http' if ($clientprotocol ne 'https');
 2821: 	my $clienthost = &Apache::lonnet::hostname($clientname);
 2822: 	my $remoteurl=$clientprotocol.'://'.$clienthost.'/userfiles/'.$fname;
 2823: 	my $response;
 2824: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
 2825: 	my $request=new HTTP::Request('GET',"$remoteurl");
 2826:         my $verifycert = 1;
 2827:         my @machine_ids = &Apache::lonnet::current_machine_ids();
 2828:         if (grep(/^\Q$clientname\E$/,@machine_ids)) {
 2829:             $verifycert = 0;
 2830:         }
 2831:         $response = &LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,$verifycert);
 2832: 	if ($response->is_error()) {
 2833: 	    unlink($transname);
 2834: 	    my $message=$response->status_line;
 2835: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
 2836: 	    &Failure($client, "failed\n", $userinput);
 2837: 	} else {
 2838: 	    Debug("Renaming $transname to $destname");
 2839: 	    if (!rename($transname,$destname)) {
 2840: 		&logthis("Unable to move $transname to $destname");
 2841: 		unlink($transname);
 2842: 		&Failure($client, "failed\n", $userinput);
 2843: 	    } else {
 2844:                 if ($fname =~ /^default.+\.(page|sequence)$/) {
 2845:                     my ($major,$minor) = split(/\./,$clientversion);
 2846:                     if (($major < 2) || ($major == 2 && $minor < 11)) {
 2847:                         my $now = time;
 2848:                         &Apache::lonnet::do_cache_new('crschange',$udom.'_'.$uname,$now,600);
 2849:                         my $key = &escape('internal.contentchange');
 2850:                         my $what = "$key=$now";
 2851:                         my $hashref = &tie_user_hash($udom,$uname,'environment',
 2852:                                                      &GDBM_WRCREAT(),"P",$what);
 2853:                         if ($hashref) {
 2854:                             $hashref->{$key}=$now;
 2855:                             if (!&untie_user_hash($hashref)) {
 2856:                                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
 2857:                                          "when updating internal.contentchange");
 2858:                             }
 2859:                         }
 2860:                     }
 2861:                 }
 2862: 		&Reply($client, "ok\n", $userinput);
 2863: 	    }
 2864: 	}   
 2865:     } else {
 2866: 	&Failure($client, "not_home\n", $userinput);
 2867:     }
 2868:     return 1;
 2869: }
 2870: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
 2871: 
 2872: #
 2873: #   Remove a file from a user's home directory userfiles subdirectory.
 2874: # Parameters:
 2875: #    cmd   - the Lond request keyword that got us here.
 2876: #    tail  - the part of the command past the keyword.
 2877: #    client- File descriptor connected with the client.
 2878: #
 2879: # Returns:
 2880: #    1    - Continue processing.
 2881: sub remove_user_file_handler {
 2882:     my ($cmd, $tail, $client) = @_;
 2883: 
 2884:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
 2885: 
 2886:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
 2887:     if ($ufile =~m|/\.\./|) {
 2888: 	# any files paths with /../ in them refuse 
 2889: 	# to deal with
 2890: 	&Failure($client, "refused\n", "$cmd:$tail");
 2891:     } else {
 2892: 	my $udir = &propath($udom,$uname);
 2893: 	if (-e $udir) {
 2894: 	    my $file=$udir.'/userfiles/'.$ufile;
 2895: 	    if (-e $file) {
 2896: 		#
 2897: 		#   If the file is a regular file unlink is fine...
 2898: 		#   However it's possible the client wants a dir 
 2899: 		#   removed, in which case rmdir is more appropriate.
 2900: 		#   Note: rmdir will only remove an empty directory.
 2901: 		#
 2902: 	        if (-f $file){
 2903: 		    unlink($file);
 2904:                     # for html files remove the associated .bak file 
 2905:                     # which may have been created by the editor.
 2906:                     if ($ufile =~ m{^((docs|supplemental)/(?:\d+|default)/\d+(?:|/.+)/)[^/]+\.x?html?$}i) {
 2907:                         my $path = $1;
 2908:                         if (-e $file.'.bak') {
 2909:                             unlink($file.'.bak');
 2910:                         }
 2911:                     }
 2912: 		} elsif(-d $file) {
 2913: 		    rmdir($file);
 2914: 		}
 2915: 		if (-e $file) {
 2916: 		    #  File is still there after we deleted it ?!?
 2917: 
 2918: 		    &Failure($client, "failed\n", "$cmd:$tail");
 2919: 		} else {
 2920: 		    &Reply($client, "ok\n", "$cmd:$tail");
 2921: 		}
 2922: 	    } else {
 2923: 		&Failure($client, "not_found\n", "$cmd:$tail");
 2924: 	    }
 2925: 	} else {
 2926: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 2927: 	}
 2928:     }
 2929:     return 1;
 2930: }
 2931: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
 2932: 
 2933: #
 2934: #   make a directory in a user's home directory userfiles subdirectory.
 2935: # Parameters:
 2936: #    cmd   - the Lond request keyword that got us here.
 2937: #    tail  - the part of the command past the keyword.
 2938: #    client- File descriptor connected with the client.
 2939: #
 2940: # Returns:
 2941: #    1    - Continue processing.
 2942: sub mkdir_user_file_handler {
 2943:     my ($cmd, $tail, $client) = @_;
 2944: 
 2945:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
 2946:     $dir=&unescape($dir);
 2947:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
 2948:     if ($ufile =~m|/\.\./|) {
 2949: 	# any files paths with /../ in them refuse 
 2950: 	# to deal with
 2951: 	&Failure($client, "refused\n", "$cmd:$tail");
 2952:     } else {
 2953: 	my $udir = &propath($udom,$uname);
 2954: 	if (-e $udir) {
 2955: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
 2956: 	    if (!&mkpath($newdir)) {
 2957: 		&Failure($client, "failed\n", "$cmd:$tail");
 2958: 	    }
 2959: 	    &Reply($client, "ok\n", "$cmd:$tail");
 2960: 	} else {
 2961: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 2962: 	}
 2963:     }
 2964:     return 1;
 2965: }
 2966: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
 2967: 
 2968: #
 2969: #   rename a file in a user's home directory userfiles subdirectory.
 2970: # Parameters:
 2971: #    cmd   - the Lond request keyword that got us here.
 2972: #    tail  - the part of the command past the keyword.
 2973: #    client- File descriptor connected with the client.
 2974: #
 2975: # Returns:
 2976: #    1    - Continue processing.
 2977: sub rename_user_file_handler {
 2978:     my ($cmd, $tail, $client) = @_;
 2979: 
 2980:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
 2981:     $old=&unescape($old);
 2982:     $new=&unescape($new);
 2983:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
 2984: 	# any files paths with /../ in them refuse to deal with
 2985: 	&Failure($client, "refused\n", "$cmd:$tail");
 2986:     } else {
 2987: 	my $udir = &propath($udom,$uname);
 2988: 	if (-e $udir) {
 2989: 	    my $oldfile=$udir.'/userfiles/'.$old;
 2990: 	    my $newfile=$udir.'/userfiles/'.$new;
 2991: 	    if (-e $newfile) {
 2992: 		&Failure($client, "exists\n", "$cmd:$tail");
 2993: 	    } elsif (! -e $oldfile) {
 2994: 		&Failure($client, "not_found\n", "$cmd:$tail");
 2995: 	    } else {
 2996: 		if (!rename($oldfile,$newfile)) {
 2997: 		    &Failure($client, "failed\n", "$cmd:$tail");
 2998: 		} else {
 2999: 		    &Reply($client, "ok\n", "$cmd:$tail");
 3000: 		}
 3001: 	    }
 3002: 	} else {
 3003: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 3004: 	}
 3005:     }
 3006:     return 1;
 3007: }
 3008: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
 3009: 
 3010: #
 3011: #  Checks if the specified user has an active session on the server
 3012: #  return ok if so, not_found if not
 3013: #
 3014: # Parameters:
 3015: #   cmd      - The request keyword that dispatched to tus.
 3016: #   tail     - The tail of the request (colon separated parameters).
 3017: #   client   - Filehandle open on the client.
 3018: # Return:
 3019: #    1.
 3020: sub user_has_session_handler {
 3021:     my ($cmd, $tail, $client) = @_;
 3022: 
 3023:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
 3024:     
 3025:     opendir(DIR,$perlvar{'lonIDsDir'});
 3026:     my $filename;
 3027:     while ($filename=readdir(DIR)) {
 3028: 	last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
 3029:     }
 3030:     if ($filename) {
 3031: 	&Reply($client, "ok\n", "$cmd:$tail");
 3032:     } else {
 3033: 	&Failure($client, "not_found\n", "$cmd:$tail");
 3034:     }
 3035:     return 1;
 3036: 
 3037: }
 3038: &register_handler("userhassession", \&user_has_session_handler, 0,1,0);
 3039: 
 3040: sub del_usersession_handler {
 3041:     my ($cmd, $tail, $client) = @_;
 3042: 
 3043:     my $result;
 3044:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
 3045:     if (($udom =~ /^$LONCAPA::match_domain$/) && ($uname =~ /^$LONCAPA::match_username$/)) {
 3046:         my $lonidsdir = $perlvar{'lonIDsDir'};
 3047:         if (-d $lonidsdir) {
 3048:             if (opendir(DIR,$lonidsdir)) {
 3049:                 my $filename;
 3050:                 while ($filename=readdir(DIR)) {
 3051:                     if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/) {
 3052:                         if (tie(my %oldenv,'GDBM_File',"$lonidsdir/$filename",
 3053:                                 &GDBM_READER(),0640)) {
 3054:                             my $linkedfile;
 3055:                             if (exists($oldenv{'user.linkedenv'})) {
 3056:                                 $linkedfile = $oldenv{'user.linkedenv'};
 3057:                             }
 3058:                             untie(%oldenv);
 3059:                             $result = unlink("$lonidsdir/$filename");
 3060:                             if ($result) {
 3061:                                 if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
 3062:                                     if (-l "$lonidsdir/$linkedfile.id") {
 3063:                                         unlink("$lonidsdir/$linkedfile.id");
 3064:                                     }
 3065:                                 }
 3066:                             }
 3067:                         } else {
 3068:                             $result = unlink("$lonidsdir/$filename");
 3069:                         }
 3070:                         last;
 3071:                     }
 3072:                 }
 3073:             }
 3074:         }
 3075:         if ($result == 1) {
 3076:             &Reply($client, "$result\n", "$cmd:$tail");
 3077:         } else {
 3078:             &Reply($client, "not_found\n", "$cmd:$tail");
 3079:         }
 3080:     } else {
 3081:         &Failure($client, "invalid_user\n", "$cmd:$tail");
 3082:     }
 3083:     return 1;
 3084: }
 3085: 
 3086: &register_handler("delusersession", \&del_usersession_handler, 0,1,0);
 3087: 
 3088: #
 3089: #  Authenticate access to a user file by checking that the token the user's 
 3090: #  passed also exists in their session file
 3091: #
 3092: # Parameters:
 3093: #   cmd      - The request keyword that dispatched to tus.
 3094: #   tail     - The tail of the request (colon separated parameters).
 3095: #   client   - Filehandle open on the client.
 3096: # Return:
 3097: #    1.
 3098: sub token_auth_user_file_handler {
 3099:     my ($cmd, $tail, $client) = @_;
 3100: 
 3101:     my ($fname, $session) = split(/:/, $tail);
 3102:     
 3103:     chomp($session);
 3104:     my $reply="non_auth";
 3105:     my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
 3106:     if (open(ENVIN,"$file")) {
 3107: 	flock(ENVIN,LOCK_SH);
 3108: 	tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
 3109: 	if (exists($disk_env{"userfile.$fname"})) {
 3110: 	    $reply="ok";
 3111: 	} else {
 3112: 	    foreach my $envname (keys(%disk_env)) {
 3113: 		if ($envname=~ m|^userfile\.\Q$fname\E|) {
 3114: 		    $reply="ok";
 3115: 		    last;
 3116: 		}
 3117: 	    }
 3118: 	}
 3119: 	untie(%disk_env);
 3120: 	close(ENVIN);
 3121: 	&Reply($client, \$reply, "$cmd:$tail");
 3122:     } else {
 3123: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
 3124:     }
 3125:     return 1;
 3126: 
 3127: }
 3128: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
 3129: 
 3130: #
 3131: #   Unsubscribe from a resource.
 3132: #
 3133: # Parameters:
 3134: #    $cmd      - The command that got us here.
 3135: #    $tail     - Tail of the command (remaining parameters).
 3136: #    $client   - File descriptor connected to client.
 3137: # Returns
 3138: #     0        - Requested to exit, caller should shut down.
 3139: #     1        - Continue processing.
 3140: #
 3141: sub unsubscribe_handler {
 3142:     my ($cmd, $tail, $client) = @_;
 3143: 
 3144:     my $userinput= "$cmd:$tail";
 3145:     
 3146:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
 3147: 
 3148:     &Debug("Unsubscribing $fname");
 3149:     if (-e $fname) {
 3150: 	&Debug("Exists");
 3151: 	&Reply($client, &unsub($fname,$clientip), $userinput);
 3152:     } else {
 3153: 	&Failure($client, "not_found\n", $userinput);
 3154:     }
 3155:     return 1;
 3156: }
 3157: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
 3158: 
 3159: #   Subscribe to a resource
 3160: #
 3161: # Parameters:
 3162: #    $cmd      - The command that got us here.
 3163: #    $tail     - Tail of the command (remaining parameters).
 3164: #    $client   - File descriptor connected to client.
 3165: # Returns
 3166: #     0        - Requested to exit, caller should shut down.
 3167: #     1        - Continue processing.
 3168: #
 3169: sub subscribe_handler {
 3170:     my ($cmd, $tail, $client)= @_;
 3171: 
 3172:     my $userinput  = "$cmd:$tail";
 3173: 
 3174:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
 3175: 
 3176:     return 1;
 3177: }
 3178: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
 3179: 
 3180: #
 3181: #   Determine the latest version of a resource (it looks for the highest
 3182: #   past version and then returns that +1)
 3183: #
 3184: # Parameters:
 3185: #    $cmd      - The command that got us here.
 3186: #    $tail     - Tail of the command (remaining parameters).
 3187: #                 (Should consist of an absolute path to a file)
 3188: #    $client   - File descriptor connected to client.
 3189: # Returns
 3190: #     0        - Requested to exit, caller should shut down.
 3191: #     1        - Continue processing.
 3192: #
 3193: sub current_version_handler {
 3194:     my ($cmd, $tail, $client) = @_;
 3195: 
 3196:     my $userinput= "$cmd:$tail";
 3197:    
 3198:     my $fname   = $tail;
 3199:     &Reply( $client, &currentversion($fname)."\n", $userinput);
 3200:     return 1;
 3201: 
 3202: }
 3203: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
 3204: 
 3205: #  Make an entry in a user's activity log.
 3206: #
 3207: # Parameters:
 3208: #    $cmd      - The command that got us here.
 3209: #    $tail     - Tail of the command (remaining parameters).
 3210: #    $client   - File descriptor connected to client.
 3211: # Returns
 3212: #     0        - Requested to exit, caller should shut down.
 3213: #     1        - Continue processing.
 3214: #
 3215: sub activity_log_handler {
 3216:     my ($cmd, $tail, $client) = @_;
 3217: 
 3218: 
 3219:     my $userinput= "$cmd:$tail";
 3220: 
 3221:     my ($udom,$uname,$what)=split(/:/,$tail);
 3222:     chomp($what);
 3223:     my $proname=&propath($udom,$uname);
 3224:     my $now=time;
 3225:     my $hfh;
 3226:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
 3227: 	print $hfh "$now:$clientname:$what\n";
 3228: 	&Reply( $client, "ok\n", $userinput); 
 3229:     } else {
 3230: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
 3231: 		 ."while attempting log\n", 
 3232: 		 $userinput);
 3233:     }
 3234: 
 3235:     return 1;
 3236: }
 3237: &register_handler("log", \&activity_log_handler, 0, 1, 0);
 3238: 
 3239: #
 3240: #   Put a namespace entry in a user profile hash.
 3241: #   My druthers would be for this to be an encrypted interaction too.
 3242: #   anything that might be an inadvertent covert channel about either
 3243: #   user authentication or user personal information....
 3244: #
 3245: # Parameters:
 3246: #    $cmd      - The command that got us here.
 3247: #    $tail     - Tail of the command (remaining parameters).
 3248: #    $client   - File descriptor connected to client.
 3249: # Returns
 3250: #     0        - Requested to exit, caller should shut down.
 3251: #     1        - Continue processing.
 3252: #
 3253: sub put_user_profile_entry {
 3254:     my ($cmd, $tail, $client)  = @_;
 3255: 
 3256:     my $userinput = "$cmd:$tail";
 3257:     
 3258:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
 3259:     if ($namespace ne 'roles') {
 3260: 	chomp($what);
 3261: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3262: 				  &GDBM_WRCREAT(),"P",$what);
 3263: 	if($hashref) {
 3264: 	    my @pairs=split(/\&/,$what);
 3265: 	    foreach my $pair (@pairs) {
 3266: 		my ($key,$value)=split(/=/,$pair);
 3267: 		$hashref->{$key}=$value;
 3268: 	    }
 3269: 	    if (&untie_user_hash($hashref)) {
 3270: 		&Reply( $client, "ok\n", $userinput);
 3271: 	    } else {
 3272: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 3273: 			"while attempting put\n", 
 3274: 			$userinput);
 3275: 	    }
 3276: 	} else {
 3277: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3278: 		     "while attempting put\n", $userinput);
 3279: 	}
 3280:     } else {
 3281:         &Failure( $client, "refused\n", $userinput);
 3282:     }
 3283:     
 3284:     return 1;
 3285: }
 3286: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
 3287: 
 3288: #   Put a piece of new data in hash, returns error if entry already exists
 3289: # Parameters:
 3290: #    $cmd      - The command that got us here.
 3291: #    $tail     - Tail of the command (remaining parameters).
 3292: #    $client   - File descriptor connected to client.
 3293: # Returns
 3294: #     0        - Requested to exit, caller should shut down.
 3295: #     1        - Continue processing.
 3296: #
 3297: sub newput_user_profile_entry {
 3298:     my ($cmd, $tail, $client)  = @_;
 3299: 
 3300:     my $userinput = "$cmd:$tail";
 3301: 
 3302:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
 3303:     if ($namespace eq 'roles') {
 3304:         &Failure( $client, "refused\n", $userinput);
 3305: 	return 1;
 3306:     }
 3307: 
 3308:     chomp($what);
 3309: 
 3310:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3311: 				 &GDBM_WRCREAT(),"N",$what);
 3312:     if(!$hashref) {
 3313: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3314: 		  "while attempting put\n", $userinput);
 3315: 	return 1;
 3316:     }
 3317: 
 3318:     my @pairs=split(/\&/,$what);
 3319:     foreach my $pair (@pairs) {
 3320: 	my ($key,$value)=split(/=/,$pair);
 3321: 	if (exists($hashref->{$key})) {
 3322:             if (!&untie_user_hash($hashref)) {
 3323:                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
 3324:                          "while attempting newput - early out as key exists");
 3325:             }
 3326:             &Failure($client, "key_exists: ".$key."\n",$userinput);
 3327:             return 1;
 3328: 	}
 3329:     }
 3330: 
 3331:     foreach my $pair (@pairs) {
 3332: 	my ($key,$value)=split(/=/,$pair);
 3333: 	$hashref->{$key}=$value;
 3334:     }
 3335: 
 3336:     if (&untie_user_hash($hashref)) {
 3337: 	&Reply( $client, "ok\n", $userinput);
 3338:     } else {
 3339: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 3340: 		 "while attempting put\n", 
 3341: 		 $userinput);
 3342:     }
 3343:     return 1;
 3344: }
 3345: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
 3346: 
 3347: # 
 3348: #   Increment a profile entry in the user history file.
 3349: #   The history contains keyword value pairs.  In this case,
 3350: #   The value itself is a pair of numbers.  The first, the current value
 3351: #   the second an increment that this function applies to the current
 3352: #   value.
 3353: #
 3354: # Parameters:
 3355: #    $cmd      - The command that got us here.
 3356: #    $tail     - Tail of the command (remaining parameters).
 3357: #    $client   - File descriptor connected to client.
 3358: # Returns
 3359: #     0        - Requested to exit, caller should shut down.
 3360: #     1        - Continue processing.
 3361: #
 3362: sub increment_user_value_handler {
 3363:     my ($cmd, $tail, $client) = @_;
 3364:     
 3365:     my $userinput   = "$cmd:$tail";
 3366:     
 3367:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
 3368:     if ($namespace ne 'roles') {
 3369:         chomp($what);
 3370: 	my $hashref = &tie_user_hash($udom, $uname,
 3371: 				     $namespace, &GDBM_WRCREAT(),
 3372: 				     "P",$what);
 3373: 	if ($hashref) {
 3374: 	    my @pairs=split(/\&/,$what);
 3375: 	    foreach my $pair (@pairs) {
 3376: 		my ($key,$value)=split(/=/,$pair);
 3377:                 $value = &unescape($value);
 3378: 		# We could check that we have a number...
 3379: 		if (! defined($value) || $value eq '') {
 3380: 		    $value = 1;
 3381: 		}
 3382: 		$hashref->{$key}+=$value;
 3383:                 if ($namespace eq 'nohist_resourcetracker') {
 3384:                     if ($hashref->{$key} < 0) {
 3385:                         $hashref->{$key} = 0;
 3386:                     }
 3387:                 }
 3388: 	    }
 3389: 	    if (&untie_user_hash($hashref)) {
 3390: 		&Reply( $client, "ok\n", $userinput);
 3391: 	    } else {
 3392: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 3393: 			 "while attempting inc\n", $userinput);
 3394: 	    }
 3395: 	} else {
 3396: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3397: 		     "while attempting inc\n", $userinput);
 3398: 	}
 3399:     } else {
 3400: 	&Failure($client, "refused\n", $userinput);
 3401:     }
 3402:     
 3403:     return 1;
 3404: }
 3405: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
 3406: 
 3407: #
 3408: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
 3409: #   Each 'role' a user has implies a set of permissions.  Adding a new role
 3410: #   for a person grants the permissions packaged with that role
 3411: #   to that user when the role is selected.
 3412: #
 3413: # Parameters:
 3414: #    $cmd       - The command string (rolesput).
 3415: #    $tail      - The remainder of the request line.  For rolesput this
 3416: #                 consists of a colon separated list that contains:
 3417: #                 The domain and user that is granting the role (logged).
 3418: #                 The domain and user that is getting the role.
 3419: #                 The roles being granted as a set of & separated pairs.
 3420: #                 each pair a key value pair.
 3421: #    $client    - File descriptor connected to the client.
 3422: # Returns:
 3423: #     0         - If the daemon should exit
 3424: #     1         - To continue processing.
 3425: #
 3426: #
 3427: sub roles_put_handler {
 3428:     my ($cmd, $tail, $client) = @_;
 3429: 
 3430:     my $userinput  = "$cmd:$tail";
 3431: 
 3432:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
 3433:     
 3434: 
 3435:     my $namespace='roles';
 3436:     chomp($what);
 3437:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3438: 				 &GDBM_WRCREAT(), "P",
 3439: 				 "$exedom:$exeuser:$what");
 3440:     #
 3441:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
 3442:     #  handle is open for the minimal amount of time.  Since the flush
 3443:     #  is done on close this improves the chances the log will be an un-
 3444:     #  corrupted ordered thing.
 3445:     if ($hashref) {
 3446: 	my $pass_entry = &get_auth_type($udom, $uname);
 3447: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
 3448: 	$auth_type = $auth_type.":";
 3449: 	my @pairs=split(/\&/,$what);
 3450: 	foreach my $pair (@pairs) {
 3451: 	    my ($key,$value)=split(/=/,$pair);
 3452: 	    &manage_permissions($key, $udom, $uname,
 3453: 			       $auth_type);
 3454: 	    $hashref->{$key}=$value;
 3455: 	}
 3456: 	if (&untie_user_hash($hashref)) {
 3457: 	    &Reply($client, "ok\n", $userinput);
 3458: 	} else {
 3459: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 3460: 		     "while attempting rolesput\n", $userinput);
 3461: 	}
 3462:     } else {
 3463: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3464: 		 "while attempting rolesput\n", $userinput);
 3465:     }
 3466:     return 1;
 3467: }
 3468: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
 3469: 
 3470: #
 3471: #   Deletes (removes) a role for a user.   This is equivalent to removing
 3472: #  a permissions package associated with the role from the user's profile.
 3473: #
 3474: # Parameters:
 3475: #     $cmd                 - The command (rolesdel)
 3476: #     $tail                - The remainder of the request line. This consists
 3477: #                             of:
 3478: #                             The domain and user requesting the change (logged)
 3479: #                             The domain and user being changed.
 3480: #                             The roles being revoked.  These are shipped to us
 3481: #                             as a bunch of & separated role name keywords.
 3482: #     $client              - The file handle open on the client.
 3483: # Returns:
 3484: #     1                    - Continue processing
 3485: #     0                    - Exit.
 3486: #
 3487: sub roles_delete_handler {
 3488:     my ($cmd, $tail, $client)  = @_;
 3489: 
 3490:     my $userinput    = "$cmd:$tail";
 3491:    
 3492:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
 3493:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
 3494: 	   "what = ".$what);
 3495:     my $namespace='roles';
 3496:     chomp($what);
 3497:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3498: 				 &GDBM_WRCREAT(), "D",
 3499: 				 "$exedom:$exeuser:$what");
 3500:     
 3501:     if ($hashref) {
 3502: 	my @rolekeys=split(/\&/,$what);
 3503: 	
 3504: 	foreach my $key (@rolekeys) {
 3505: 	    delete $hashref->{$key};
 3506: 	}
 3507: 	if (&untie_user_hash($hashref)) {
 3508: 	    &Reply($client, "ok\n", $userinput);
 3509: 	} else {
 3510: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 3511: 		     "while attempting rolesdel\n", $userinput);
 3512: 	}
 3513:     } else {
 3514:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3515: 		 "while attempting rolesdel\n", $userinput);
 3516:     }
 3517:     
 3518:     return 1;
 3519: }
 3520: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
 3521: 
 3522: # Unencrypted get from a user's profile database.  See 
 3523: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
 3524: # This function retrieves a keyed item from a specific named database in the
 3525: # user's directory.
 3526: #
 3527: # Parameters:
 3528: #   $cmd             - Command request keyword (get).
 3529: #   $tail            - Tail of the command.  This is a colon separated list
 3530: #                      consisting of the domain and username that uniquely
 3531: #                      identifies the profile,
 3532: #                      The 'namespace' which selects the gdbm file to 
 3533: #                      do the lookup in, 
 3534: #                      & separated list of keys to lookup.  Note that
 3535: #                      the values are returned as an & separated list too.
 3536: #   $client          - File descriptor open on the client.
 3537: # Returns:
 3538: #   1       - Continue processing.
 3539: #   0       - Exit.
 3540: #
 3541: sub get_profile_entry {
 3542:     my ($cmd, $tail, $client) = @_;
 3543: 
 3544:     my $userinput= "$cmd:$tail";
 3545:    
 3546:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 3547:     chomp($what);
 3548: 
 3549: 
 3550:     my $replystring = read_profile($udom, $uname, $namespace, $what);
 3551:     my ($first) = split(/:/,$replystring);
 3552:     if($first ne "error") {
 3553: 	&Reply($client, \$replystring, $userinput);
 3554:     } else {
 3555: 	&Failure($client, $replystring." while attempting get\n", $userinput);
 3556:     }
 3557:     return 1;
 3558: 
 3559: 
 3560: }
 3561: &register_handler("get", \&get_profile_entry, 0,1,0);
 3562: 
 3563: #
 3564: #  Process the encrypted get request.  Note that the request is sent
 3565: #  in clear, but the reply is encrypted.  This is a small covert channel:
 3566: #  information about the sensitive keys is given to the snooper.  Just not
 3567: #  information about the values of the sensitive key.  Hmm if I wanted to
 3568: #  know these I'd snoop for the egets. Get the profile item names from them
 3569: #  and then issue a get for them since there's no enforcement of the
 3570: #  requirement of an encrypted get for particular profile items.  If I
 3571: #  were re-doing this, I'd force the request to be encrypted as well as the
 3572: #  reply.  I'd also just enforce encrypted transactions for all gets since
 3573: #  that would prevent any covert channel snooping.
 3574: #
 3575: #  Parameters:
 3576: #     $cmd               - Command keyword of request (eget).
 3577: #     $tail              - Tail of the command.  See GetProfileEntry
 3578: #                          for more information about this.
 3579: #     $client            - File open on the client.
 3580: #  Returns:
 3581: #     1      - Continue processing
 3582: #     0      - server should exit.
 3583: sub get_profile_entry_encrypted {
 3584:     my ($cmd, $tail, $client) = @_;
 3585: 
 3586:     my $userinput = "$cmd:$tail";
 3587:    
 3588:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 3589:     chomp($what);
 3590:     my $qresult = read_profile($udom, $uname, $namespace, $what);
 3591:     my ($first) = split(/:/, $qresult);
 3592:     if($first ne "error") {
 3593: 	
 3594: 	if ($cipher) {
 3595: 	    my $cmdlength=length($qresult);
 3596: 	    $qresult.="         ";
 3597: 	    my $encqresult='';
 3598: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 3599: 		$encqresult.= unpack("H16", 
 3600: 				     $cipher->encrypt(substr($qresult,
 3601: 							     $encidx,
 3602: 							     8)));
 3603: 	    }
 3604: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
 3605: 	} else {
 3606: 		&Failure( $client, "error:no_key\n", $userinput);
 3607: 	    }
 3608:     } else {
 3609: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
 3610: 
 3611:     }
 3612:     
 3613:     return 1;
 3614: }
 3615: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
 3616: 
 3617: #
 3618: #   Deletes a key in a user profile database.
 3619: #   
 3620: #   Parameters:
 3621: #       $cmd                  - Command keyword (del).
 3622: #       $tail                 - Command tail.  IN this case a colon
 3623: #                               separated list containing:
 3624: #                               The domain and user that identifies uniquely
 3625: #                               the identity of the user.
 3626: #                               The profile namespace (name of the profile
 3627: #                               database file).
 3628: #                               & separated list of keywords to delete.
 3629: #       $client              - File open on client socket.
 3630: # Returns:
 3631: #     1   - Continue processing
 3632: #     0   - Exit server.
 3633: #
 3634: #
 3635: sub delete_profile_entry {
 3636:     my ($cmd, $tail, $client) = @_;
 3637: 
 3638:     my $userinput = "cmd:$tail";
 3639: 
 3640:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 3641:     chomp($what);
 3642:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3643: 				 &GDBM_WRCREAT(),
 3644: 				 "D",$what);
 3645:     if ($hashref) {
 3646:         my @keys=split(/\&/,$what);
 3647: 	foreach my $key (@keys) {
 3648: 	    delete($hashref->{$key});
 3649: 	}
 3650: 	if (&untie_user_hash($hashref)) {
 3651: 	    &Reply($client, "ok\n", $userinput);
 3652: 	} else {
 3653: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3654: 		    "while attempting del\n", $userinput);
 3655: 	}
 3656:     } else {
 3657: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3658: 		 "while attempting del\n", $userinput);
 3659:     }
 3660:     return 1;
 3661: }
 3662: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
 3663: 
 3664: #
 3665: #  List the set of keys that are defined in a profile database file.
 3666: #  A successful reply from this will contain an & separated list of
 3667: #  the keys. 
 3668: # Parameters:
 3669: #     $cmd              - Command request (keys).
 3670: #     $tail             - Remainder of the request, a colon separated
 3671: #                         list containing domain/user that identifies the
 3672: #                         user being queried, and the database namespace
 3673: #                         (database filename essentially).
 3674: #     $client           - File open on the client.
 3675: #  Returns:
 3676: #    1    - Continue processing.
 3677: #    0    - Exit the server.
 3678: #
 3679: sub get_profile_keys {
 3680:     my ($cmd, $tail, $client) = @_;
 3681: 
 3682:     my $userinput = "$cmd:$tail";
 3683: 
 3684:     my ($udom,$uname,$namespace)=split(/:/,$tail);
 3685:     my $qresult='';
 3686:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3687: 				  &GDBM_READER());
 3688:     if ($hashref) {
 3689: 	foreach my $key (keys %$hashref) {
 3690: 	    $qresult.="$key&";
 3691: 	}
 3692: 	if (&untie_user_hash($hashref)) {
 3693: 	    $qresult=~s/\&$//;
 3694: 	    &Reply($client, \$qresult, $userinput);
 3695: 	} else {
 3696: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3697: 		    "while attempting keys\n", $userinput);
 3698: 	}
 3699:     } else {
 3700: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3701: 		 "while attempting keys\n", $userinput);
 3702:     }
 3703:    
 3704:     return 1;
 3705: }
 3706: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
 3707: 
 3708: #
 3709: #   Dump the contents of a user profile database.
 3710: #   Note that this constitutes a very large covert channel too since
 3711: #   the dump will return sensitive information that is not encrypted.
 3712: #   The naive security assumption is that the session negotiation ensures
 3713: #   our client is trusted and I don't believe that's assured at present.
 3714: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
 3715: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
 3716: # 
 3717: #  Parameters:
 3718: #     $cmd           - The command request keyword (currentdump).
 3719: #     $tail          - Remainder of the request, consisting of a colon
 3720: #                      separated list that has the domain/username and
 3721: #                      the namespace to dump (database file).
 3722: #     $client        - file open on the remote client.
 3723: # Returns:
 3724: #     1    - Continue processing.
 3725: #     0    - Exit the server.
 3726: #
 3727: sub dump_profile_database {
 3728:     my ($cmd, $tail, $client) = @_;
 3729: 
 3730:     my $res = LONCAPA::Lond::dump_profile_database($tail);
 3731: 
 3732:     if ($res =~ /^error:/) {
 3733:         Failure($client, \$res, "$cmd:$tail");
 3734:     } else {
 3735:         Reply($client, \$res, "$cmd:$tail");
 3736:     }
 3737: 
 3738:     return 1;  
 3739: 
 3740:     #TODO remove 
 3741:     my $userinput = "$cmd:$tail";
 3742:    
 3743:     my ($udom,$uname,$namespace) = split(/:/,$tail);
 3744:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3745: 				 &GDBM_READER());
 3746:     if ($hashref) {
 3747: 	# Structure of %data:
 3748: 	# $data{$symb}->{$parameter}=$value;
 3749: 	# $data{$symb}->{'v.'.$parameter}=$version;
 3750: 	# since $parameter will be unescaped, we do not
 3751:  	# have to worry about silly parameter names...
 3752: 	
 3753:         my $qresult='';
 3754: 	my %data = ();                     # A hash of anonymous hashes..
 3755: 	while (my ($key,$value) = each(%$hashref)) {
 3756: 	    my ($v,$symb,$param) = split(/:/,$key);
 3757: 	    next if ($v eq 'version' || $symb eq 'keys');
 3758: 	    next if (exists($data{$symb}) && 
 3759: 		     exists($data{$symb}->{$param}) &&
 3760: 		     $data{$symb}->{'v.'.$param} > $v);
 3761: 	    $data{$symb}->{$param}=$value;
 3762: 	    $data{$symb}->{'v.'.$param}=$v;
 3763: 	}
 3764: 	if (&untie_user_hash($hashref)) {
 3765: 	    while (my ($symb,$param_hash) = each(%data)) {
 3766: 		while(my ($param,$value) = each (%$param_hash)){
 3767: 		    next if ($param =~ /^v\./);       # Ignore versions...
 3768: 		    #
 3769: 		    #   Just dump the symb=value pairs separated by &
 3770: 		    #
 3771: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
 3772: 		}
 3773: 	    }
 3774: 	    chop($qresult);
 3775: 	    &Reply($client , \$qresult, $userinput);
 3776: 	} else {
 3777: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 3778: 		     "while attempting currentdump\n", $userinput);
 3779: 	}
 3780:     } else {
 3781: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3782: 		"while attempting currentdump\n", $userinput);
 3783:     }
 3784: 
 3785:     return 1;
 3786: }
 3787: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
 3788: 
 3789: #
 3790: #   Dump a profile database with an optional regular expression
 3791: #   to match against the keys.  In this dump, no effort is made
 3792: #   to separate symb from version information. Presumably the
 3793: #   databases that are dumped by this command are of a different
 3794: #   structure.  Need to look at this and improve the documentation of
 3795: #   both this and the currentdump handler.
 3796: # Parameters:
 3797: #    $cmd                     - The command keyword.
 3798: #    $tail                    - All of the characters after the $cmd:
 3799: #                               These are expected to be a colon
 3800: #                               separated list containing:
 3801: #                               domain/user - identifying the user.
 3802: #                               namespace   - identifying the database.
 3803: #                               regexp      - optional regular expression
 3804: #                                             that is matched against
 3805: #                                             database keywords to do
 3806: #                                             selective dumps.
 3807: #                               range       - optional range of entries
 3808: #                                             e.g., 10-20 would return the
 3809: #                                             10th to 19th items, etc.  
 3810: #   $client                   - Channel open on the client.
 3811: # Returns:
 3812: #    1    - Continue processing.
 3813: # Side effects:
 3814: #    response is written to $client.
 3815: #
 3816: sub dump_with_regexp {
 3817:     my ($cmd, $tail, $client) = @_;
 3818: 
 3819:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
 3820:     
 3821:     if ($res =~ /^error:/) {
 3822:         Failure($client, \$res, "$cmd:$tail");
 3823:     } else {
 3824:         Reply($client, \$res, "$cmd:$tail");
 3825:     }
 3826: 
 3827:     return 1;
 3828: }
 3829: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
 3830: 
 3831: #  Store a set of key=value pairs associated with a versioned name.
 3832: #
 3833: #  Parameters:
 3834: #    $cmd                - Request command keyword.
 3835: #    $tail               - Tail of the request.  This is a colon
 3836: #                          separated list containing:
 3837: #                          domain/user - User and authentication domain.
 3838: #                          namespace   - Name of the database being modified
 3839: #                          rid         - Resource keyword to modify.
 3840: #                          what        - new value associated with rid.
 3841: #                          laststore   - (optional) version=timestamp
 3842: #                                        for most recent transaction for rid
 3843: #                                        in namespace, when cstore was called
 3844: #
 3845: #    $client             - Socket open on the client.
 3846: #
 3847: #
 3848: #  Returns:
 3849: #      1 (keep on processing).
 3850: #  Side-Effects:
 3851: #    Writes to the client
 3852: #    Successful storage will cause either 'ok', or, if $laststore was included
 3853: #    in the tail of the request, and the version number for the last transaction
 3854: #    is larger than the version in $laststore, delay:$numtrans , where $numtrans
 3855: #    is the number of store evevnts recorded for rid in namespace since
 3856: #    lonnet::store() was called by the client.
 3857: #
 3858: sub store_handler {
 3859:     my ($cmd, $tail, $client) = @_;
 3860:  
 3861:     my $userinput = "$cmd:$tail";
 3862:     chomp($tail);
 3863:     my ($udom,$uname,$namespace,$rid,$what,$laststore) =split(/:/,$tail);
 3864:     if ($namespace ne 'roles') {
 3865: 
 3866: 	my @pairs=split(/\&/,$what);
 3867: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
 3868: 				       &GDBM_WRCREAT(), "S",
 3869: 				       "$rid:$what");
 3870: 	if ($hashref) {
 3871: 	    my $now = time;
 3872:             my $numtrans;
 3873:             if ($laststore) {
 3874:                 my ($previousversion,$previoustime) = split(/\=/,$laststore);
 3875:                 my ($lastversion,$lasttime) = (0,0);
 3876:                 $lastversion = $hashref->{"version:$rid"};
 3877:                 if ($lastversion) {
 3878:                     $lasttime = $hashref->{"$lastversion:$rid:timestamp"};
 3879:                 }
 3880:                 if (($previousversion) && ($previousversion !~ /\D/)) {
 3881:                     if (($lastversion > $previousversion) && ($lasttime >= $previoustime)) {
 3882:                         $numtrans = $lastversion - $previousversion;
 3883:                     }
 3884:                 } elsif ($lastversion) {
 3885:                     $numtrans = $lastversion;
 3886:                 }
 3887:                 if ($numtrans) {
 3888:                     $numtrans =~ s/D//g;
 3889:                 }
 3890:             }
 3891: 	    $hashref->{"version:$rid"}++;
 3892: 	    my $version=$hashref->{"version:$rid"};
 3893: 	    my $allkeys=''; 
 3894: 	    foreach my $pair (@pairs) {
 3895: 		my ($key,$value)=split(/=/,$pair);
 3896: 		$allkeys.=$key.':';
 3897: 		$hashref->{"$version:$rid:$key"}=$value;
 3898: 	    }
 3899: 	    $hashref->{"$version:$rid:timestamp"}=$now;
 3900: 	    $allkeys.='timestamp';
 3901: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
 3902: 	    if (&untie_user_hash($hashref)) {
 3903:                 my $msg = 'ok';
 3904:                 if ($numtrans) {
 3905:                     $msg = 'delay:'.$numtrans;
 3906:                 }
 3907: 		&Reply($client, "$msg\n", $userinput);
 3908: 	    } else {
 3909: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3910: 			"while attempting store\n", $userinput);
 3911: 	    }
 3912: 	} else {
 3913: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3914: 		     "while attempting store\n", $userinput);
 3915: 	}
 3916:     } else {
 3917: 	&Failure($client, "refused\n", $userinput);
 3918:     }
 3919: 
 3920:     return 1;
 3921: }
 3922: &register_handler("store", \&store_handler, 0, 1, 0);
 3923: 
 3924: #  Modify a set of key=value pairs associated with a versioned name.
 3925: #
 3926: #  Parameters:
 3927: #    $cmd                - Request command keyword.
 3928: #    $tail               - Tail of the request.  This is a colon
 3929: #                          separated list containing:
 3930: #                          domain/user - User and authentication domain.
 3931: #                          namespace   - Name of the database being modified
 3932: #                          rid         - Resource keyword to modify.
 3933: #                          v           - Version item to modify
 3934: #                          what        - new value associated with rid.
 3935: #
 3936: #    $client             - Socket open on the client.
 3937: #
 3938: #
 3939: #  Returns:
 3940: #      1 (keep on processing).
 3941: #  Side-Effects:
 3942: #    Writes to the client
 3943: sub putstore_handler {
 3944:     my ($cmd, $tail, $client) = @_;
 3945:  
 3946:     my $userinput = "$cmd:$tail";
 3947: 
 3948:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
 3949:     if ($namespace ne 'roles') {
 3950: 
 3951: 	chomp($what);
 3952: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
 3953: 				       &GDBM_WRCREAT(), "M",
 3954: 				       "$rid:$v:$what");
 3955: 	if ($hashref) {
 3956: 	    my $now = time;
 3957: 	    my %data = &hash_extract($what);
 3958: 	    my @allkeys;
 3959: 	    while (my($key,$value) = each(%data)) {
 3960: 		push(@allkeys,$key);
 3961: 		$hashref->{"$v:$rid:$key"} = $value;
 3962: 	    }
 3963: 	    my $allkeys = join(':',@allkeys);
 3964: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
 3965: 
 3966: 	    if (&untie_user_hash($hashref)) {
 3967: 		&Reply($client, "ok\n", $userinput);
 3968: 	    } else {
 3969: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3970: 			"while attempting store\n", $userinput);
 3971: 	    }
 3972: 	} else {
 3973: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3974: 		     "while attempting store\n", $userinput);
 3975: 	}
 3976:     } else {
 3977: 	&Failure($client, "refused\n", $userinput);
 3978:     }
 3979: 
 3980:     return 1;
 3981: }
 3982: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
 3983: 
 3984: sub hash_extract {
 3985:     my ($str)=@_;
 3986:     my %hash;
 3987:     foreach my $pair (split(/\&/,$str)) {
 3988: 	my ($key,$value)=split(/=/,$pair);
 3989: 	$hash{$key}=$value;
 3990:     }
 3991:     return (%hash);
 3992: }
 3993: sub hash_to_str {
 3994:     my ($hash_ref)=@_;
 3995:     my $str;
 3996:     foreach my $key (keys(%$hash_ref)) {
 3997: 	$str.=$key.'='.$hash_ref->{$key}.'&';
 3998:     }
 3999:     $str=~s/\&$//;
 4000:     return $str;
 4001: }
 4002: 
 4003: #
 4004: #  Dump out all versions of a resource that has key=value pairs associated
 4005: # with it for each version.  These resources are built up via the store
 4006: # command.
 4007: #
 4008: #  Parameters:
 4009: #     $cmd               - Command keyword.
 4010: #     $tail              - Remainder of the request which consists of:
 4011: #                          domain/user   - User and auth. domain.
 4012: #                          namespace     - name of resource database.
 4013: #                          rid           - Resource id.
 4014: #    $client             - socket open on the client.
 4015: #
 4016: # Returns:
 4017: #      1  indicating the caller should not yet exit.
 4018: # Side-effects:
 4019: #   Writes a reply to the client.
 4020: #   The reply is a string of the following shape:
 4021: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
 4022: #    Where the 1 above represents version 1.
 4023: #    this continues for all pairs of keys in all versions.
 4024: #
 4025: #
 4026: #    
 4027: #
 4028: sub restore_handler {
 4029:     my ($cmd, $tail, $client) = @_;
 4030: 
 4031:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
 4032:     my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
 4033:     $namespace=~s/\//\_/g;
 4034:     $namespace = &LONCAPA::clean_username($namespace);
 4035: 
 4036:     chomp($rid);
 4037:     my $qresult='';
 4038:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
 4039:     if ($hashref) {
 4040: 	my $version=$hashref->{"version:$rid"};
 4041: 	$qresult.="version=$version&";
 4042: 	my $scope;
 4043: 	for ($scope=1;$scope<=$version;$scope++) {
 4044: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
 4045: 	    my @keys=split(/:/,$vkeys);
 4046: 	    my $key;
 4047: 	    $qresult.="$scope:keys=$vkeys&";
 4048: 	    foreach $key (@keys) {
 4049: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
 4050: 	    }                                  
 4051: 	}
 4052: 	if (&untie_user_hash($hashref)) {
 4053: 	    $qresult=~s/\&$//;
 4054: 	    &Reply( $client, \$qresult, $userinput);
 4055: 	} else {
 4056: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4057: 		    "while attempting restore\n", $userinput);
 4058: 	}
 4059:     } else {
 4060: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 4061: 		"while attempting restore\n", $userinput);
 4062:     }
 4063:   
 4064:     return 1;
 4065: 
 4066: 
 4067: }
 4068: &register_handler("restore", \&restore_handler, 0,1,0);
 4069: 
 4070: #
 4071: #   Add a chat message to a synchronous discussion board.
 4072: #
 4073: # Parameters:
 4074: #    $cmd                - Request keyword.
 4075: #    $tail               - Tail of the command. A colon separated list
 4076: #                          containing:
 4077: #                          cdom    - Domain on which the chat board lives
 4078: #                          cnum    - Course containing the chat board.
 4079: #                          newpost - Body of the posting.
 4080: #                          group   - Optional group, if chat board is only 
 4081: #                                    accessible in a group within the course 
 4082: #   $client              - Socket open on the client.
 4083: # Returns:
 4084: #   1    - Indicating caller should keep on processing.
 4085: #
 4086: # Side-effects:
 4087: #   writes a reply to the client.
 4088: #
 4089: #
 4090: sub send_chat_handler {
 4091:     my ($cmd, $tail, $client) = @_;
 4092: 
 4093:     
 4094:     my $userinput = "$cmd:$tail";
 4095: 
 4096:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
 4097:     &chat_add($cdom,$cnum,$newpost,$group);
 4098:     &Reply($client, "ok\n", $userinput);
 4099: 
 4100:     return 1;
 4101: }
 4102: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
 4103: 
 4104: #
 4105: #   Retrieve the set of chat messages from a discussion board.
 4106: #
 4107: #  Parameters:
 4108: #    $cmd             - Command keyword that initiated the request.
 4109: #    $tail            - Remainder of the request after the command
 4110: #                       keyword.  In this case a colon separated list of
 4111: #                       chat domain    - Which discussion board.
 4112: #                       chat id        - Discussion thread(?)
 4113: #                       domain/user    - Authentication domain and username
 4114: #                                        of the requesting person.
 4115: #                       group          - Optional course group containing
 4116: #                                        the board.      
 4117: #   $client           - Socket open on the client program.
 4118: # Returns:
 4119: #    1     - continue processing
 4120: # Side effects:
 4121: #    Response is written to the client.
 4122: #
 4123: sub retrieve_chat_handler {
 4124:     my ($cmd, $tail, $client) = @_;
 4125: 
 4126: 
 4127:     my $userinput = "$cmd:$tail";
 4128: 
 4129:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
 4130:     my $reply='';
 4131:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
 4132: 	$reply.=&escape($_).':';
 4133:     }
 4134:     $reply=~s/\:$//;
 4135:     &Reply($client, \$reply, $userinput);
 4136: 
 4137: 
 4138:     return 1;
 4139: }
 4140: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
 4141: 
 4142: #
 4143: #  Initiate a query of an sql database.  SQL query repsonses get put in
 4144: #  a file for later retrieval.  This prevents sql query results from
 4145: #  bottlenecking the system.  Note that with loncnew, perhaps this is
 4146: #  less of an issue since multiple outstanding requests can be concurrently
 4147: #  serviced.
 4148: #
 4149: #  Parameters:
 4150: #     $cmd       - Command keyword that initiated the request.
 4151: #     $tail      - Remainder of the command after the keyword.
 4152: #                  For this function, this consists of a query and
 4153: #                  3 arguments that are self-documentingly labelled
 4154: #                  in the original arg1, arg2, arg3.
 4155: #     $client    - Socket open on the client.
 4156: # Return:
 4157: #    1   - Indicating processing should continue.
 4158: # Side-effects:
 4159: #    a reply is written to $client.
 4160: #
 4161: sub send_query_handler {
 4162:     my ($cmd, $tail, $client) = @_;
 4163: 
 4164:     my $userinput = "$cmd:$tail";
 4165: 
 4166:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
 4167:     $query=~s/\n*$//g;
 4168:     if (($query eq 'usersearch') || ($query eq 'instdirsearch')) {
 4169:         my $usersearchconf = &get_usersearch_config($currentdomainid,'directorysrch');
 4170:         my $earlyout;
 4171:         if (ref($usersearchconf) eq 'HASH') {
 4172:             if ($currentdomainid eq $clienthomedom) {
 4173:                 if ($query eq 'usersearch') {
 4174:                     if ($usersearchconf->{'lcavailable'} eq '0') {
 4175:                         $earlyout = 1;
 4176:                     }
 4177:                 } else {
 4178:                     if ($usersearchconf->{'available'} eq '0') {
 4179:                         $earlyout = 1;
 4180:                     }
 4181:                 }
 4182:             } else {
 4183:                 if ($query eq 'usersearch') {
 4184:                     if ($usersearchconf->{'lclocalonly'}) {
 4185:                         $earlyout = 1;
 4186:                     }
 4187:                 } else {
 4188:                     if ($usersearchconf->{'localonly'}) {
 4189:                         $earlyout = 1;
 4190:                     }
 4191:                 }
 4192:             }
 4193:         }
 4194:         if ($earlyout) {
 4195:             &Reply($client, "query_not_authorized\n");
 4196:             return 1;
 4197:         }
 4198:     }
 4199:     &Reply($client, "". &sql_reply("$clientname\&$query".
 4200: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
 4201: 	  $userinput);
 4202:     
 4203:     return 1;
 4204: }
 4205: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
 4206: 
 4207: #
 4208: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
 4209: #   The query is submitted via a "querysend" transaction.
 4210: #   There it is passed on to the lonsql daemon, queued and issued to
 4211: #   mysql.
 4212: #     This transaction is invoked when the sql transaction is complete
 4213: #   it stores the query results in flie and indicates query completion.
 4214: #   presumably local software then fetches this response... I'm guessing
 4215: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
 4216: #   lonsql on completion of the query interacts with the lond of our
 4217: #   client to do a query reply storing two files:
 4218: #    - id     - The results of the query.
 4219: #    - id.end - Indicating the transaction completed. 
 4220: #    NOTE: id is a unique id assigned to the query and querysend time.
 4221: # Parameters:
 4222: #    $cmd        - Command keyword that initiated this request.
 4223: #    $tail       - Remainder of the tail.  In this case that's a colon
 4224: #                  separated list containing the query Id and the 
 4225: #                  results of the query.
 4226: #    $client     - Socket open on the client.
 4227: # Return:
 4228: #    1           - Indicating that we should continue processing.
 4229: # Side effects:
 4230: #    ok written to the client.
 4231: #
 4232: sub reply_query_handler {
 4233:     my ($cmd, $tail, $client) = @_;
 4234: 
 4235: 
 4236:     my $userinput = "$cmd:$tail";
 4237: 
 4238:     my ($id,$reply)=split(/:/,$tail); 
 4239:     my $store;
 4240:     my $execdir=$perlvar{'lonDaemons'};
 4241:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
 4242: 	$reply=~s/\&/\n/g;
 4243: 	print $store $reply;
 4244: 	close $store;
 4245: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
 4246: 	print $store2 "done\n";
 4247: 	close $store2;
 4248: 	&Reply($client, "ok\n", $userinput);
 4249:     } else {
 4250: 	&Failure($client, "error: ".($!+0)
 4251: 		." IO::File->new Failed ".
 4252: 		"while attempting queryreply\n", $userinput);
 4253:     }
 4254:  
 4255: 
 4256:     return 1;
 4257: }
 4258: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
 4259: 
 4260: #
 4261: #  Process the courseidput request.  Not quite sure what this means
 4262: #  at the system level sense.  It appears a gdbm file in the 
 4263: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
 4264: #  a set of entries made in that database.
 4265: #
 4266: # Parameters:
 4267: #   $cmd      - The command keyword that initiated this request.
 4268: #   $tail     - Tail of the command.  In this case consists of a colon
 4269: #               separated list contaning the domain to apply this to and
 4270: #               an ampersand separated list of keyword=value pairs.
 4271: #               Each value is a colon separated list that includes:  
 4272: #               description, institutional code and course owner.
 4273: #               For backward compatibility with versions included
 4274: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
 4275: #               code and/or course owner are preserved from the existing 
 4276: #               record when writing a new record in response to 1.1 or 
 4277: #               1.2 implementations of lonnet::flushcourselogs().   
 4278: #                      
 4279: #   $client   - Socket open on the client.
 4280: # Returns:
 4281: #   1    - indicating that processing should continue
 4282: #
 4283: # Side effects:
 4284: #   reply is written to the client.
 4285: #
 4286: sub put_course_id_handler {
 4287:     my ($cmd, $tail, $client) = @_;
 4288: 
 4289: 
 4290:     my $userinput = "$cmd:$tail";
 4291: 
 4292:     my ($udom, $what) = split(/:/, $tail,2);
 4293:     chomp($what);
 4294:     my $now=time;
 4295:     my @pairs=split(/\&/,$what);
 4296: 
 4297:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 4298:     if ($hashref) {
 4299: 	foreach my $pair (@pairs) {
 4300:             my ($key,$courseinfo) = split(/=/,$pair,2);
 4301:             $courseinfo =~ s/=/:/g;
 4302:             if (defined($hashref->{$key})) {
 4303:                 my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
 4304:                 if (ref($value) eq 'HASH') {
 4305:                     my @items = ('description','inst_code','owner','type');
 4306:                     my @new_items = split(/:/,$courseinfo,-1);
 4307:                     my %storehash; 
 4308:                     for (my $i=0; $i<@new_items; $i++) {
 4309:                         $storehash{$items[$i]} = &unescape($new_items[$i]);
 4310:                     }
 4311:                     $hashref->{$key} = 
 4312:                         &Apache::lonnet::freeze_escape(\%storehash);
 4313:                     my $unesc_key = &unescape($key);
 4314:                     $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
 4315:                     next;
 4316:                 }
 4317:             }
 4318:             my @current_items = split(/:/,$hashref->{$key},-1);
 4319:             shift(@current_items); # remove description
 4320:             pop(@current_items);   # remove last access
 4321:             my $numcurrent = scalar(@current_items);
 4322:             if ($numcurrent > 3) {
 4323:                 $numcurrent = 3;
 4324:             }
 4325:             my @new_items = split(/:/,$courseinfo,-1);
 4326:             my $numnew = scalar(@new_items);
 4327:             if ($numcurrent > 0) {
 4328:                 if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2 
 4329:                     for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
 4330:                         $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
 4331:                     }
 4332:                 }
 4333:             }
 4334:             $hashref->{$key}=$courseinfo.':'.$now;
 4335: 	}
 4336: 	if (&untie_domain_hash($hashref)) {
 4337: 	    &Reply( $client, "ok\n", $userinput);
 4338: 	} else {
 4339: 	    &Failure($client, "error: ".($!+0)
 4340: 		     ." untie(GDBM) Failed ".
 4341: 		     "while attempting courseidput\n", $userinput);
 4342: 	}
 4343:     } else {
 4344: 	&Failure($client, "error: ".($!+0)
 4345: 		 ." tie(GDBM) Failed ".
 4346: 		 "while attempting courseidput\n", $userinput);
 4347:     }
 4348: 
 4349:     return 1;
 4350: }
 4351: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
 4352: 
 4353: sub put_course_id_hash_handler {
 4354:     my ($cmd, $tail, $client) = @_;
 4355:     my $userinput = "$cmd:$tail";
 4356:     my ($udom,$mode,$what) = split(/:/, $tail,3);
 4357:     chomp($what);
 4358:     my $now=time;
 4359:     my @pairs=split(/\&/,$what);
 4360:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 4361:     if ($hashref) {
 4362:         foreach my $pair (@pairs) {
 4363:             my ($key,$value)=split(/=/,$pair);
 4364:             my $unesc_key = &unescape($key);
 4365:             if ($mode ne 'timeonly') {
 4366:                 if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
 4367:                     my $curritems = &Apache::lonnet::thaw_unescape($key); 
 4368:                     if (ref($curritems) ne 'HASH') {
 4369:                         my @current_items = split(/:/,$hashref->{$key},-1);
 4370:                         my $lasttime = pop(@current_items);
 4371:                         $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
 4372:                     } else {
 4373:                         $hashref->{&escape('lasttime:'.$unesc_key)} = '';
 4374:                     }
 4375:                 } 
 4376:                 $hashref->{$key} = $value;
 4377:             }
 4378:             if ($mode ne 'notime') {
 4379:                 $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
 4380:             }
 4381:         }
 4382:         if (&untie_domain_hash($hashref)) {
 4383:             &Reply($client, "ok\n", $userinput);
 4384:         } else {
 4385:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4386:                      "while attempting courseidputhash\n", $userinput);
 4387:         }
 4388:     } else {
 4389:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 4390:                   "while attempting courseidputhash\n", $userinput);
 4391:     }
 4392:     return 1;
 4393: }
 4394: &register_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
 4395: 
 4396: #  Retrieves the value of a course id resource keyword pattern
 4397: #  defined since a starting date.  Both the starting date and the
 4398: #  keyword pattern are optional.  If the starting date is not supplied it
 4399: #  is treated as the beginning of time.  If the pattern is not found,
 4400: #  it is treatred as "." matching everything.
 4401: #
 4402: #  Parameters:
 4403: #     $cmd     - Command keyword that resulted in us being dispatched.
 4404: #     $tail    - The remainder of the command that, in this case, consists
 4405: #                of a colon separated list of:
 4406: #                 domain   - The domain in which the course database is 
 4407: #                            defined.
 4408: #                 since    - Optional parameter describing the minimum
 4409: #                            time of definition(?) of the resources that
 4410: #                            will match the dump.
 4411: #                 description - regular expression that is used to filter
 4412: #                            the dump.  Only keywords matching this regexp
 4413: #                            will be used.
 4414: #                 institutional code - optional supplied code to filter 
 4415: #                            the dump. Only courses with an institutional code 
 4416: #                            that match the supplied code will be returned.
 4417: #                 owner    - optional supplied username and domain of owner to
 4418: #                            filter the dump.  Only courses for which the course
 4419: #                            owner matches the supplied username and/or domain
 4420: #                            will be returned. Pre-2.2.0 legacy entries from 
 4421: #                            nohist_courseiddump will only contain usernames.
 4422: #                 type     - optional parameter for selection 
 4423: #                 regexp_ok - if 1 or -1 allow the supplied institutional code
 4424: #                            filter to behave as a regular expression:
 4425: #	                      1 will not exclude the course if the instcode matches the RE 
 4426: #                            -1 will exclude the course if the instcode matches the RE
 4427: #                 rtn_as_hash - whether to return the information available for
 4428: #                            each matched item as a frozen hash of all 
 4429: #                            key, value pairs in the item's hash, or as a 
 4430: #                            colon-separated list of (in order) description,
 4431: #                            institutional code, and course owner.
 4432: #                 selfenrollonly - filter by courses allowing self-enrollment  
 4433: #                                  now or in the future (selfenrollonly = 1).
 4434: #                 catfilter - filter by course category, assigned to a course 
 4435: #                             using manually defined categories (i.e., not
 4436: #                             self-cataloging based on on institutional code).   
 4437: #                 showhidden - include course in results even if course  
 4438: #                              was set to be excluded from course catalog (DC only).
 4439: #                 caller -  if set to 'coursecatalog', courses set to be hidden
 4440: #                           from course catalog will be excluded from results (unless
 4441: #                           overridden by "showhidden".
 4442: #                 cloner - escaped username:domain of course cloner (if picking course to
 4443: #                          clone).
 4444: #                 cc_clone_list - escaped comma separated list of courses for which 
 4445: #                                 course cloner has active CC role (and so can clone
 4446: #                                 automatically).
 4447: #                 cloneonly - filter by courses for which cloner has rights to clone.
 4448: #                 createdbefore - include courses for which creation date preceeded this date.
 4449: #                 createdafter - include courses for which creation date followed this date.
 4450: #                 creationcontext - include courses created in specified context 
 4451: #
 4452: #                 domcloner - flag to indicate if user can create CCs in course's domain.
 4453: #                             If so, ability to clone course is automatic.
 4454: #                 hasuniquecode - filter by courses for which a six character unique code has 
 4455: #                                 been set.
 4456: #
 4457: #     $client  - The socket open on the client.
 4458: # Returns:
 4459: #    1     - Continue processing.
 4460: # Side Effects:
 4461: #   a reply is written to $client.
 4462: sub dump_course_id_handler {
 4463:     my ($cmd, $tail, $client) = @_;
 4464: 
 4465:     my $res = LONCAPA::Lond::dump_course_id_handler($tail);
 4466:     if ($res =~ /^error:/) {
 4467:         Failure($client, \$res, "$cmd:$tail");
 4468:     } else {
 4469:         Reply($client, \$res, "$cmd:$tail");
 4470:     }
 4471: 
 4472:     return 1;  
 4473: 
 4474:     #TODO remove
 4475:     my $userinput = "$cmd:$tail";
 4476: 
 4477:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
 4478:         $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
 4479:         $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
 4480:         $creationcontext,$domcloner,$hasuniquecode) =split(/:/,$tail);
 4481:     my $now = time;
 4482:     my ($cloneruname,$clonerudom,%cc_clone);
 4483:     if (defined($description)) {
 4484: 	$description=&unescape($description);
 4485:     } else {
 4486: 	$description='.';
 4487:     }
 4488:     if (defined($instcodefilter)) {
 4489:         $instcodefilter=&unescape($instcodefilter);
 4490:     } else {
 4491:         $instcodefilter='.';
 4492:     }
 4493:     my ($ownerunamefilter,$ownerdomfilter);
 4494:     if (defined($ownerfilter)) {
 4495:         $ownerfilter=&unescape($ownerfilter);
 4496:         if ($ownerfilter ne '.' && defined($ownerfilter)) {
 4497:             if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
 4498:                  $ownerunamefilter = $1;
 4499:                  $ownerdomfilter = $2;
 4500:             } else {
 4501:                 $ownerunamefilter = $ownerfilter;
 4502:                 $ownerdomfilter = '';
 4503:             }
 4504:         }
 4505:     } else {
 4506:         $ownerfilter='.';
 4507:     }
 4508: 
 4509:     if (defined($coursefilter)) {
 4510:         $coursefilter=&unescape($coursefilter);
 4511:     } else {
 4512:         $coursefilter='.';
 4513:     }
 4514:     if (defined($typefilter)) {
 4515:         $typefilter=&unescape($typefilter);
 4516:     } else {
 4517:         $typefilter='.';
 4518:     }
 4519:     if (defined($regexp_ok)) {
 4520:         $regexp_ok=&unescape($regexp_ok);
 4521:     }
 4522:     if (defined($catfilter)) {
 4523:         $catfilter=&unescape($catfilter);
 4524:     }
 4525:     if (defined($cloner)) {
 4526:         $cloner = &unescape($cloner);
 4527:         ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/); 
 4528:     }
 4529:     if (defined($cc_clone_list)) {
 4530:         $cc_clone_list = &unescape($cc_clone_list);
 4531:         my @cc_cloners = split('&',$cc_clone_list);
 4532:         foreach my $cid (@cc_cloners) {
 4533:             my ($clonedom,$clonenum) = split(':',$cid);
 4534:             next if ($clonedom ne $udom); 
 4535:             $cc_clone{$clonedom.'_'.$clonenum} = 1;
 4536:         } 
 4537:     }
 4538:     if ($createdbefore ne '') {
 4539:         $createdbefore = &unescape($createdbefore);
 4540:     } else {
 4541:        $createdbefore = 0;
 4542:     }
 4543:     if ($createdafter ne '') {
 4544:         $createdafter = &unescape($createdafter);
 4545:     } else {
 4546:         $createdafter = 0;
 4547:     }
 4548:     if ($creationcontext ne '') {
 4549:         $creationcontext = &unescape($creationcontext);
 4550:     } else {
 4551:         $creationcontext = '.';
 4552:     }
 4553:     unless ($hasuniquecode) {
 4554:         $hasuniquecode = '.';
 4555:     }
 4556:     my $unpack = 1;
 4557:     if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' && 
 4558:         $typefilter eq '.') {
 4559:         $unpack = 0;
 4560:     }
 4561:     if (!defined($since)) { $since=0; }
 4562:     my $qresult='';
 4563:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 4564:     if ($hashref) {
 4565: 	while (my ($key,$value) = each(%$hashref)) {
 4566:             my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
 4567:                 %unesc_val,$selfenroll_end,$selfenroll_types,$created,
 4568:                 $context);
 4569:             $unesc_key = &unescape($key);
 4570:             if ($unesc_key =~ /^lasttime:/) {
 4571:                 next;
 4572:             } else {
 4573:                 $lasttime_key = &escape('lasttime:'.$unesc_key);
 4574:             }
 4575:             if ($hashref->{$lasttime_key} ne '') {
 4576:                 $lasttime = $hashref->{$lasttime_key};
 4577:                 next if ($lasttime<$since);
 4578:             }
 4579:             my ($canclone,$valchange);
 4580:             my $items = &Apache::lonnet::thaw_unescape($value);
 4581:             if (ref($items) eq 'HASH') {
 4582:                 if ($hashref->{$lasttime_key} eq '') {
 4583:                     next if ($since > 1);
 4584:                 }
 4585:                 $is_hash =  1;
 4586:                 if ($domcloner) {
 4587:                     $canclone = 1;
 4588:                 } elsif (defined($clonerudom)) {
 4589:                     if ($items->{'cloners'}) {
 4590:                         my @cloneable = split(',',$items->{'cloners'});
 4591:                         if (@cloneable) {
 4592:                             if (grep(/^\*$/,@cloneable))  {
 4593:                                 $canclone = 1;
 4594:                             } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
 4595:                                 $canclone = 1;
 4596:                             } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
 4597:                                 $canclone = 1;
 4598:                             }
 4599:                         }
 4600:                         unless ($canclone) {
 4601:                             if ($cloneruname ne '' && $clonerudom ne '') {
 4602:                                 if ($cc_clone{$unesc_key}) {
 4603:                                     $canclone = 1;
 4604:                                     $items->{'cloners'} .= ','.$cloneruname.':'.
 4605:                                                            $clonerudom;
 4606:                                     $valchange = 1;
 4607:                                 }
 4608:                             }
 4609:                         }
 4610:                     } elsif (defined($cloneruname)) {
 4611:                         if ($cc_clone{$unesc_key}) {
 4612:                             $canclone = 1;
 4613:                             $items->{'cloners'} = $cloneruname.':'.$clonerudom;
 4614:                             $valchange = 1;
 4615:                         }
 4616:                         unless ($canclone) {
 4617:                             if ($items->{'owner'} =~ /:/) {
 4618:                                 if ($items->{'owner'} eq $cloner) {
 4619:                                     $canclone = 1;
 4620:                                 }
 4621:                             } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
 4622:                                 $canclone = 1;
 4623:                             }
 4624:                             if ($canclone) {
 4625:                                 $items->{'cloners'} = $cloneruname.':'.$clonerudom;
 4626:                                 $valchange = 1;
 4627:                             }
 4628:                         }
 4629:                     }
 4630:                 }
 4631:                 if ($unpack || !$rtn_as_hash) {
 4632:                     $unesc_val{'descr'} = $items->{'description'};
 4633:                     $unesc_val{'inst_code'} = $items->{'inst_code'};
 4634:                     $unesc_val{'owner'} = $items->{'owner'};
 4635:                     $unesc_val{'type'} = $items->{'type'};
 4636:                     $unesc_val{'cloners'} = $items->{'cloners'};
 4637:                     $unesc_val{'created'} = $items->{'created'};
 4638:                     $unesc_val{'context'} = $items->{'context'};
 4639:                 }
 4640:                 $selfenroll_types = $items->{'selfenroll_types'};
 4641:                 $selfenroll_end = $items->{'selfenroll_end_date'};
 4642:                 $created = $items->{'created'};
 4643:                 $context = $items->{'context'};
 4644:                 if ($hasuniquecode ne '.') {
 4645:                     next unless ($items->{'uniquecode'});
 4646:                 }
 4647:                 if ($selfenrollonly) {
 4648:                     next if (!$selfenroll_types);
 4649:                     if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
 4650:                         next;
 4651:                     }
 4652:                 }
 4653:                 if ($creationcontext ne '.') {
 4654:                     next if (($context ne '') && ($context ne $creationcontext));  
 4655:                 }
 4656:                 if ($createdbefore > 0) {
 4657:                     next if (($created eq '') || ($created > $createdbefore));   
 4658:                 }
 4659:                 if ($createdafter > 0) {
 4660:                     next if (($created eq '') || ($created <= $createdafter)); 
 4661:                 }
 4662:                 if ($catfilter ne '') {
 4663:                     next if ($items->{'categories'} eq '');
 4664:                     my @categories = split('&',$items->{'categories'}); 
 4665:                     next if (@categories == 0);
 4666:                     my @subcats = split('&',$catfilter);
 4667:                     my $matchcat = 0;
 4668:                     foreach my $cat (@categories) {
 4669:                         if (grep(/^\Q$cat\E$/,@subcats)) {
 4670:                             $matchcat = 1;
 4671:                             last;
 4672:                         }
 4673:                     }
 4674:                     next if (!$matchcat);
 4675:                 }
 4676:                 if ($caller eq 'coursecatalog') {
 4677:                     if ($items->{'hidefromcat'} eq 'yes') {
 4678:                         next if !$showhidden;
 4679:                     }
 4680:                 }
 4681:             } else {
 4682:                 next if ($catfilter ne '');
 4683:                 next if ($selfenrollonly);
 4684:                 next if ($createdbefore || $createdafter);
 4685:                 next if ($creationcontext ne '.');
 4686:                 if ((defined($clonerudom)) && (defined($cloneruname)))  {
 4687:                     if ($cc_clone{$unesc_key}) {
 4688:                         $canclone = 1;
 4689:                         $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
 4690:                     }
 4691:                 }
 4692:                 $is_hash =  0;
 4693:                 my @courseitems = split(/:/,$value);
 4694:                 $lasttime = pop(@courseitems);
 4695:                 if ($hashref->{$lasttime_key} eq '') {
 4696:                     next if ($lasttime<$since);
 4697:                 }
 4698: 	        ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
 4699:             }
 4700:             if ($cloneonly) {
 4701:                next unless ($canclone);
 4702:             }
 4703:             my $match = 1;
 4704: 	    if ($description ne '.') {
 4705:                 if (!$is_hash) {
 4706:                     $unesc_val{'descr'} = &unescape($val{'descr'});
 4707:                 }
 4708:                 if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
 4709:                     $match = 0;
 4710:                 }
 4711:             }
 4712:             if ($instcodefilter ne '.') {
 4713:                 if (!$is_hash) {
 4714:                     $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
 4715:                 }
 4716:                 if ($regexp_ok == 1) {
 4717:                     if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
 4718:                         $match = 0;
 4719:                     }
 4720:                 } elsif ($regexp_ok == -1) {
 4721:                     if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
 4722:                         $match = 0;
 4723:                     }
 4724:                 } else {
 4725:                     if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
 4726:                         $match = 0;
 4727:                     }
 4728:                 }
 4729: 	    }
 4730:             if ($ownerfilter ne '.') {
 4731:                 if (!$is_hash) {
 4732:                     $unesc_val{'owner'} = &unescape($val{'owner'});
 4733:                 }
 4734:                 if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
 4735:                     if ($unesc_val{'owner'} =~ /:/) {
 4736:                         if (eval{$unesc_val{'owner'} !~ 
 4737:                              /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
 4738:                             $match = 0;
 4739:                         } 
 4740:                     } else {
 4741:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
 4742:                             $match = 0;
 4743:                         }
 4744:                     }
 4745:                 } elsif ($ownerunamefilter ne '') {
 4746:                     if ($unesc_val{'owner'} =~ /:/) {
 4747:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
 4748:                              $match = 0;
 4749:                         }
 4750:                     } else {
 4751:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
 4752:                             $match = 0;
 4753:                         }
 4754:                     }
 4755:                 } elsif ($ownerdomfilter ne '') {
 4756:                     if ($unesc_val{'owner'} =~ /:/) {
 4757:                         if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
 4758:                              $match = 0;
 4759:                         }
 4760:                     } else {
 4761:                         if ($ownerdomfilter ne $udom) {
 4762:                             $match = 0;
 4763:                         }
 4764:                     }
 4765:                 }
 4766:             }
 4767:             if ($coursefilter ne '.') {
 4768:                 if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
 4769:                     $match = 0;
 4770:                 }
 4771:             }
 4772:             if ($typefilter ne '.') {
 4773:                 if (!$is_hash) {
 4774:                     $unesc_val{'type'} = &unescape($val{'type'});
 4775:                 }
 4776:                 if ($unesc_val{'type'} eq '') {
 4777:                     if ($typefilter ne 'Course') {
 4778:                         $match = 0;
 4779:                     }
 4780:                 } else {
 4781:                     if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
 4782:                         $match = 0;
 4783:                     }
 4784:                 }
 4785:             }
 4786:             if ($match == 1) {
 4787:                 if ($rtn_as_hash) {
 4788:                     if ($is_hash) {
 4789:                         if ($valchange) {
 4790:                             my $newvalue = &Apache::lonnet::freeze_escape($items);
 4791:                             $qresult.=$key.'='.$newvalue.'&';
 4792:                         } else {
 4793:                             $qresult.=$key.'='.$value.'&';
 4794:                         }
 4795:                     } else {
 4796:                         my %rtnhash = ( 'description' => &unescape($val{'descr'}),
 4797:                                         'inst_code' => &unescape($val{'inst_code'}),
 4798:                                         'owner'     => &unescape($val{'owner'}),
 4799:                                         'type'      => &unescape($val{'type'}),
 4800:                                         'cloners'   => &unescape($val{'cloners'}),
 4801:                                       );
 4802:                         my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
 4803:                         $qresult.=$key.'='.$items.'&';
 4804:                     }
 4805:                 } else {
 4806:                     if ($is_hash) {
 4807:                         $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
 4808:                                     &escape($unesc_val{'inst_code'}).':'.
 4809:                                     &escape($unesc_val{'owner'}).'&';
 4810:                     } else {
 4811:                         $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
 4812:                                     ':'.$val{'owner'}.'&';
 4813:                     }
 4814:                 }
 4815:             }
 4816: 	}
 4817: 	if (&untie_domain_hash($hashref)) {
 4818: 	    chop($qresult);
 4819: 	    &Reply($client, \$qresult, $userinput);
 4820: 	} else {
 4821: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4822: 		    "while attempting courseiddump\n", $userinput);
 4823: 	}
 4824:     } else {
 4825: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 4826: 		"while attempting courseiddump\n", $userinput);
 4827:     }
 4828:     return 1;
 4829: }
 4830: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
 4831: 
 4832: sub course_lastaccess_handler {
 4833:     my ($cmd, $tail, $client) = @_;
 4834:     my $userinput = "$cmd:$tail";
 4835:     my ($cdom,$cnum) = split(':',$tail); 
 4836:     my (%lastaccess,$qresult);
 4837:     my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
 4838:     if ($hashref) {
 4839:         while (my ($key,$value) = each(%$hashref)) {
 4840:             my ($unesc_key,$lasttime);
 4841:             $unesc_key = &unescape($key);
 4842:             if ($cnum) {
 4843:                 next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
 4844:             }
 4845:             if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
 4846:                 $lastaccess{$1} = $value;
 4847:             } else {
 4848:                 my $items = &Apache::lonnet::thaw_unescape($value);
 4849:                 if (ref($items) eq 'HASH') {
 4850:                     unless ($lastaccess{$unesc_key}) {
 4851:                         $lastaccess{$unesc_key} = '';
 4852:                     }
 4853:                 } else {
 4854:                     my @courseitems = split(':',$value);
 4855:                     $lastaccess{$unesc_key} = pop(@courseitems);
 4856:                 }
 4857:             }
 4858:         }
 4859:         foreach my $cid (sort(keys(%lastaccess))) {
 4860:             $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&'; 
 4861:         }
 4862:         if (&untie_domain_hash($hashref)) {
 4863:             if ($qresult) {
 4864:                 chop($qresult);
 4865:             }
 4866:             &Reply($client, \$qresult, $userinput);
 4867:         } else {
 4868:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4869:                     "while attempting lastacourseaccess\n", $userinput);
 4870:         }
 4871:     } else {
 4872:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 4873:                 "while attempting lastcourseaccess\n", $userinput);
 4874:     }
 4875:     return 1;
 4876: }
 4877: &register_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
 4878: 
 4879: sub course_sessions_handler {
 4880:     my ($cmd, $tail, $client) = @_;
 4881:     my $userinput = "$cmd:$tail";
 4882:     my ($cdom,$cnum,$lastactivity) = split(':',$tail);
 4883:     my $dbsuffix = '_'.$cdom.'_'.$cnum.'.db';
 4884:     my (%sessions,$qresult);
 4885:     my $now=time;
 4886:     if (opendir(DIR,$perlvar{'lonIDsDir'})) {
 4887:         my $filename;
 4888:         while ($filename=readdir(DIR)) {
 4889:             next if ($filename=~/^\./);
 4890:             next if ($filename=~/^publicuser_/);
 4891:             next if ($filename=~/^[a-f0-9]+_(linked|lti_\d+)\.id$/);
 4892:             if ($filename =~ /^($LONCAPA::match_username)_\d+_($LONCAPA::match_domain)_/) {
 4893:                 my ($uname,$udom) = ($1,$2);
 4894:                 next unless (-e "$perlvar{'lonDaemons'}/tmp/$uname$dbsuffix");
 4895:                 my $mtime = (stat("$perlvar{'lonIDsDir'}/$filename"))[9];
 4896:                 if ($lastactivity < 0) {
 4897:                     next if ($mtime-$now > $lastactivity);
 4898:                 } else {
 4899:                     next if ($now-$mtime > $lastactivity);
 4900:                 }
 4901:                 $sessions{$uname.':'.$udom} = $mtime;
 4902:             }
 4903:         }
 4904:         closedir(DIR); 
 4905:     }
 4906:     foreach my $user (keys(%sessions)) {
 4907:         $qresult.=&escape($user).'='.$sessions{$user}.'&';
 4908:     }
 4909:     if ($qresult) {
 4910:         chop($qresult);
 4911:     }
 4912:     &Reply($client, \$qresult, $userinput);
 4913:     return 1;
 4914: }
 4915: &register_handler("coursesessions",\&course_sessions_handler, 0, 1, 0);
 4916: 
 4917: #
 4918: # Puts an unencrypted entry in a namespace db file at the domain level 
 4919: #
 4920: # Parameters:
 4921: #    $cmd      - The command that got us here.
 4922: #    $tail     - Tail of the command (remaining parameters).
 4923: #    $client   - File descriptor connected to client.
 4924: # Returns
 4925: #     0        - Requested to exit, caller should shut down.
 4926: #     1        - Continue processing.
 4927: #  Side effects:
 4928: #     reply is written to $client.
 4929: #
 4930: sub put_domain_handler {
 4931:     my ($cmd,$tail,$client) = @_;
 4932: 
 4933:     my $userinput = "$cmd:$tail";
 4934: 
 4935:     my ($udom,$namespace,$what) =split(/:/,$tail,3);
 4936:     chomp($what);
 4937:     my @pairs=split(/\&/,$what);
 4938:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
 4939:                                    "P", $what);
 4940:     if ($hashref) {
 4941:         foreach my $pair (@pairs) {
 4942:             my ($key,$value)=split(/=/,$pair);
 4943:             $hashref->{$key}=$value;
 4944:         }
 4945:         if (&untie_domain_hash($hashref)) {
 4946:             &Reply($client, "ok\n", $userinput);
 4947:         } else {
 4948:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4949:                      "while attempting putdom\n", $userinput);
 4950:         }
 4951:     } else {
 4952:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 4953:                   "while attempting putdom\n", $userinput);
 4954:     }
 4955: 
 4956:     return 1;
 4957: }
 4958: &register_handler("putdom", \&put_domain_handler, 0, 1, 0);
 4959: 
 4960: # Updates one or more entries in clickers.db file at the domain level
 4961: #
 4962: # Parameters:
 4963: #    $cmd      - The command that got us here.
 4964: #    $tail     - Tail of the command (remaining parameters).
 4965: #                In this case a colon separated list containing:
 4966: #                (a) the domain for which we are updating the entries,
 4967: #                (b) the action required -- add or del -- and
 4968: #                (c) a &-separated list of entries to add or delete.
 4969: #    $client   - File descriptor connected to client.
 4970: # Returns
 4971: #     1        - Continue processing.
 4972: #     0        - Requested to exit, caller should shut down.
 4973: #  Side effects:
 4974: #     reply is written to $client.
 4975: #
 4976: 
 4977: 
 4978: sub update_clickers {
 4979:     my ($cmd, $tail, $client)  = @_;
 4980: 
 4981:     my $userinput = "$cmd:$tail";
 4982:     my ($udom,$action,$what) =split(/:/,$tail,3);
 4983:     chomp($what);
 4984: 
 4985:     my $hashref = &tie_domain_hash($udom, "clickers", &GDBM_WRCREAT(),
 4986:                                  "U","$action:$what");
 4987: 
 4988:     if (!$hashref) {
 4989:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 4990:                   "while attempting updateclickers\n", $userinput);
 4991:         return 1;
 4992:     }
 4993: 
 4994:     my @pairs=split(/\&/,$what);
 4995:     foreach my $pair (@pairs) {
 4996:         my ($key,$value)=split(/=/,$pair);
 4997:         if ($action eq 'add') {
 4998:             if (exists($hashref->{$key})) {
 4999:                 my @newvals = split(/,/,&unescape($value));
 5000:                 my @currvals = split(/,/,&unescape($hashref->{$key}));
 5001:                 my @merged = sort(keys(%{{map { $_ => 1 } (@newvals,@currvals)}}));
 5002:                 $hashref->{$key}=&escape(join(',',@merged));
 5003:             } else {
 5004:                 $hashref->{$key}=$value;
 5005:             }
 5006:         } elsif ($action eq 'del') {
 5007:             if (exists($hashref->{$key})) {
 5008:                 my %current;
 5009:                 map { $current{$_} = 1; } split(/,/,&unescape($hashref->{$key}));
 5010:                 map { delete($current{$_}); } split(/,/,&unescape($value));
 5011:                 if (keys(%current)) {
 5012:                     $hashref->{$key}=&escape(join(',',sort(keys(%current))));
 5013:                 } else {
 5014:                     delete($hashref->{$key});
 5015:                 }
 5016:             }
 5017:         }
 5018:     }
 5019:     if (&untie_user_hash($hashref)) {
 5020:         &Reply( $client, "ok\n", $userinput);
 5021:     } else {
 5022:         &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 5023:                  "while attempting put\n",
 5024:                  $userinput);
 5025:     }
 5026:     return 1;
 5027: }
 5028: &register_handler("updateclickers", \&update_clickers, 0, 1, 0);
 5029: 
 5030: 
 5031: # Deletes one or more entries in a namespace db file at the domain level
 5032: #
 5033: # Parameters:
 5034: #    $cmd      - The command that got us here.
 5035: #    $tail     - Tail of the command (remaining parameters).
 5036: #                In this case a colon separated list containing:
 5037: #                (a) the domain for which we are deleting the entries,
 5038: #                (b) &-separated list of keys to delete.  
 5039: #    $client   - File descriptor connected to client.
 5040: # Returns
 5041: #     1        - Continue processing.
 5042: #     0        - Requested to exit, caller should shut down.
 5043: #  Side effects:
 5044: #     reply is written to $client.
 5045: #
 5046: 
 5047: sub del_domain_handler {
 5048:     my ($cmd,$tail,$client) = @_;
 5049: 
 5050:     my $userinput = "$cmd:$tail";
 5051: 
 5052:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
 5053:     chomp($what);
 5054:     my $hashref = &tie_domain_hash($udom,$namespace,&GDBM_WRCREAT(),
 5055:                                    "D", $what);
 5056:     if ($hashref) {
 5057:         my @keys=split(/\&/,$what);
 5058:         foreach my $key (@keys) {
 5059:             delete($hashref->{$key});
 5060:         }
 5061:         if (&untie_user_hash($hashref)) {
 5062:             &Reply($client, "ok\n", $userinput);
 5063:         } else {
 5064:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5065:                     "while attempting deldom\n", $userinput);
 5066:         }
 5067:     } else {
 5068:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 5069:                  "while attempting deldom\n", $userinput);
 5070:     }
 5071:     return 1;
 5072: }
 5073: &register_handler("deldom", \&del_domain_handler, 0, 1, 0);
 5074: 
 5075: 
 5076: # Unencrypted get from the namespace database file at the domain level.
 5077: # This function retrieves a keyed item from a specific named database in the
 5078: # domain directory.
 5079: #
 5080: # Parameters:
 5081: #   $cmd             - Command request keyword (getdom).
 5082: #   $tail            - Tail of the command.  This is a colon separated list
 5083: #                      consisting of the domain and the 'namespace' 
 5084: #                      which selects the gdbm file to do the lookup in,
 5085: #                      & separated list of keys to lookup.  Note that
 5086: #                      the values are returned as an & separated list too.
 5087: #   $client          - File descriptor open on the client.
 5088: # Returns:
 5089: #   1       - Continue processing.
 5090: #   0       - Exit.
 5091: #  Side effects:
 5092: #     reply is written to $client.
 5093: #
 5094: 
 5095: sub get_domain_handler {
 5096:     my ($cmd, $tail, $client) = @_;
 5097: 
 5098:     my $userinput = "$cmd:$tail";
 5099: 
 5100:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
 5101:     if ($namespace =~ /^enc/) {
 5102:         &Failure( $client, "refused\n", $userinput);
 5103:     } else {
 5104:         my $res = LONCAPA::Lond::get_dom($userinput);
 5105:         if ($res =~ /^error:/) {
 5106:             &Failure($client, \$res, $userinput);
 5107:         } else {
 5108:             &Reply($client, \$res, $userinput);
 5109:         }
 5110:     }
 5111: 
 5112:     return 1;
 5113: }
 5114: &register_handler("getdom", \&get_domain_handler, 0, 1, 0);
 5115: 
 5116: sub encrypted_get_domain_handler {
 5117:     my ($cmd, $tail, $client) = @_;
 5118: 
 5119:     my $userinput = "$cmd:$tail";
 5120: 
 5121:     my $res = LONCAPA::Lond::get_dom($userinput);
 5122:     if ($res =~ /^error:/) {
 5123:         &Failure($client, \$res, $userinput);
 5124:     } else {
 5125:         if ($cipher) {
 5126:             my $cmdlength=length($res);
 5127:             $res.="         ";
 5128:             my $encres='';
 5129:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 5130:                 $encres.= unpack("H16",
 5131:                                  $cipher->encrypt(substr($res,
 5132:                                                          $encidx,
 5133:                                                          8)));
 5134:             }
 5135:             &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
 5136:         } else {
 5137:             &Failure( $client, "error:no_key\n",$userinput);
 5138:         }
 5139:     }
 5140:     return 1;
 5141: }
 5142: &register_handler("egetdom", \&encrypted_get_domain_handler, 1, 1, 0);
 5143: 
 5144: #
 5145: #  Puts an id to a domains id database. 
 5146: #
 5147: #  Parameters:
 5148: #   $cmd     - The command that triggered us.
 5149: #   $tail    - Remainder of the request other than the command. This is a 
 5150: #              colon separated list containing:
 5151: #              $domain  - The domain for which we are writing the id.
 5152: #              $pairs  - The id info to write... this is and & separated list
 5153: #                        of keyword=value.
 5154: #   $client  - Socket open on the client.
 5155: #  Returns:
 5156: #    1   - Continue processing.
 5157: #  Side effects:
 5158: #     reply is written to $client.
 5159: #
 5160: sub put_id_handler {
 5161:     my ($cmd,$tail,$client) = @_;
 5162: 
 5163: 
 5164:     my $userinput = "$cmd:$tail";
 5165: 
 5166:     my ($udom,$what)=split(/:/,$tail);
 5167:     chomp($what);
 5168:     my @pairs=split(/\&/,$what);
 5169:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
 5170: 				   "P", $what);
 5171:     if ($hashref) {
 5172: 	foreach my $pair (@pairs) {
 5173: 	    my ($key,$value)=split(/=/,$pair);
 5174: 	    $hashref->{$key}=$value;
 5175: 	}
 5176: 	if (&untie_domain_hash($hashref)) {
 5177: 	    &Reply($client, "ok\n", $userinput);
 5178: 	} else {
 5179: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5180: 		     "while attempting idput\n", $userinput);
 5181: 	}
 5182:     } else {
 5183: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 5184: 		  "while attempting idput\n", $userinput);
 5185:     }
 5186: 
 5187:     return 1;
 5188: }
 5189: &register_handler("idput", \&put_id_handler, 0, 1, 0);
 5190: 
 5191: #
 5192: #  Retrieves a set of id values from the id database.
 5193: #  Returns an & separated list of results, one for each requested id to the
 5194: #  client.
 5195: #
 5196: # Parameters:
 5197: #   $cmd       - Command keyword that caused us to be dispatched.
 5198: #   $tail      - Tail of the command.  Consists of a colon separated:
 5199: #               domain - the domain whose id table we dump
 5200: #               ids      Consists of an & separated list of
 5201: #                        id keywords whose values will be fetched.
 5202: #                        nonexisting keywords will have an empty value.
 5203: #   $client    - Socket open on the client.
 5204: #
 5205: # Returns:
 5206: #    1 - indicating processing should continue.
 5207: # Side effects:
 5208: #   An & separated list of results is written to $client.
 5209: #
 5210: sub get_id_handler {
 5211:     my ($cmd, $tail, $client) = @_;
 5212: 
 5213:     
 5214:     my $userinput = "$client:$tail";
 5215:     
 5216:     my ($udom,$what)=split(/:/,$tail);
 5217:     chomp($what);
 5218:     my @queries=split(/\&/,$what);
 5219:     my $qresult='';
 5220:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
 5221:     if ($hashref) {
 5222: 	for (my $i=0;$i<=$#queries;$i++) {
 5223: 	    $qresult.="$hashref->{$queries[$i]}&";
 5224: 	}
 5225: 	if (&untie_domain_hash($hashref)) {
 5226: 	    $qresult=~s/\&$//;
 5227: 	    &Reply($client, \$qresult, $userinput);
 5228: 	} else {
 5229: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 5230: 		      "while attempting idget\n",$userinput);
 5231: 	}
 5232:     } else {
 5233: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 5234: 		 "while attempting idget\n",$userinput);
 5235:     }
 5236:     
 5237:     return 1;
 5238: }
 5239: &register_handler("idget", \&get_id_handler, 0, 1, 0);
 5240: 
 5241: #   Deletes one or more ids in a domain's id database.
 5242: #
 5243: #   Parameters:
 5244: #       $cmd                  - Command keyword (iddel).
 5245: #       $tail                 - Command tail.  In this case a colon
 5246: #                               separated list containing:
 5247: #                               The domain for which we are deleting the id(s).
 5248: #                               &-separated list of id(s) to delete.
 5249: #       $client               - File open on client socket.
 5250: # Returns:
 5251: #     1   - Continue processing
 5252: #     0   - Exit server.
 5253: #     
 5254: #
 5255: 
 5256: sub del_id_handler {
 5257:     my ($cmd,$tail,$client) = @_;
 5258: 
 5259:     my $userinput = "$cmd:$tail";
 5260: 
 5261:     my ($udom,$what)=split(/:/,$tail);
 5262:     chomp($what);
 5263:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
 5264:                                    "D", $what);
 5265:     if ($hashref) {
 5266:         my @keys=split(/\&/,$what);
 5267:         foreach my $key (@keys) {
 5268:             delete($hashref->{$key});
 5269:         }
 5270:         if (&untie_user_hash($hashref)) {
 5271:             &Reply($client, "ok\n", $userinput);
 5272:         } else {
 5273:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5274:                     "while attempting iddel\n", $userinput);
 5275:         }
 5276:     } else {
 5277:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 5278:                  "while attempting iddel\n", $userinput);
 5279:     }
 5280:     return 1;
 5281: }
 5282: &register_handler("iddel", \&del_id_handler, 0, 1, 0);
 5283: 
 5284: #
 5285: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
 5286: #
 5287: # Parameters
 5288: #   $cmd       - Command keyword that caused us to be dispatched.
 5289: #   $tail      - Tail of the command.  Consists of a colon separated:
 5290: #               domain - the domain whose dcmail we are recording
 5291: #               email    Consists of key=value pair 
 5292: #                        where key is unique msgid
 5293: #                        and value is message (in XML)
 5294: #   $client    - Socket open on the client.
 5295: #
 5296: # Returns:
 5297: #    1 - indicating processing should continue.
 5298: # Side effects
 5299: #     reply is written to $client.
 5300: #
 5301: sub put_dcmail_handler {
 5302:     my ($cmd,$tail,$client) = @_;
 5303:     my $userinput = "$cmd:$tail";
 5304: 
 5305: 
 5306:     my ($udom,$what)=split(/:/,$tail);
 5307:     chomp($what);
 5308:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
 5309:     if ($hashref) {
 5310:         my ($key,$value)=split(/=/,$what);
 5311:         $hashref->{$key}=$value;
 5312:     }
 5313:     if (&untie_domain_hash($hashref)) {
 5314:         &Reply($client, "ok\n", $userinput);
 5315:     } else {
 5316:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5317:                  "while attempting dcmailput\n", $userinput);
 5318:     }
 5319:     return 1;
 5320: }
 5321: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
 5322: 
 5323: #
 5324: # Retrieves broadcast e-mail from nohist_dcmail database
 5325: # Returns to client an & separated list of key=value pairs,
 5326: # where key is msgid and value is message information.
 5327: #
 5328: # Parameters
 5329: #   $cmd       - Command keyword that caused us to be dispatched.
 5330: #   $tail      - Tail of the command.  Consists of a colon separated:
 5331: #               domain - the domain whose dcmail table we dump
 5332: #               startfilter - beginning of time window 
 5333: #               endfilter - end of time window
 5334: #               sendersfilter - & separated list of username:domain 
 5335: #                 for senders to search for.
 5336: #   $client    - Socket open on the client.
 5337: #
 5338: # Returns:
 5339: #    1 - indicating processing should continue.
 5340: # Side effects
 5341: #     reply (& separated list of msgid=messageinfo pairs) is 
 5342: #     written to $client.
 5343: #
 5344: sub dump_dcmail_handler {
 5345:     my ($cmd, $tail, $client) = @_;
 5346:                                                                                 
 5347:     my $userinput = "$cmd:$tail";
 5348:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
 5349:     chomp($sendersfilter);
 5350:     my @senders = ();
 5351:     if (defined($startfilter)) {
 5352:         $startfilter=&unescape($startfilter);
 5353:     } else {
 5354:         $startfilter='.';
 5355:     }
 5356:     if (defined($endfilter)) {
 5357:         $endfilter=&unescape($endfilter);
 5358:     } else {
 5359:         $endfilter='.';
 5360:     }
 5361:     if (defined($sendersfilter)) {
 5362:         $sendersfilter=&unescape($sendersfilter);
 5363: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
 5364:     }
 5365: 
 5366:     my $qresult='';
 5367:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
 5368:     if ($hashref) {
 5369:         while (my ($key,$value) = each(%$hashref)) {
 5370:             my $match = 1;
 5371:             my ($timestamp,$subj,$uname,$udom) = 
 5372: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
 5373:             $subj = &unescape($subj);
 5374:             unless ($startfilter eq '.' || !defined($startfilter)) {
 5375:                 if ($timestamp < $startfilter) {
 5376:                     $match = 0;
 5377:                 }
 5378:             }
 5379:             unless ($endfilter eq '.' || !defined($endfilter)) {
 5380:                 if ($timestamp > $endfilter) {
 5381:                     $match = 0;
 5382:                 }
 5383:             }
 5384:             unless (@senders < 1) {
 5385:                 unless (grep/^$uname:$udom$/,@senders) {
 5386:                     $match = 0;
 5387:                 }
 5388:             }
 5389:             if ($match == 1) {
 5390:                 $qresult.=$key.'='.$value.'&';
 5391:             }
 5392:         }
 5393:         if (&untie_domain_hash($hashref)) {
 5394:             chop($qresult);
 5395:             &Reply($client, \$qresult, $userinput);
 5396:         } else {
 5397:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5398:                     "while attempting dcmaildump\n", $userinput);
 5399:         }
 5400:     } else {
 5401:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 5402:                 "while attempting dcmaildump\n", $userinput);
 5403:     }
 5404:     return 1;
 5405: }
 5406: 
 5407: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
 5408: 
 5409: #
 5410: # Puts domain roles in nohist_domainroles database
 5411: #
 5412: # Parameters
 5413: #   $cmd       - Command keyword that caused us to be dispatched.
 5414: #   $tail      - Tail of the command.  Consists of a colon separated:
 5415: #               domain - the domain whose roles we are recording  
 5416: #               role -   Consists of key=value pair
 5417: #                        where key is unique role
 5418: #                        and value is start/end date information
 5419: #   $client    - Socket open on the client.
 5420: #
 5421: # Returns:
 5422: #    1 - indicating processing should continue.
 5423: # Side effects
 5424: #     reply is written to $client.
 5425: #
 5426: 
 5427: sub put_domainroles_handler {
 5428:     my ($cmd,$tail,$client) = @_;
 5429: 
 5430:     my $userinput = "$cmd:$tail";
 5431:     my ($udom,$what)=split(/:/,$tail);
 5432:     chomp($what);
 5433:     my @pairs=split(/\&/,$what);
 5434:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
 5435:     if ($hashref) {
 5436:         foreach my $pair (@pairs) {
 5437:             my ($key,$value)=split(/=/,$pair);
 5438:             $hashref->{$key}=$value;
 5439:         }
 5440:         if (&untie_domain_hash($hashref)) {
 5441:             &Reply($client, "ok\n", $userinput);
 5442:         } else {
 5443:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5444:                      "while attempting domroleput\n", $userinput);
 5445:         }
 5446:     } else {
 5447:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 5448:                   "while attempting domroleput\n", $userinput);
 5449:     }
 5450:                                                                                   
 5451:     return 1;
 5452: }
 5453: 
 5454: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
 5455: 
 5456: #
 5457: # Retrieves domain roles from nohist_domainroles database
 5458: # Returns to client an & separated list of key=value pairs,
 5459: # where key is role and value is start and end date information.
 5460: #
 5461: # Parameters
 5462: #   $cmd       - Command keyword that caused us to be dispatched.
 5463: #   $tail      - Tail of the command.  Consists of a colon separated:
 5464: #               domain - the domain whose domain roles table we dump
 5465: #   $client    - Socket open on the client.
 5466: #
 5467: # Returns:
 5468: #    1 - indicating processing should continue.
 5469: # Side effects
 5470: #     reply (& separated list of role=start/end info pairs) is
 5471: #     written to $client.
 5472: #
 5473: sub dump_domainroles_handler {
 5474:     my ($cmd, $tail, $client) = @_;
 5475:                                                                                            
 5476:     my $userinput = "$cmd:$tail";
 5477:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
 5478:     chomp($rolesfilter);
 5479:     my @roles = ();
 5480:     if (defined($startfilter)) {
 5481:         $startfilter=&unescape($startfilter);
 5482:     } else {
 5483:         $startfilter='.';
 5484:     }
 5485:     if (defined($endfilter)) {
 5486:         $endfilter=&unescape($endfilter);
 5487:     } else {
 5488:         $endfilter='.';
 5489:     }
 5490:     if (defined($rolesfilter)) {
 5491:         $rolesfilter=&unescape($rolesfilter);
 5492: 	@roles = split(/\&/,$rolesfilter);
 5493:     }
 5494: 
 5495:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
 5496:     if ($hashref) {
 5497:         my $qresult = '';
 5498:         while (my ($key,$value) = each(%$hashref)) {
 5499:             my $match = 1;
 5500:             my ($end,$start) = split(/:/,&unescape($value));
 5501:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
 5502:             unless (@roles < 1) {
 5503:                 unless (grep/^\Q$trole\E$/,@roles) {
 5504:                     $match = 0;
 5505:                     next;
 5506:                 }
 5507:             }
 5508:             unless ($startfilter eq '.' || !defined($startfilter)) {
 5509:                 if ((defined($start)) && ($start >= $startfilter)) {
 5510:                     $match = 0;
 5511:                     next;
 5512:                 }
 5513:             }
 5514:             unless ($endfilter eq '.' || !defined($endfilter)) {
 5515:                 if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
 5516:                     $match = 0;
 5517:                     next;
 5518:                 }
 5519:             }
 5520:             if ($match == 1) {
 5521:                 $qresult.=$key.'='.$value.'&';
 5522:             }
 5523:         }
 5524:         if (&untie_domain_hash($hashref)) {
 5525:             chop($qresult);
 5526:             &Reply($client, \$qresult, $userinput);
 5527:         } else {
 5528:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5529:                     "while attempting domrolesdump\n", $userinput);
 5530:         }
 5531:     } else {
 5532:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 5533:                 "while attempting domrolesdump\n", $userinput);
 5534:     }
 5535:     return 1;
 5536: }
 5537: 
 5538: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
 5539: 
 5540: 
 5541: #  Process the tmpput command I'm not sure what this does.. Seems to
 5542: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
 5543: # where Id is the client's ip concatenated with a sequence number.
 5544: # The file will contain some value that is passed in.  Is this e.g.
 5545: # a login token?
 5546: #
 5547: # Parameters:
 5548: #    $cmd     - The command that got us dispatched.
 5549: #    $tail    - The remainder of the request following $cmd:
 5550: #               In this case this will be the contents of the file.
 5551: #    $client  - Socket connected to the client.
 5552: # Returns:
 5553: #    1 indicating processing can continue.
 5554: # Side effects:
 5555: #   A file is created in the local filesystem.
 5556: #   A reply is sent to the client.
 5557: sub tmp_put_handler {
 5558:     my ($cmd, $what, $client) = @_;
 5559: 
 5560:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
 5561: 
 5562:     my ($record,$context) = split(/:/,$what);
 5563:     if ($context ne '') {
 5564:         chomp($context);
 5565:         $context = &unescape($context);
 5566:     }
 5567:     my ($id,$store);
 5568:     $tmpsnum++;
 5569:     if (($context eq 'resetpw') || ($context eq 'createaccount')) {
 5570:         $id = &md5_hex(&md5_hex(time.{}.rand().$$));
 5571:     } else {
 5572:         $id = $$.'_'.$clientip.'_'.$tmpsnum;
 5573:     }
 5574:     $id=~s/\W/\_/g;
 5575:     $record=~s/\n//g;
 5576:     my $execdir=$perlvar{'lonDaemons'};
 5577:     if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
 5578: 	print $store $record;
 5579: 	close $store;
 5580: 	&Reply($client, \$id, $userinput);
 5581:     } else {
 5582: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
 5583: 		  "while attempting tmpput\n", $userinput);
 5584:     }
 5585:     return 1;
 5586:   
 5587: }
 5588: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
 5589: 
 5590: #   Processes the tmpget command.  This command returns the contents
 5591: #  of a temporary resource file(?) created via tmpput.
 5592: #
 5593: # Paramters:
 5594: #    $cmd      - Command that got us dispatched.
 5595: #    $id       - Tail of the command, contain the id of the resource
 5596: #                we want to fetch.
 5597: #    $client   - socket open on the client.
 5598: # Return:
 5599: #    1         - Inidcating processing can continue.
 5600: # Side effects:
 5601: #   A reply is sent to the client.
 5602: #
 5603: sub tmp_get_handler {
 5604:     my ($cmd, $id, $client) = @_;
 5605: 
 5606:     my $userinput = "$cmd:$id"; 
 5607:     
 5608: 
 5609:     $id=~s/\W/\_/g;
 5610:     my $store;
 5611:     my $execdir=$perlvar{'lonDaemons'};
 5612:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
 5613: 	my $reply=<$store>;
 5614: 	&Reply( $client, \$reply, $userinput);
 5615: 	close $store;
 5616:     } else {
 5617: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
 5618: 		  "while attempting tmpget\n", $userinput);
 5619:     }
 5620: 
 5621:     return 1;
 5622: }
 5623: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
 5624: 
 5625: #
 5626: #  Process the tmpdel command.  This command deletes a temp resource
 5627: #  created by the tmpput command.
 5628: #
 5629: # Parameters:
 5630: #   $cmd      - Command that got us here.
 5631: #   $id       - Id of the temporary resource created.
 5632: #   $client   - socket open on the client process.
 5633: #
 5634: # Returns:
 5635: #   1     - Indicating processing should continue.
 5636: # Side Effects:
 5637: #   A file is deleted
 5638: #   A reply is sent to the client.
 5639: sub tmp_del_handler {
 5640:     my ($cmd, $id, $client) = @_;
 5641:     
 5642:     my $userinput= "$cmd:$id";
 5643:     
 5644:     chomp($id);
 5645:     $id=~s/\W/\_/g;
 5646:     my $execdir=$perlvar{'lonDaemons'};
 5647:     if (unlink("$execdir/tmp/$id.tmp")) {
 5648: 	&Reply($client, "ok\n", $userinput);
 5649:     } else {
 5650: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
 5651: 		  "while attempting tmpdel\n", $userinput);
 5652:     }
 5653:     
 5654:     return 1;
 5655: 
 5656: }
 5657: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
 5658: 
 5659: #
 5660: #  Process the updatebalcookie command.  This command updates a
 5661: #  cookie in the lonBalancedir directory on a load balancer node.
 5662: #
 5663: # Parameters:
 5664: #   $cmd      - Command that got us here.
 5665: #   $tail     - Tail of the request (escaped cookie: escaped current entry)
 5666: #
 5667: #   $client   - socket open on the client process.
 5668: #
 5669: # Returns:
 5670: #   1     - Indicating processing should continue.
 5671: # Side Effects:
 5672: #   A cookie file is updated from the lonBalancedir directory
 5673: #   A reply is sent to the client.
 5674: #
 5675: sub update_balcookie_handler {
 5676:     my ($cmd, $tail, $client) = @_;
 5677: 
 5678:     my $userinput= "$cmd:$tail";
 5679:     chomp($tail);
 5680:     my ($cookie,$lastentry) = map { &unescape($_) } (split(/:/,$tail));
 5681: 
 5682:     my $updatedone;
 5683:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
 5684:         my $execdir=$perlvar{'lonBalanceDir'};
 5685:         if (-e "$execdir/$cookie.id") {
 5686:             my $doupdate;
 5687:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
 5688:                 while (my $line = <$fh>) {
 5689:                     chomp($line);
 5690:                     if ($line eq $lastentry) {
 5691:                         $doupdate = 1;
 5692:                         last;
 5693:                     }
 5694:                 }
 5695:                 close($fh);
 5696:             }
 5697:             if ($doupdate) {
 5698:                 if (open(my $fh,'>',"$execdir/$cookie.id")) {
 5699:                     print $fh $clientname;
 5700:                     close($fh);
 5701:                     $updatedone = 1;
 5702:                 }
 5703:             }
 5704:         }
 5705:     }
 5706:     if ($updatedone) {
 5707:         &Reply($client, "ok\n", $userinput);
 5708:     } else {
 5709:         &Failure( $client, "error: ".($!+0)."file update failed ".
 5710:                   "while attempting updatebalcookie\n", $userinput);
 5711:     }
 5712:     return 1;
 5713: }
 5714: &register_handler("updatebalcookie", \&update_balcookie_handler, 0, 1, 0);
 5715: 
 5716: #
 5717: #  Process the delbalcookie command. This command deletes a balancer
 5718: #  cookie in the lonBalancedir directory on a load balancer node.
 5719: #
 5720: # Parameters:
 5721: #   $cmd      - Command that got us here.
 5722: #   $cookie   - Cookie to be deleted.
 5723: #   $client   - socket open on the client process.
 5724: #
 5725: # Returns:
 5726: #   1     - Indicating processing should continue.
 5727: # Side Effects:
 5728: #   A cookie file is deleted from the lonBalancedir directory
 5729: #   A reply is sent to the client.
 5730: sub del_balcookie_handler {
 5731:     my ($cmd, $cookie, $client) = @_;
 5732: 
 5733:     my $userinput= "$cmd:$cookie";
 5734: 
 5735:     chomp($cookie);
 5736:     $cookie = &unescape($cookie);
 5737:     my $deleted = '';
 5738:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
 5739:         my $execdir=$perlvar{'lonBalanceDir'};
 5740:         if (-e "$execdir/$cookie.id") {
 5741:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
 5742:                 my $dodelete;
 5743:                 while (my $line = <$fh>) {
 5744:                     chomp($line);
 5745:                     if ($line eq $clientname) {
 5746:                         $dodelete = 1;
 5747:                         last;
 5748:                     }
 5749:                 }
 5750:                 close($fh);
 5751:                 if ($dodelete) {
 5752:                     if (unlink("$execdir/$cookie.id")) {
 5753:                         $deleted = 1;
 5754:                     }
 5755:                 }
 5756:             }
 5757:         }
 5758:     }
 5759:     if ($deleted) {
 5760:         &Reply($client, "ok\n", $userinput);
 5761:     } else {
 5762:         &Failure( $client, "error: ".($!+0)."Unlinking cookie file Failed ".
 5763:                   "while attempting delbalcookie\n", $userinput);
 5764:     }
 5765:     return 1;
 5766: }
 5767: &register_handler("delbalcookie", \&del_balcookie_handler, 0, 1, 0);
 5768: 
 5769: #
 5770: #   Processes the setannounce command.  This command
 5771: #   creates a file named announce.txt in the top directory of
 5772: #   the documentn root and sets its contents.  The announce.txt file is
 5773: #   printed in its entirety at the LonCAPA login page.  Note:
 5774: #   once the announcement.txt fileis created it cannot be deleted.
 5775: #   However, setting the contents of the file to empty removes the
 5776: #   announcement from the login page of loncapa so who cares.
 5777: #
 5778: # Parameters:
 5779: #    $cmd          - The command that got us dispatched.
 5780: #    $announcement - The text of the announcement.
 5781: #    $client       - Socket open on the client process.
 5782: # Retunrns:
 5783: #   1             - Indicating request processing should continue
 5784: # Side Effects:
 5785: #   The file {DocRoot}/announcement.txt is created.
 5786: #   A reply is sent to $client.
 5787: #
 5788: sub set_announce_handler {
 5789:     my ($cmd, $announcement, $client) = @_;
 5790:   
 5791:     my $userinput    = "$cmd:$announcement";
 5792: 
 5793:     chomp($announcement);
 5794:     $announcement=&unescape($announcement);
 5795:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
 5796: 				'/announcement.txt')) {
 5797: 	print $store $announcement;
 5798: 	close $store;
 5799: 	&Reply($client, "ok\n", $userinput);
 5800:     } else {
 5801: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
 5802:     }
 5803: 
 5804:     return 1;
 5805: }
 5806: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
 5807: 
 5808: #
 5809: #  Return the version of the daemon.  This can be used to determine
 5810: #  the compatibility of cross version installations or, alternatively to
 5811: #  simply know who's out of date and who isn't.  Note that the version
 5812: #  is returned concatenated with the tail.
 5813: # Parameters:
 5814: #   $cmd        - the request that dispatched to us.
 5815: #   $tail       - Tail of the request (client's version?).
 5816: #   $client     - Socket open on the client.
 5817: #Returns:
 5818: #   1 - continue processing requests.
 5819: # Side Effects:
 5820: #   Replies with version to $client.
 5821: sub get_version_handler {
 5822:     my ($cmd, $tail, $client) = @_;
 5823: 
 5824:     my $userinput  = $cmd.$tail;
 5825:     
 5826:     &Reply($client, &version($userinput)."\n", $userinput);
 5827: 
 5828: 
 5829:     return 1;
 5830: }
 5831: &register_handler("version", \&get_version_handler, 0, 1, 0);
 5832: 
 5833: #  Set the current host and domain.  This is used to support
 5834: #  multihomed systems.  Each IP of the system, or even separate daemons
 5835: #  on the same IP can be treated as handling a separate lonCAPA virtual
 5836: #  machine.  This command selects the virtual lonCAPA.  The client always
 5837: #  knows the right one since it is lonc and it is selecting the domain/system
 5838: #  from the hosts.tab file.
 5839: # Parameters:
 5840: #    $cmd      - Command that dispatched us.
 5841: #    $tail     - Tail of the command (domain/host requested).
 5842: #    $socket   - Socket open on the client.
 5843: #
 5844: # Returns:
 5845: #     1   - Indicates the program should continue to process requests.
 5846: # Side-effects:
 5847: #     The default domain/system context is modified for this daemon.
 5848: #     a reply is sent to the client.
 5849: #
 5850: sub set_virtual_host_handler {
 5851:     my ($cmd, $tail, $socket) = @_;
 5852:   
 5853:     my $userinput  ="$cmd:$tail";
 5854: 
 5855:     &Reply($client, &sethost($userinput)."\n", $userinput);
 5856: 
 5857: 
 5858:     return 1;
 5859: }
 5860: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
 5861: 
 5862: #  Process a request to exit:
 5863: #   - "bye" is sent to the client.
 5864: #   - The client socket is shutdown and closed.
 5865: #   - We indicate to the caller that we should exit.
 5866: # Formal Parameters:
 5867: #   $cmd                - The command that got us here.
 5868: #   $tail               - Tail of the command (empty).
 5869: #   $client             - Socket open on the tail.
 5870: # Returns:
 5871: #   0      - Indicating the program should exit!!
 5872: #
 5873: sub exit_handler {
 5874:     my ($cmd, $tail, $client) = @_;
 5875: 
 5876:     my $userinput = "$cmd:$tail";
 5877: 
 5878:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
 5879:     &Reply($client, "bye\n", $userinput);
 5880:     $client->shutdown(2);        # shutdown the socket forcibly.
 5881:     $client->close();
 5882: 
 5883:     return 0;
 5884: }
 5885: &register_handler("exit", \&exit_handler, 0,1,1);
 5886: &register_handler("init", \&exit_handler, 0,1,1);
 5887: &register_handler("quit", \&exit_handler, 0,1,1);
 5888: 
 5889: #  Determine if auto-enrollment is enabled.
 5890: #  Note that the original had what I believe to be a defect.
 5891: #  The original returned 0 if the requestor was not a registerd client.
 5892: #  It should return "refused".
 5893: # Formal Parameters:
 5894: #   $cmd       - The command that invoked us.
 5895: #   $tail      - The tail of the command (Extra command parameters.
 5896: #   $client    - The socket open on the client that issued the request.
 5897: # Returns:
 5898: #    1         - Indicating processing should continue.
 5899: #
 5900: sub enrollment_enabled_handler {
 5901:     my ($cmd, $tail, $client) = @_;
 5902:     my $userinput = $cmd.":".$tail; # For logging purposes.
 5903: 
 5904:     
 5905:     my ($cdom) = split(/:/, $tail, 2);   # Domain we're asking about.
 5906: 
 5907:     my $outcome  = &localenroll::run($cdom);
 5908:     &Reply($client, \$outcome, $userinput);
 5909: 
 5910:     return 1;
 5911: }
 5912: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
 5913: 
 5914: #
 5915: #   Validate an institutional code used for a LON-CAPA course.          
 5916: #
 5917: # Formal Parameters:
 5918: #   $cmd          - The command request that got us dispatched.
 5919: #   $tail         - The tail of the command.  In this case,
 5920: #                   this is a colon separated set of words that will be split
 5921: #                   into:
 5922: #                        $dom      - The domain for which the check of 
 5923: #                                    institutional course code will occur.
 5924: #
 5925: #                        $instcode - The institutional code for the course
 5926: #                                    being requested, or validated for rights
 5927: #                                    to request.
 5928: #
 5929: #                        $owner    - The course requestor (who will be the
 5930: #                                    course owner, in the form username:domain
 5931: #
 5932: #   $client       - Socket open on the client.
 5933: # Returns:
 5934: #    1           - Indicating processing should continue.
 5935: #
 5936: sub validate_instcode_handler {
 5937:     my ($cmd, $tail, $client) = @_;
 5938:     my $userinput = "$cmd:$tail";
 5939:     my ($dom,$instcode,$owner) = split(/:/, $tail);
 5940:     $instcode = &unescape($instcode);
 5941:     $owner = &unescape($owner);
 5942:     my ($outcome,$description,$credits) = 
 5943:         &localenroll::validate_instcode($dom,$instcode,$owner);
 5944:     my $result = &escape($outcome).'&'.&escape($description).'&'.
 5945:                  &escape($credits);
 5946:     &Reply($client, \$result, $userinput);
 5947: 
 5948:     return 1;
 5949: }
 5950: &register_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
 5951: 
 5952: #
 5953: #  Validate co-owner for cross-listed institutional code and
 5954: #  institutional course code itself used for a LON-CAPA course.
 5955: #
 5956: # Formal Parameters:
 5957: #   $cmd          - The command request that got us dispatched.
 5958: #   $tail         - The tail of the command.  In this case,
 5959: #                   this is a colon separated string containing:
 5960: #      $dom            - Course's LON-CAPA domain
 5961: #      $instcode       - Institutional course code for the course
 5962: #      $inst_xlist     - Institutional course Id for the crosslisting
 5963: #      $coowner        - Username of co-owner
 5964: #      (values for all but $dom have been escaped). 
 5965: #
 5966: #   $client       - Socket open on the client.
 5967: # Returns:
 5968: #    1           - Indicating processing should continue.
 5969: #
 5970: sub validate_instcrosslist_handler  {
 5971:     my ($cmd, $tail, $client) = @_;
 5972:     my $userinput = "$cmd:$tail";
 5973:     my ($dom,$instcode,$inst_xlist,$coowner) = split(/:/,$tail);
 5974:     $instcode = &unescape($instcode);
 5975:     $inst_xlist = &unescape($inst_xlist);
 5976:     $coowner = &unescape($coowner);
 5977:     my $outcome = &localenroll::validate_crosslist_access($dom,$instcode,
 5978:                                                           $inst_xlist,$coowner);
 5979:     &Reply($client, \$outcome, $userinput);
 5980: 
 5981:     return 1;
 5982: }
 5983: &register_handler("autovalidateinstcrosslist", \&validate_instcrosslist_handler, 0, 1, 0);
 5984: 
 5985: #   Get the official sections for which auto-enrollment is possible.
 5986: #   Since the admin people won't know about 'unofficial sections' 
 5987: #   we cannot auto-enroll on them.
 5988: # Formal Parameters:
 5989: #    $cmd     - The command request that got us dispatched here.
 5990: #    $tail    - The remainder of the request.  In our case this
 5991: #               will be split into:
 5992: #               $coursecode   - The course name from the admin point of view.
 5993: #               $cdom         - The course's domain(?).
 5994: #    $client  - Socket open on the client.
 5995: # Returns:
 5996: #    1    - Indiciting processing should continue.
 5997: #
 5998: sub get_sections_handler {
 5999:     my ($cmd, $tail, $client) = @_;
 6000:     my $userinput = "$cmd:$tail";
 6001: 
 6002:     my ($coursecode, $cdom) = split(/:/, $tail);
 6003:     my @secs = &localenroll::get_sections($coursecode,$cdom);
 6004:     my $seclist = &escape(join(':',@secs));
 6005: 
 6006:     &Reply($client, \$seclist, $userinput);
 6007:     
 6008: 
 6009:     return 1;
 6010: }
 6011: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
 6012: 
 6013: #   Validate the owner of a new course section.  
 6014: #
 6015: # Formal Parameters:
 6016: #   $cmd      - Command that got us dispatched.
 6017: #   $tail     - the remainder of the command.  For us this consists of a
 6018: #               colon separated string containing:
 6019: #                  $inst    - Course Id from the institutions point of view.
 6020: #                  $owner   - Proposed owner of the course.
 6021: #                  $cdom    - Domain of the course (from the institutions
 6022: #                             point of view?)..
 6023: #   $client   - Socket open on the client.
 6024: #
 6025: # Returns:
 6026: #   1        - Processing should continue.
 6027: #
 6028: sub validate_course_owner_handler {
 6029:     my ($cmd, $tail, $client)  = @_;
 6030:     my $userinput = "$cmd:$tail";
 6031:     my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
 6032:     
 6033:     $owner = &unescape($owner);
 6034:     $coowners = &unescape($coowners);
 6035:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
 6036:     &Reply($client, \$outcome, $userinput);
 6037: 
 6038: 
 6039: 
 6040:     return 1;
 6041: }
 6042: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
 6043: 
 6044: #
 6045: #   Validate a course section in the official schedule of classes
 6046: #   from the institutions point of view (part of autoenrollment).
 6047: #
 6048: # Formal Parameters:
 6049: #   $cmd          - The command request that got us dispatched.
 6050: #   $tail         - The tail of the command.  In this case,
 6051: #                   this is a colon separated set of words that will be split
 6052: #                   into:
 6053: #                        $inst_course_id - The course/section id from the
 6054: #                                          institutions point of view.
 6055: #                        $cdom           - The domain from the institutions
 6056: #                                          point of view.
 6057: #   $client       - Socket open on the client.
 6058: # Returns:
 6059: #    1           - Indicating processing should continue.
 6060: #
 6061: sub validate_course_section_handler {
 6062:     my ($cmd, $tail, $client) = @_;
 6063:     my $userinput = "$cmd:$tail";
 6064:     my ($inst_course_id, $cdom) = split(/:/, $tail);
 6065: 
 6066:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
 6067:     &Reply($client, \$outcome, $userinput);
 6068: 
 6069: 
 6070:     return 1;
 6071: }
 6072: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
 6073: 
 6074: #
 6075: #   Validate course owner's access to enrollment data for specific class section. 
 6076: #   
 6077: #
 6078: # Formal Parameters:
 6079: #    $cmd     - The command request that got us dispatched.
 6080: #    $tail    - The tail of the command.   In this case this is a colon separated
 6081: #               set of values that will be split into:
 6082: #               $inst_class  - Institutional code for the specific class section   
 6083: #               $ownerlist   - An escaped comma-separated list of username:domain 
 6084: #                              of the course owner, and co-owner(s).
 6085: #               $cdom        - The domain of the course from the institution's
 6086: #                              point of view.
 6087: #    $client  - The socket open on the client.
 6088: # Returns:
 6089: #    1 - continue processing.
 6090: #
 6091: 
 6092: sub validate_class_access_handler {
 6093:     my ($cmd, $tail, $client) = @_;
 6094:     my $userinput = "$cmd:$tail";
 6095:     my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
 6096:     my $owners = &unescape($ownerlist);
 6097:     my $outcome;
 6098:     eval {
 6099: 	local($SIG{__DIE__})='DEFAULT';
 6100: 	$outcome=&localenroll::check_section($inst_class,$owners,$cdom);
 6101:     };
 6102:     &Reply($client,\$outcome, $userinput);
 6103: 
 6104:     return 1;
 6105: }
 6106: &register_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
 6107: 
 6108: #
 6109: #   Validate course owner or co-owners(s) access to enrollment data for all sections
 6110: #   and crosslistings for a particular course.
 6111: #
 6112: #
 6113: # Formal Parameters:
 6114: #    $cmd     - The command request that got us dispatched.
 6115: #    $tail    - The tail of the command.   In this case this is a colon separated
 6116: #               set of values that will be split into:
 6117: #               $ownerlist   - An escaped comma-separated list of username:domain
 6118: #                              of the course owner, and co-owner(s).
 6119: #               $cdom        - The domain of the course from the institution's
 6120: #                              point of view.
 6121: #               $classes     - Frozen hash of institutional course sections and
 6122: #                              crosslistings.
 6123: #    $client  - The socket open on the client.
 6124: # Returns:
 6125: #    1 - continue processing.
 6126: #
 6127: 
 6128: sub validate_classes_handler {
 6129:     my ($cmd, $tail, $client) = @_;
 6130:     my $userinput = "$cmd:$tail";
 6131:     my ($ownerlist,$cdom,$classes) = split(/:/, $tail);
 6132:     my $classesref = &Apache::lonnet::thaw_unescape($classes);
 6133:     my $owners = &unescape($ownerlist);
 6134:     my $result;
 6135:     eval {
 6136:         local($SIG{__DIE__})='DEFAULT';
 6137:         my %validations;
 6138:         my $response = &localenroll::check_instclasses($owners,$cdom,$classesref,
 6139:                                                        \%validations);
 6140:         if ($response eq 'ok') {
 6141:             foreach my $key (keys(%validations)) {
 6142:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
 6143:             }
 6144:             $result =~ s/\&$//;
 6145:         } else {
 6146:             $result = 'error';
 6147:         }
 6148:     };
 6149:     if (!$@) {
 6150:         &Reply($client, \$result, $userinput);
 6151:     } else {
 6152:         &Failure($client,"unknown_cmd\n",$userinput);
 6153:     }
 6154:     return 1;
 6155: }
 6156: &register_handler("autovalidateinstclasses", \&validate_classes_handler, 0, 1, 0);
 6157: 
 6158: #
 6159: #   Create a password for a new LON-CAPA user added by auto-enrollment.
 6160: #   Only used for case where authentication method for new user is localauth
 6161: #
 6162: # Formal Parameters:
 6163: #    $cmd     - The command request that got us dispatched.
 6164: #    $tail    - The tail of the command.   In this case this is a colon separated
 6165: #               set of words that will be split into:
 6166: #               $authparam - An authentication parameter (localauth parameter).
 6167: #               $cdom      - The domain of the course from the institution's
 6168: #                            point of view.
 6169: #    $client  - The socket open on the client.
 6170: # Returns:
 6171: #    1 - continue processing.
 6172: #
 6173: sub create_auto_enroll_password_handler {
 6174:     my ($cmd, $tail, $client) = @_;
 6175:     my $userinput = "$cmd:$tail";
 6176: 
 6177:     my ($authparam, $cdom) = split(/:/, $userinput);
 6178: 
 6179:     my ($create_passwd,$authchk);
 6180:     ($authparam,
 6181:      $create_passwd,
 6182:      $authchk) = &localenroll::create_password($authparam,$cdom);
 6183: 
 6184:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
 6185: 	   $userinput);
 6186: 
 6187: 
 6188:     return 1;
 6189: }
 6190: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
 6191: 		  0, 1, 0);
 6192: 
 6193: sub auto_export_grades_handler {
 6194:     my ($cmd, $tail, $client) = @_;
 6195:     my $userinput = "$cmd:$tail";
 6196:     my ($cdom,$cnum,$info,$data) = split(/:/,$tail);
 6197:     my $inforef = &Apache::lonnet::thaw_unescape($info);
 6198:     my $dataref = &Apache::lonnet::thaw_unescape($data);
 6199:     my ($outcome,$result);;
 6200:     eval {
 6201:         local($SIG{__DIE__})='DEFAULT';
 6202:         my %rtnhash;
 6203:         $outcome=&localenroll::export_grades($cdom,$cnum,$inforef,$dataref,\%rtnhash);
 6204:         if ($outcome eq 'ok') {
 6205:             foreach my $key (keys(%rtnhash)) {
 6206:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
 6207:             }
 6208:             $result =~ s/\&$//;
 6209:         }
 6210:     };
 6211:     if (!$@) {
 6212:         if ($outcome eq 'ok') {
 6213:             if ($cipher) {
 6214:                 my $cmdlength=length($result);
 6215:                 $result.="         ";
 6216:                 my $encresult='';
 6217:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 6218:                     $encresult.= unpack("H16",
 6219:                                         $cipher->encrypt(substr($result,
 6220:                                                                 $encidx,
 6221:                                                                 8)));
 6222:                 }
 6223:                 &Reply( $client, "enc:$cmdlength:$encresult\n", $userinput);
 6224:             } else {
 6225:                 &Failure( $client, "error:no_key\n", $userinput);
 6226:             }
 6227:         } else {
 6228:             &Reply($client, "$outcome\n", $userinput);
 6229:         }
 6230:     } else {
 6231:         &Failure($client,"export_error\n",$userinput);
 6232:     }
 6233:     return 1;
 6234: }
 6235: &register_handler("autoexportgrades", \&auto_export_grades_handler,
 6236:                   1, 1, 0);
 6237: 
 6238: #   Retrieve and remove temporary files created by/during autoenrollment.
 6239: #
 6240: # Formal Parameters:
 6241: #    $cmd      - The command that got us dispatched.
 6242: #    $tail     - The tail of the command.  In our case this is a colon 
 6243: #                separated list that will be split into:
 6244: #                $filename - The name of the file to retrieve.
 6245: #                            The filename is given as a path relative to
 6246: #                            the LonCAPA temp file directory.
 6247: #    $client   - Socket open on the client.
 6248: #
 6249: # Returns:
 6250: #   1     - Continue processing.
 6251: sub retrieve_auto_file_handler {
 6252:     my ($cmd, $tail, $client)    = @_;
 6253:     my $userinput                = "cmd:$tail";
 6254: 
 6255:     my ($filename)   = split(/:/, $tail);
 6256: 
 6257:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
 6258: 
 6259:     if ($filename =~m{/\.\./}) {
 6260:         &Failure($client, "refused\n", $userinput);
 6261:     } elsif ($filename !~ /^$LONCAPA::match_domain\_$LONCAPA::match_courseid\_.+_classlist\.xml$/) {
 6262:         &Failure($client, "refused\n", $userinput);
 6263:     } elsif ( (-e $source) && ($filename ne '') ) {
 6264: 	my $reply = '';
 6265: 	if (open(my $fh,$source)) {
 6266: 	    while (<$fh>) {
 6267: 		chomp($_);
 6268: 		$_ =~ s/^\s+//g;
 6269: 		$_ =~ s/\s+$//g;
 6270: 		$reply .= $_;
 6271: 	    }
 6272: 	    close($fh);
 6273: 	    &Reply($client, &escape($reply)."\n", $userinput);
 6274: 
 6275: #   Does this have to be uncommented??!?  (RF).
 6276: #
 6277: #                                unlink($source);
 6278: 	} else {
 6279: 	    &Failure($client, "error\n", $userinput);
 6280: 	}
 6281:     } else {
 6282: 	&Failure($client, "error\n", $userinput);
 6283:     }
 6284:     
 6285: 
 6286:     return 1;
 6287: }
 6288: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
 6289: 
 6290: sub crsreq_checks_handler {
 6291:     my ($cmd, $tail, $client) = @_;
 6292:     my $userinput = "$cmd:$tail";
 6293:     my $dom = $tail;
 6294:     my $result;
 6295:     my @reqtypes = ('official','unofficial','community','textbook','placement');
 6296:     eval {
 6297:         local($SIG{__DIE__})='DEFAULT';
 6298:         my %validations;
 6299:         my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
 6300:                                                    \%validations);
 6301:         if ($response eq 'ok') { 
 6302:             foreach my $key (keys(%validations)) {
 6303:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
 6304:             }
 6305:             $result =~ s/\&$//;
 6306:         } else {
 6307:             $result = 'error';
 6308:         }
 6309:     };
 6310:     if (!$@) {
 6311:         &Reply($client, \$result, $userinput);
 6312:     } else {
 6313:         &Failure($client,"unknown_cmd\n",$userinput);
 6314:     }
 6315:     return 1;
 6316: }
 6317: &register_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
 6318: 
 6319: sub validate_crsreq_handler {
 6320:     my ($cmd, $tail, $client) = @_;
 6321:     my $userinput = "$cmd:$tail";
 6322:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
 6323:     $instcode = &unescape($instcode);
 6324:     $owner = &unescape($owner);
 6325:     $crstype = &unescape($crstype);
 6326:     $inststatuslist = &unescape($inststatuslist);
 6327:     $instcode = &unescape($instcode);
 6328:     $instseclist = &unescape($instseclist);
 6329:     my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
 6330:     my $outcome;
 6331:     eval {
 6332:         local($SIG{__DIE__})='DEFAULT';
 6333:         $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
 6334:                                                  $inststatuslist,$instcode,
 6335:                                                  $instseclist,$custominfo);
 6336:     };
 6337:     if (!$@) {
 6338:         &Reply($client, \$outcome, $userinput);
 6339:     } else {
 6340:         &Failure($client,"unknown_cmd\n",$userinput);
 6341:     }
 6342:     return 1;
 6343: }
 6344: &register_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
 6345: 
 6346: sub crsreq_update_handler {
 6347:     my ($cmd, $tail, $client) = @_;
 6348:     my $userinput = "$cmd:$tail";
 6349:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
 6350:         $accessstart,$accessend,$infohashref) =
 6351:         split(/:/, $tail);
 6352:     $crstype = &unescape($crstype);
 6353:     $action = &unescape($action);
 6354:     $ownername = &unescape($ownername);
 6355:     $ownerdomain = &unescape($ownerdomain);
 6356:     $fullname = &unescape($fullname);
 6357:     $title = &unescape($title);
 6358:     $code = &unescape($code);
 6359:     $accessstart = &unescape($accessstart);
 6360:     $accessend = &unescape($accessend);
 6361:     my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
 6362:     my ($result,$outcome);
 6363:     eval {
 6364:         local($SIG{__DIE__})='DEFAULT';
 6365:         my %rtnhash;
 6366:         $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
 6367:                                                 $ownername,$ownerdomain,$fullname,
 6368:                                                 $title,$code,$accessstart,$accessend,
 6369:                                                 $incoming,\%rtnhash);
 6370:         if ($outcome eq 'ok') {
 6371:             my @posskeys = qw(createdweb createdmsg createdcustomized createdactions queuedweb queuedmsg formitems reviewweb validationjs onload javascript);
 6372:             foreach my $key (keys(%rtnhash)) {
 6373:                 if (grep(/^\Q$key\E/,@posskeys)) {
 6374:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
 6375:                 }
 6376:             }
 6377:             $result =~ s/\&$//;
 6378:         }
 6379:     };
 6380:     if (!$@) {
 6381:         if ($outcome eq 'ok') {
 6382:             &Reply($client, \$result, $userinput);
 6383:         } else {
 6384:             &Reply($client, "format_error\n", $userinput);
 6385:         }
 6386:     } else {
 6387:         &Failure($client,"unknown_cmd\n",$userinput);
 6388:     }
 6389:     return 1;
 6390: }
 6391: &register_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
 6392: 
 6393: #
 6394: #   Read and retrieve institutional code format (for support form).
 6395: # Formal Parameters:
 6396: #    $cmd        - Command that dispatched us.
 6397: #    $tail       - Tail of the command.  In this case it conatins 
 6398: #                  the course domain and the coursename.
 6399: #    $client     - Socket open on the client.
 6400: # Returns:
 6401: #    1     - Continue processing.
 6402: #
 6403: sub get_institutional_code_format_handler {
 6404:     my ($cmd, $tail, $client)   = @_;
 6405:     my $userinput               = "$cmd:$tail";
 6406: 
 6407:     my $reply;
 6408:     my($cdom,$course) = split(/:/,$tail);
 6409:     my @pairs = split/\&/,$course;
 6410:     my %instcodes = ();
 6411:     my %codes = ();
 6412:     my @codetitles = ();
 6413:     my %cat_titles = ();
 6414:     my %cat_order = ();
 6415:     foreach (@pairs) {
 6416: 	my ($key,$value) = split/=/,$_;
 6417: 	$instcodes{&unescape($key)} = &unescape($value);
 6418:     }
 6419:     my $formatreply = &localenroll::instcode_format($cdom,
 6420: 						    \%instcodes,
 6421: 						    \%codes,
 6422: 						    \@codetitles,
 6423: 						    \%cat_titles,
 6424: 						    \%cat_order);
 6425:     if ($formatreply eq 'ok') {
 6426: 	my $codes_str = &Apache::lonnet::hash2str(%codes);
 6427: 	my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
 6428: 	my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
 6429: 	my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
 6430: 	&Reply($client,
 6431: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
 6432: 	       .$cat_order_str."\n",
 6433: 	       $userinput);
 6434:     } else {
 6435: 	# this else branch added by RF since if not ok, lonc will
 6436: 	# hang waiting on reply until timeout.
 6437: 	#
 6438: 	&Reply($client, "format_error\n", $userinput);
 6439:     }
 6440:     
 6441:     return 1;
 6442: }
 6443: &register_handler("autoinstcodeformat",
 6444: 		  \&get_institutional_code_format_handler,0,1,0);
 6445: 
 6446: sub get_institutional_defaults_handler {
 6447:     my ($cmd, $tail, $client)   = @_;
 6448:     my $userinput               = "$cmd:$tail";
 6449: 
 6450:     my $dom = $tail;
 6451:     my %defaults_hash;
 6452:     my @code_order;
 6453:     my $outcome;
 6454:     eval {
 6455:         local($SIG{__DIE__})='DEFAULT';
 6456:         $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
 6457:                                                    \@code_order);
 6458:     };
 6459:     if (!$@) {
 6460:         if ($outcome eq 'ok') {
 6461:             my $result='';
 6462:             while (my ($key,$value) = each(%defaults_hash)) {
 6463:                 $result.=&escape($key).'='.&escape($value).'&';
 6464:             }
 6465:             $result .= 'code_order='.&escape(join('&',@code_order));
 6466:             &Reply($client,\$result,$userinput);
 6467:         } else {
 6468:             &Reply($client,"error\n", $userinput);
 6469:         }
 6470:     } else {
 6471:         &Failure($client,"unknown_cmd\n",$userinput);
 6472:     }
 6473: }
 6474: &register_handler("autoinstcodedefaults",
 6475:                   \&get_institutional_defaults_handler,0,1,0);
 6476: 
 6477: sub get_possible_instcodes_handler {
 6478:     my ($cmd, $tail, $client)   = @_;
 6479:     my $userinput               = "$cmd:$tail";
 6480: 
 6481:     my $reply;
 6482:     my $cdom = $tail;
 6483:     my (@codetitles,%cat_titles,%cat_order,@code_order);
 6484:     my $formatreply = &localenroll::possible_instcodes($cdom,
 6485:                                                        \@codetitles,
 6486:                                                        \%cat_titles,
 6487:                                                        \%cat_order,
 6488:                                                        \@code_order);
 6489:     if ($formatreply eq 'ok') {
 6490:         my $result = join('&',map {&escape($_);} (@codetitles)).':';
 6491:         $result .= join('&',map {&escape($_);} (@code_order)).':';
 6492:         foreach my $key (keys(%cat_titles)) {
 6493:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
 6494:         }
 6495:         $result =~ s/\&$//;
 6496:         $result .= ':';
 6497:         foreach my $key (keys(%cat_order)) {
 6498:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
 6499:         }
 6500:         $result =~ s/\&$//;
 6501:         &Reply($client,\$result,$userinput);
 6502:     } else {
 6503:         &Reply($client, "format_error\n", $userinput);
 6504:     }
 6505:     return 1;
 6506: }
 6507: &register_handler("autopossibleinstcodes",
 6508:                   \&get_possible_instcodes_handler,0,1,0);
 6509: 
 6510: sub get_institutional_user_rules {
 6511:     my ($cmd, $tail, $client)   = @_;
 6512:     my $userinput               = "$cmd:$tail";
 6513:     my $dom = &unescape($tail);
 6514:     my (%rules_hash,@rules_order);
 6515:     my $outcome;
 6516:     eval {
 6517:         local($SIG{__DIE__})='DEFAULT';
 6518:         $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
 6519:     };
 6520:     if (!$@) {
 6521:         if ($outcome eq 'ok') {
 6522:             my $result;
 6523:             foreach my $key (keys(%rules_hash)) {
 6524:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
 6525:             }
 6526:             $result =~ s/\&$//;
 6527:             $result .= ':';
 6528:             if (@rules_order > 0) {
 6529:                 foreach my $item (@rules_order) {
 6530:                     $result .= &escape($item).'&';
 6531:                 }
 6532:             }
 6533:             $result =~ s/\&$//;
 6534:             &Reply($client,\$result,$userinput);
 6535:         } else {
 6536:             &Reply($client,"error\n", $userinput);
 6537:         }
 6538:     } else {
 6539:         &Failure($client,"unknown_cmd\n",$userinput);
 6540:     }
 6541: }
 6542: &register_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
 6543: 
 6544: sub get_institutional_id_rules {
 6545:     my ($cmd, $tail, $client)   = @_;
 6546:     my $userinput               = "$cmd:$tail";
 6547:     my $dom = &unescape($tail);
 6548:     my (%rules_hash,@rules_order);
 6549:     my $outcome;
 6550:     eval {
 6551:         local($SIG{__DIE__})='DEFAULT';
 6552:         $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
 6553:     };
 6554:     if (!$@) {
 6555:         if ($outcome eq 'ok') {
 6556:             my $result;
 6557:             foreach my $key (keys(%rules_hash)) {
 6558:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
 6559:             }
 6560:             $result =~ s/\&$//;
 6561:             $result .= ':';
 6562:             if (@rules_order > 0) {
 6563:                 foreach my $item (@rules_order) {
 6564:                     $result .= &escape($item).'&';
 6565:                 }
 6566:             }
 6567:             $result =~ s/\&$//;
 6568:             &Reply($client,\$result,$userinput);
 6569:         } else {
 6570:             &Reply($client,"error\n", $userinput);
 6571:         }
 6572:     } else {
 6573:         &Failure($client,"unknown_cmd\n",$userinput);
 6574:     }
 6575: }
 6576: &register_handler("instidrules",\&get_institutional_id_rules,0,1,0);
 6577: 
 6578: sub get_institutional_selfcreate_rules {
 6579:     my ($cmd, $tail, $client)   = @_;
 6580:     my $userinput               = "$cmd:$tail";
 6581:     my $dom = &unescape($tail);
 6582:     my (%rules_hash,@rules_order);
 6583:     my $outcome;
 6584:     eval {
 6585:         local($SIG{__DIE__})='DEFAULT';
 6586:         $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
 6587:     };
 6588:     if (!$@) {
 6589:         if ($outcome eq 'ok') {
 6590:             my $result;
 6591:             foreach my $key (keys(%rules_hash)) {
 6592:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
 6593:             }
 6594:             $result =~ s/\&$//;
 6595:             $result .= ':';
 6596:             if (@rules_order > 0) {
 6597:                 foreach my $item (@rules_order) {
 6598:                     $result .= &escape($item).'&';
 6599:                 }
 6600:             }
 6601:             $result =~ s/\&$//;
 6602:             &Reply($client,\$result,$userinput);
 6603:         } else {
 6604:             &Reply($client,"error\n", $userinput);
 6605:         }
 6606:     } else {
 6607:         &Failure($client,"unknown_cmd\n",$userinput);
 6608:     }
 6609: }
 6610: &register_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
 6611: 
 6612: 
 6613: sub institutional_username_check {
 6614:     my ($cmd, $tail, $client)   = @_;
 6615:     my $userinput               = "$cmd:$tail";
 6616:     my %rulecheck;
 6617:     my $outcome;
 6618:     my ($udom,$uname,@rules) = split(/:/,$tail);
 6619:     $udom = &unescape($udom);
 6620:     $uname = &unescape($uname);
 6621:     @rules = map {&unescape($_);} (@rules);
 6622:     eval {
 6623:         local($SIG{__DIE__})='DEFAULT';
 6624:         $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
 6625:     };
 6626:     if (!$@) {
 6627:         if ($outcome eq 'ok') {
 6628:             my $result='';
 6629:             foreach my $key (keys(%rulecheck)) {
 6630:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
 6631:             }
 6632:             &Reply($client,\$result,$userinput);
 6633:         } else {
 6634:             &Reply($client,"error\n", $userinput);
 6635:         }
 6636:     } else {
 6637:         &Failure($client,"unknown_cmd\n",$userinput);
 6638:     }
 6639: }
 6640: &register_handler("instrulecheck",\&institutional_username_check,0,1,0);
 6641: 
 6642: sub institutional_id_check {
 6643:     my ($cmd, $tail, $client)   = @_;
 6644:     my $userinput               = "$cmd:$tail";
 6645:     my %rulecheck;
 6646:     my $outcome;
 6647:     my ($udom,$id,@rules) = split(/:/,$tail);
 6648:     $udom = &unescape($udom);
 6649:     $id = &unescape($id);
 6650:     @rules = map {&unescape($_);} (@rules);
 6651:     eval {
 6652:         local($SIG{__DIE__})='DEFAULT';
 6653:         $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
 6654:     };
 6655:     if (!$@) {
 6656:         if ($outcome eq 'ok') {
 6657:             my $result='';
 6658:             foreach my $key (keys(%rulecheck)) {
 6659:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
 6660:             }
 6661:             &Reply($client,\$result,$userinput);
 6662:         } else {
 6663:             &Reply($client,"error\n", $userinput);
 6664:         }
 6665:     } else {
 6666:         &Failure($client,"unknown_cmd\n",$userinput);
 6667:     }
 6668: }
 6669: &register_handler("instidrulecheck",\&institutional_id_check,0,1,0);
 6670: 
 6671: sub institutional_selfcreate_check {
 6672:     my ($cmd, $tail, $client)   = @_;
 6673:     my $userinput               = "$cmd:$tail";
 6674:     my %rulecheck;
 6675:     my $outcome;
 6676:     my ($udom,$email,@rules) = split(/:/,$tail);
 6677:     $udom = &unescape($udom);
 6678:     $email = &unescape($email);
 6679:     @rules = map {&unescape($_);} (@rules);
 6680:     eval {
 6681:         local($SIG{__DIE__})='DEFAULT';
 6682:         $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
 6683:     };
 6684:     if (!$@) {
 6685:         if ($outcome eq 'ok') {
 6686:             my $result='';
 6687:             foreach my $key (keys(%rulecheck)) {
 6688:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
 6689:             }
 6690:             &Reply($client,\$result,$userinput);
 6691:         } else {
 6692:             &Reply($client,"error\n", $userinput);
 6693:         }
 6694:     } else {
 6695:         &Failure($client,"unknown_cmd\n",$userinput);
 6696:     }
 6697: }
 6698: &register_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
 6699: 
 6700: # Get domain specific conditions for import of student photographs to a course
 6701: #
 6702: # Retrieves information from photo_permission subroutine in localenroll.
 6703: # Returns outcome (ok) if no processing errors, and whether course owner is 
 6704: # required to accept conditions of use (yes/no).
 6705: #
 6706: #    
 6707: sub photo_permission_handler {
 6708:     my ($cmd, $tail, $client)   = @_;
 6709:     my $userinput               = "$cmd:$tail";
 6710:     my $cdom = $tail;
 6711:     my ($perm_reqd,$conditions);
 6712:     my $outcome;
 6713:     eval {
 6714: 	local($SIG{__DIE__})='DEFAULT';
 6715: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
 6716: 						  \$conditions);
 6717:     };
 6718:     if (!$@) {
 6719: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
 6720: 	       $userinput);
 6721:     } else {
 6722: 	&Failure($client,"unknown_cmd\n",$userinput);
 6723:     }
 6724:     return 1;
 6725: }
 6726: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
 6727: 
 6728: #
 6729: # Checks if student photo is available for a user in the domain, in the user's
 6730: # directory (in /userfiles/internal/studentphoto.jpg).
 6731: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
 6732: # the student's photo.   
 6733: 
 6734: sub photo_check_handler {
 6735:     my ($cmd, $tail, $client)   = @_;
 6736:     my $userinput               = "$cmd:$tail";
 6737:     my ($udom,$uname,$pid) = split(/:/,$tail);
 6738:     $udom = &unescape($udom);
 6739:     $uname = &unescape($uname);
 6740:     $pid = &unescape($pid);
 6741:     my $path=&propath($udom,$uname).'/userfiles/internal/';
 6742:     if (!-e $path) {
 6743:         &mkpath($path);
 6744:     }
 6745:     my $response;
 6746:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
 6747:     $result .= ':'.$response;
 6748:     &Reply($client, &escape($result)."\n",$userinput);
 6749:     return 1;
 6750: }
 6751: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
 6752: 
 6753: #
 6754: # Retrieve information from localenroll about whether to provide a button     
 6755: # for users who have enbled import of student photos to initiate an 
 6756: # update of photo files for registered students. Also include 
 6757: # comment to display alongside button.  
 6758: 
 6759: sub photo_choice_handler {
 6760:     my ($cmd, $tail, $client) = @_;
 6761:     my $userinput             = "$cmd:$tail";
 6762:     my $cdom                  = &unescape($tail);
 6763:     my ($update,$comment);
 6764:     eval {
 6765: 	local($SIG{__DIE__})='DEFAULT';
 6766: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
 6767:     };
 6768:     if (!$@) {
 6769: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
 6770:     } else {
 6771: 	&Failure($client,"unknown_cmd\n",$userinput);
 6772:     }
 6773:     return 1;
 6774: }
 6775: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
 6776: 
 6777: #
 6778: # Gets a student's photo to exist (in the correct image type) in the user's 
 6779: # directory.
 6780: # Formal Parameters:
 6781: #    $cmd     - The command request that got us dispatched.
 6782: #    $tail    - A colon separated set of words that will be split into:
 6783: #               $domain - student's domain
 6784: #               $uname  - student username
 6785: #               $type   - image type desired
 6786: #    $client  - The socket open on the client.
 6787: # Returns:
 6788: #    1 - continue processing.
 6789: 
 6790: sub student_photo_handler {
 6791:     my ($cmd, $tail, $client) = @_;
 6792:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
 6793: 
 6794:     my $path=&propath($domain,$uname). '/userfiles/internal/';
 6795:     my $filename = 'studentphoto.'.$ext;
 6796:     if ($type eq 'thumbnail') {
 6797:         $filename = 'studentphoto_tn.'.$ext;
 6798:     }
 6799:     if (-e $path.$filename) {
 6800: 	&Reply($client,"ok\n","$cmd:$tail");
 6801: 	return 1;
 6802:     }
 6803:     &mkpath($path);
 6804:     my $file;
 6805:     if ($type eq 'thumbnail') {
 6806: 	eval {
 6807: 	    local($SIG{__DIE__})='DEFAULT';
 6808: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
 6809: 	};
 6810:     } else {
 6811:         $file=&localstudentphoto::fetch($domain,$uname);
 6812:     }
 6813:     if (!$file) {
 6814: 	&Failure($client,"unavailable\n","$cmd:$tail");
 6815: 	return 1;
 6816:     }
 6817:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
 6818:     if (-e $path.$filename) {
 6819: 	&Reply($client,"ok\n","$cmd:$tail");
 6820: 	return 1;
 6821:     }
 6822:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
 6823:     return 1;
 6824: }
 6825: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
 6826: 
 6827: sub inst_usertypes_handler {
 6828:     my ($cmd, $domain, $client) = @_;
 6829:     my $res;
 6830:     my $userinput = $cmd.":".$domain; # For logging purposes.
 6831:     my (%typeshash,@order,$result);
 6832:     eval {
 6833: 	local($SIG{__DIE__})='DEFAULT';
 6834: 	$result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
 6835:     };
 6836:     if ($result eq 'ok') {
 6837:         if (keys(%typeshash) > 0) {
 6838:             foreach my $key (keys(%typeshash)) {
 6839:                 $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
 6840:             }
 6841:         }
 6842:         $res=~s/\&$//;
 6843:         $res .= ':';
 6844:         if (@order > 0) {
 6845:             foreach my $item (@order) {
 6846:                 $res .= &escape($item).'&';
 6847:             }
 6848:         }
 6849:         $res=~s/\&$//;
 6850:     }
 6851:     &Reply($client, \$res, $userinput);
 6852:     return 1;
 6853: }
 6854: &register_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
 6855: 
 6856: # mkpath makes all directories for a file, expects an absolute path with a
 6857: # file or a trailing / if just a dir is passed
 6858: # returns 1 on success 0 on failure
 6859: sub mkpath {
 6860:     my ($file)=@_;
 6861:     my @parts=split(/\//,$file,-1);
 6862:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
 6863:     for (my $i=3;$i<= ($#parts-1);$i++) {
 6864: 	$now.='/'.$parts[$i]; 
 6865: 	if (!-e $now) {
 6866: 	    if  (!mkdir($now,0770)) { return 0; }
 6867: 	}
 6868:     }
 6869:     return 1;
 6870: }
 6871: 
 6872: #---------------------------------------------------------------
 6873: #
 6874: #   Getting, decoding and dispatching requests:
 6875: #
 6876: #
 6877: #   Get a Request:
 6878: #   Gets a Request message from the client.  The transaction
 6879: #   is defined as a 'line' of text.  We remove the new line
 6880: #   from the text line.  
 6881: #
 6882: sub get_request {
 6883:     my $input = <$client>;
 6884:     chomp($input);
 6885: 
 6886:     &Debug("get_request: Request = $input\n");
 6887: 
 6888:     &status('Processing '.$clientname.':'.$input);
 6889: 
 6890:     return $input;
 6891: }
 6892: #---------------------------------------------------------------
 6893: #
 6894: #  Process a request.  This sub should shrink as each action
 6895: #  gets farmed out into a separat sub that is registered 
 6896: #  with the dispatch hash.  
 6897: #
 6898: # Parameters:
 6899: #    user_input   - The request received from the client (lonc).
 6900: #
 6901: # Returns:
 6902: #    true to keep processing, false if caller should exit.
 6903: #
 6904: sub process_request {
 6905:     my ($userinput) = @_; # Easier for now to break style than to
 6906:                           # fix all the userinput -> user_input.
 6907:     my $wasenc    = 0;		# True if request was encrypted.
 6908: # ------------------------------------------------------------ See if encrypted
 6909:     # for command
 6910:     # sethost:<server>
 6911:     # <command>:<args>
 6912:     #   we just send it to the processor
 6913:     # for
 6914:     # sethost:<server>:<command>:<args>
 6915:     #  we do the implict set host and then do the command
 6916:     if ($userinput =~ /^sethost:/) {
 6917: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
 6918: 	if (defined($userinput)) {
 6919: 	    &sethost("$cmd:$newid");
 6920: 	} else {
 6921: 	    $userinput = "$cmd:$newid";
 6922: 	}
 6923:     }
 6924: 
 6925:     if ($userinput =~ /^enc/) {
 6926: 	$userinput = decipher($userinput);
 6927: 	$wasenc=1;
 6928: 	if(!$userinput) {	# Cipher not defined.
 6929: 	    &Failure($client, "error: Encrypted data without negotated key\n");
 6930: 	    return 0;
 6931: 	}
 6932:     }
 6933:     Debug("process_request: $userinput\n");
 6934:     
 6935:     #  
 6936:     #   The 'correct way' to add a command to lond is now to
 6937:     #   write a sub to execute it and Add it to the command dispatch
 6938:     #   hash via a call to register_handler..  The comments to that
 6939:     #   sub should give you enough to go on to show how to do this
 6940:     #   along with the examples that are building up as this code
 6941:     #   is getting refactored.   Until all branches of the
 6942:     #   if/elseif monster below have been factored out into
 6943:     #   separate procesor subs, if the dispatch hash is missing
 6944:     #   the command keyword, we will fall through to the remainder
 6945:     #   of the if/else chain below in order to keep this thing in 
 6946:     #   working order throughout the transmogrification.
 6947: 
 6948:     my ($command, $tail) = split(/:/, $userinput, 2);
 6949:     chomp($command);
 6950:     chomp($tail);
 6951:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
 6952:     $command =~ s/(\r)//;	# And this too for parameterless commands.
 6953:     if(!$tail) {
 6954: 	$tail ="";		# defined but blank.
 6955:     }
 6956: 
 6957:     &Debug("Command received: $command, encoded = $wasenc");
 6958: 
 6959:     if(defined $Dispatcher{$command}) {
 6960: 
 6961: 	my $dispatch_info = $Dispatcher{$command};
 6962: 	my $handler       = $$dispatch_info[0];
 6963: 	my $need_encode   = $$dispatch_info[1];
 6964: 	my $client_types  = $$dispatch_info[2];
 6965: 	Debug("Matched dispatch hash: mustencode: $need_encode "
 6966: 	      ."ClientType $client_types");
 6967:       
 6968: 	#  Validate the request:
 6969:       
 6970: 	my $ok = 1;
 6971: 	my $requesterprivs = 0;
 6972: 	if(&isClient()) {
 6973: 	    $requesterprivs |= $CLIENT_OK;
 6974: 	}
 6975: 	if(&isManager()) {
 6976: 	    $requesterprivs |= $MANAGER_OK;
 6977: 	}
 6978: 	if($need_encode && (!$wasenc)) {
 6979: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
 6980: 	    $ok = 0;
 6981: 	}
 6982: 	if(($client_types & $requesterprivs) == 0) {
 6983: 	    Debug("Client not privileged to do this operation");
 6984: 	    $ok = 0;
 6985: 	}
 6986:         if ($ok) {
 6987:             my $realcommand = $command;
 6988:             if ($command eq 'querysend') {
 6989:                 my ($query,$rest)=split(/\:/,$tail,2);
 6990:                 $query=~s/\n*$//g;
 6991:                 my @possqueries = 
 6992:                     qw(userlog courselog fetchenrollment institutionalphotos usersearch instdirsearch getinstuser getmultinstusers);
 6993:                 if (grep(/^\Q$query\E$/,@possqueries)) {
 6994:                     $command .= '_'.$query;
 6995:                 } elsif ($query eq 'prepare activity log') {
 6996:                     $command .= '_activitylog';
 6997:                 }
 6998:             }
 6999:             if (ref($trust{$command}) eq 'HASH') {
 7000:                 my $donechecks;
 7001:                 if ($trust{$command}{'anywhere'}) {
 7002:                    $donechecks = 1;
 7003:                 } elsif ($trust{$command}{'manageronly'}) {
 7004:                     unless (&isManager()) {
 7005:                         $ok = 0;
 7006:                     }
 7007:                     $donechecks = 1;
 7008:                 } elsif ($trust{$command}{'institutiononly'}) {
 7009:                     unless ($clientsameinst) {
 7010:                         $ok = 0;
 7011:                     }
 7012:                     $donechecks = 1;
 7013:                 } elsif ($clientsameinst) {
 7014:                     $donechecks = 1;
 7015:                 }
 7016:                 unless ($donechecks) {
 7017:                     foreach my $rule (keys(%{$trust{$command}})) {
 7018:                         next if ($rule eq 'remote');
 7019:                         if ($trust{$command}{$rule}) {
 7020:                             if ($clientprohibited{$rule}) {
 7021:                                 $ok = 0;
 7022:                             } else {
 7023:                                 $ok = 1;
 7024:                                 $donechecks = 1;
 7025:                                 last;
 7026:                             }
 7027:                         }
 7028:                     }
 7029:                 }
 7030:                 unless ($donechecks) {
 7031:                     if ($trust{$command}{'remote'}) {
 7032:                         if ($clientremoteok) {
 7033:                             $ok = 1;
 7034:                         } else {
 7035:                             $ok = 0;
 7036:                         } 
 7037:                     }
 7038:                 }
 7039:             }
 7040:             $command = $realcommand;
 7041:         }
 7042: 
 7043: 	if($ok) {
 7044: 	    Debug("Dispatching to handler $command $tail");
 7045: 	    my $keep_going = &$handler($command, $tail, $client);
 7046: 	    return $keep_going;
 7047: 	} else {
 7048: 	    Debug("Refusing to dispatch because client did not match requirements");
 7049: 	    Failure($client, "refused\n", $userinput);
 7050: 	    return 1;
 7051: 	}
 7052:     }
 7053: 
 7054:     print $client "unknown_cmd\n";
 7055: # -------------------------------------------------------------------- complete
 7056:     Debug("process_request - returning 1");
 7057:     return 1;
 7058: }
 7059: #
 7060: #   Decipher encoded traffic
 7061: #  Parameters:
 7062: #     input      - Encoded data.
 7063: #  Returns:
 7064: #     Decoded data or undef if encryption key was not yet negotiated.
 7065: #  Implicit input:
 7066: #     cipher  - This global holds the negotiated encryption key.
 7067: #
 7068: sub decipher {
 7069:     my ($input)  = @_;
 7070:     my $output = '';
 7071:     
 7072:     
 7073:     if($cipher) {
 7074: 	my($enc, $enclength, $encinput) = split(/:/, $input);
 7075: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
 7076: 	    $output .= 
 7077: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
 7078: 	}
 7079: 	return substr($output, 0, $enclength);
 7080:     } else {
 7081: 	return undef;
 7082:     }
 7083: }
 7084: 
 7085: #
 7086: #   Register a command processor.  This function is invoked to register a sub
 7087: #   to process a request.  Once registered, the ProcessRequest sub can automatically
 7088: #   dispatch requests to an appropriate sub, and do the top level validity checking
 7089: #   as well:
 7090: #    - Is the keyword recognized.
 7091: #    - Is the proper client type attempting the request.
 7092: #    - Is the request encrypted if it has to be.
 7093: #   Parameters:
 7094: #    $request_name         - Name of the request being registered.
 7095: #                           This is the command request that will match
 7096: #                           against the hash keywords to lookup the information
 7097: #                           associated with the dispatch information.
 7098: #    $procedure           - Reference to a sub to call to process the request.
 7099: #                           All subs get called as follows:
 7100: #                             Procedure($cmd, $tail, $replyfd, $key)
 7101: #                             $cmd    - the actual keyword that invoked us.
 7102: #                             $tail   - the tail of the request that invoked us.
 7103: #                             $replyfd- File descriptor connected to the client
 7104: #    $must_encode          - True if the request must be encoded to be good.
 7105: #    $client_ok            - True if it's ok for a client to request this.
 7106: #    $manager_ok           - True if it's ok for a manager to request this.
 7107: # Side effects:
 7108: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
 7109: #      - On failure, the program will die as it's a bad internal bug to try to 
 7110: #        register a duplicate command handler.
 7111: #
 7112: sub register_handler {
 7113:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
 7114: 
 7115:     #  Don't allow duplication#
 7116:    
 7117:     if (defined $Dispatcher{$request_name}) {
 7118: 	die "Attempting to define a duplicate request handler for $request_name\n";
 7119:     }
 7120:     #   Build the client type mask:
 7121:     
 7122:     my $client_type_mask = 0;
 7123:     if($client_ok) {
 7124: 	$client_type_mask  |= $CLIENT_OK;
 7125:     }
 7126:     if($manager_ok) {
 7127: 	$client_type_mask  |= $MANAGER_OK;
 7128:     }
 7129:    
 7130:     #  Enter the hash:
 7131:       
 7132:     my @entry = ($procedure, $must_encode, $client_type_mask);
 7133:    
 7134:     $Dispatcher{$request_name} = \@entry;
 7135:    
 7136: }
 7137: 
 7138: 
 7139: #------------------------------------------------------------------
 7140: 
 7141: 
 7142: 
 7143: 
 7144: #
 7145: #  Convert an error return code from lcpasswd to a string value.
 7146: #
 7147: sub lcpasswdstrerror {
 7148:     my $ErrorCode = shift;
 7149:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
 7150: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
 7151:     } else {
 7152: 	return $passwderrors[$ErrorCode];
 7153:     }
 7154: }
 7155: 
 7156: # grabs exception and records it to log before exiting
 7157: sub catchexception {
 7158:     my ($error)=@_;
 7159:     $SIG{'QUIT'}='DEFAULT';
 7160:     $SIG{__DIE__}='DEFAULT';
 7161:     &status("Catching exception");
 7162:     &logthis("<font color='red'>CRITICAL: "
 7163:      ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
 7164:      ."a crash with this error msg->[$error]</font>");
 7165:     &logthis('Famous last words: '.$status.' - '.$lastlog);
 7166:     if ($client) { print $client "error: $error\n"; }
 7167:     $server->close();
 7168:     die($error);
 7169: }
 7170: sub timeout {
 7171:     &status("Handling Timeout");
 7172:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
 7173:     &catchexception('Timeout');
 7174: }
 7175: # -------------------------------- Set signal handlers to record abnormal exits
 7176: 
 7177: 
 7178: $SIG{'QUIT'}=\&catchexception;
 7179: $SIG{__DIE__}=\&catchexception;
 7180: 
 7181: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
 7182: &status("Read loncapa.conf and loncapa_apache.conf");
 7183: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
 7184: %perlvar=%{$perlvarref};
 7185: undef $perlvarref;
 7186: 
 7187: # ----------------------------- Make sure this process is running from user=www
 7188: my $wwwid=getpwnam('www');
 7189: if ($wwwid!=$<) {
 7190:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
 7191:    my $subj="LON: $currenthostid User ID mismatch";
 7192:    system("echo 'User ID mismatch.  lond must be run as user www.' |".
 7193:           " mail -s '$subj' $emailto > /dev/null");
 7194:    exit 1;
 7195: }
 7196: 
 7197: # --------------------------------------------- Check if other instance running
 7198: 
 7199: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
 7200: 
 7201: if (-e $pidfile) {
 7202:    my $lfh=IO::File->new("$pidfile");
 7203:    my $pide=<$lfh>;
 7204:    chomp($pide);
 7205:    if (kill 0 => $pide) { die "already running"; }
 7206: }
 7207: 
 7208: # ------------------------------------------------------------- Read hosts file
 7209: 
 7210: 
 7211: 
 7212: # establish SERVER socket, bind and listen.
 7213: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
 7214:                                 Type      => SOCK_STREAM,
 7215:                                 Proto     => 'tcp',
 7216:                                 ReuseAddr     => 1,
 7217:                                 Listen    => 10 )
 7218:   or die "making socket: $@\n";
 7219: 
 7220: # --------------------------------------------------------- Do global variables
 7221: 
 7222: # global variables
 7223: 
 7224: my %children               = ();       # keys are current child process IDs
 7225: 
 7226: sub REAPER {                        # takes care of dead children
 7227:     $SIG{CHLD} = \&REAPER;
 7228:     &status("Handling child death");
 7229:     my $pid;
 7230:     do {
 7231: 	$pid = waitpid(-1,&WNOHANG());
 7232: 	if (defined($children{$pid})) {
 7233: 	    &logthis("Child $pid died");
 7234: 	    delete($children{$pid});
 7235: 	} elsif ($pid > 0) {
 7236: 	    &logthis("Unknown Child $pid died");
 7237: 	}
 7238:     } while ( $pid > 0 );
 7239:     foreach my $child (keys(%children)) {
 7240: 	$pid = waitpid($child,&WNOHANG());
 7241: 	if ($pid > 0) {
 7242: 	    &logthis("Child $child - $pid looks like we missed it's death");
 7243: 	    delete($children{$pid});
 7244: 	}
 7245:     }
 7246:     &status("Finished Handling child death");
 7247: }
 7248: 
 7249: sub HUNTSMAN {                      # signal handler for SIGINT
 7250:     &status("Killing children (INT)");
 7251:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
 7252:     kill 'INT' => keys %children;
 7253:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
 7254:     my $execdir=$perlvar{'lonDaemons'};
 7255:     unlink("$execdir/logs/lond.pid");
 7256:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
 7257:     &status("Done killing children");
 7258:     exit;                           # clean up with dignity
 7259: }
 7260: 
 7261: sub HUPSMAN {                      # signal handler for SIGHUP
 7262:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
 7263:     &status("Killing children for restart (HUP)");
 7264:     kill 'INT' => keys %children;
 7265:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
 7266:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
 7267:     my $execdir=$perlvar{'lonDaemons'};
 7268:     unlink("$execdir/logs/lond.pid");
 7269:     &status("Restarting self (HUP)");
 7270:     exec("$execdir/lond");         # here we go again
 7271: }
 7272: 
 7273: #
 7274: #  Reload the Apache daemon's state.
 7275: #  This is done by invoking /home/httpd/perl/apachereload
 7276: #  a setuid perl script that can be root for us to do this job.
 7277: #
 7278: sub ReloadApache {
 7279: # --------------------------- Handle case of another apachereload process (locking)
 7280:     if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
 7281:         my $execdir = $perlvar{'lonDaemons'};
 7282:         my $script  = $execdir."/apachereload";
 7283:         system($script);
 7284:         unlink('/tmp/lock_apachereload'); #  Remove the lock file.
 7285:     }
 7286: }
 7287: 
 7288: #
 7289: #   Called in response to a USR2 signal.
 7290: #   - Reread hosts.tab
 7291: #   - All children connected to hosts that were removed from hosts.tab
 7292: #     are killed via SIGINT
 7293: #   - All children connected to previously existing hosts are sent SIGUSR1
 7294: #   - Our internal hosts hash is updated to reflect the new contents of
 7295: #     hosts.tab causing connections from hosts added to hosts.tab to
 7296: #     now be honored.
 7297: #
 7298: sub UpdateHosts {
 7299:     &status("Reload hosts.tab");
 7300:     logthis('<font color="blue"> Updating connections </font>');
 7301:     #
 7302:     #  The %children hash has the set of IP's we currently have children
 7303:     #  on.  These need to be matched against records in the hosts.tab
 7304:     #  Any ip's no longer in the table get killed off they correspond to
 7305:     #  either dropped or changed hosts.  Note that the re-read of the table
 7306:     #  will take care of new and changed hosts as connections come into being.
 7307: 
 7308:     &Apache::lonnet::reset_hosts_info();
 7309:     my %active;
 7310: 
 7311:     foreach my $child (keys(%children)) {
 7312: 	my $childip = $children{$child};
 7313: 	if ($childip ne '127.0.0.1'
 7314: 	    && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
 7315: 	    logthis('<font color="blue"> UpdateHosts killing child '
 7316: 		    ." $child for ip $childip </font>");
 7317: 	    kill('INT', $child);
 7318: 	} else {
 7319:             $active{$child} = $childip;
 7320: 	    logthis('<font color="green"> keeping child for ip '
 7321: 		    ." $childip (pid=$child) </font>");
 7322: 	}
 7323:     }
 7324: 
 7325:     my %oldconf = %secureconf;
 7326:     my %connchange;
 7327:     if (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
 7328:         logthis('<font color="blue"> Reloaded SSL connection rules and cleared CRL checking history </font>');
 7329:     } else {
 7330:         logthis('<font color="yellow"> Failed to reload SSL connection rules and clear CRL checking history </font>');
 7331:     }
 7332:     if ((ref($oldconf{'connfrom'}) eq 'HASH') && (ref($secureconf{'connfrom'}) eq 'HASH')) {
 7333:         foreach my $type ('dom','intdom','other') {
 7334:             if ((($oldconf{'connfrom'}{$type} eq 'no') && ($secureconf{'connfrom'}{$type} eq 'req')) ||
 7335:                 (($oldconf{'connfrom'}{$type} eq 'req') && ($secureconf{'connfrom'}{$type} eq 'no'))) {
 7336:                 $connchange{$type} = 1;
 7337:             }
 7338:         }
 7339:     }
 7340:     if (keys(%connchange)) {
 7341:         foreach my $child (keys(%active)) {
 7342:             my $childip = $active{$child};
 7343:             if ($childip ne '127.0.0.1') {
 7344:                 my $childhostname  = gethostbyaddr(Socket::inet_aton($childip),AF_INET);
 7345:                 if ($childhostname ne '') {
 7346:                     my $childlonhost = &Apache::lonnet::get_server_homeID($childhostname);
 7347:                     my ($samedom,$sameinst) = &set_client_info($childlonhost);
 7348:                     if ($samedom) {
 7349:                         if ($connchange{'dom'}) {
 7350:                             logthis('<font color="blue"> UpdateHosts killing child '
 7351:                                    ." $child for ip $childip </font>");
 7352:                             kill('INT', $child);
 7353:                         }
 7354:                     } elsif ($sameinst) {
 7355:                         if ($connchange{'intdom'}) {
 7356:                             logthis('<font color="blue"> UpdateHosts killing child '
 7357:                                    ." $child for ip $childip </font>");
 7358:                            kill('INT', $child);
 7359:                         }
 7360:                     } else {
 7361:                         if ($connchange{'other'}) {
 7362:                             logthis('<font color="blue"> UpdateHosts killing child '
 7363:                                    ." $child for ip $childip </font>");
 7364:                             kill('INT', $child);
 7365:                         }
 7366:                     }
 7367:                 }
 7368:             }
 7369:         }
 7370:     }
 7371:     ReloadApache;
 7372:     &status("Finished reloading hosts.tab");
 7373: }
 7374: 
 7375: sub checkchildren {
 7376:     &status("Checking on the children (sending signals)");
 7377:     &initnewstatus();
 7378:     &logstatus();
 7379:     &logthis('Going to check on the children');
 7380:     my $docdir=$perlvar{'lonDocRoot'};
 7381:     foreach (sort keys %children) {
 7382: 	#sleep 1;
 7383:         unless (kill 'USR1' => $_) {
 7384: 	    &logthis ('Child '.$_.' is dead');
 7385:             &logstatus($$.' is dead');
 7386: 	    delete($children{$_});
 7387:         } 
 7388:     }
 7389:     sleep 5;
 7390:     $SIG{ALRM} = sub { Debug("timeout"); 
 7391: 		       die "timeout";  };
 7392:     $SIG{__DIE__} = 'DEFAULT';
 7393:     &status("Checking on the children (waiting for reports)");
 7394:     foreach (sort keys %children) {
 7395:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
 7396:           eval {
 7397:             alarm(300);
 7398: 	    &logthis('Child '.$_.' did not respond');
 7399: 	    kill 9 => $_;
 7400: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
 7401: 	    #$subj="LON: $currenthostid killed lond process $_";
 7402: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
 7403: 	    #$execdir=$perlvar{'lonDaemons'};
 7404: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
 7405: 	    delete($children{$_});
 7406: 	    alarm(0);
 7407: 	  }
 7408:         }
 7409:     }
 7410:     $SIG{ALRM} = 'DEFAULT';
 7411:     $SIG{__DIE__} = \&catchexception;
 7412:     &status("Finished checking children");
 7413:     &logthis('Finished Checking children');
 7414: }
 7415: 
 7416: # --------------------------------------------------------------------- Logging
 7417: 
 7418: sub logthis {
 7419:     my $message=shift;
 7420:     my $execdir=$perlvar{'lonDaemons'};
 7421:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
 7422:     my $now=time;
 7423:     my $local=localtime($now);
 7424:     $lastlog=$local.': '.$message;
 7425:     print $fh "$local ($$): $message\n";
 7426: }
 7427: 
 7428: # ------------------------- Conditional log if $DEBUG true.
 7429: sub Debug {
 7430:     my $message = shift;
 7431:     if($DEBUG) {
 7432: 	&logthis($message);
 7433:     }
 7434: }
 7435: 
 7436: #
 7437: #   Sub to do replies to client.. this gives a hook for some
 7438: #   debug tracing too:
 7439: #  Parameters:
 7440: #     fd      - File open on client.
 7441: #     reply   - Text to send to client.
 7442: #     request - Original request from client.
 7443: #
 7444: #NOTE $reply must be terminated by exactly *one* \n. If $reply is a reference
 7445: #this is done automatically ($$reply must not contain any \n in this case). 
 7446: #If $reply is a string the caller has to ensure this.
 7447: sub Reply {
 7448:     my ($fd, $reply, $request) = @_;
 7449:     if (ref($reply)) {
 7450: 	print $fd $$reply;
 7451: 	print $fd "\n";
 7452: 	if ($DEBUG) { Debug("Request was $request  Reply was $$reply"); }
 7453:     } else {
 7454: 	print $fd $reply;
 7455: 	if ($DEBUG) { Debug("Request was $request  Reply was $reply"); }
 7456:     }
 7457:     $Transactions++;
 7458: }
 7459: 
 7460: 
 7461: #
 7462: #    Sub to report a failure.
 7463: #    This function:
 7464: #     -   Increments the failure statistic counters.
 7465: #     -   Invokes Reply to send the error message to the client.
 7466: # Parameters:
 7467: #    fd       - File descriptor open on the client
 7468: #    reply    - Reply text to emit.
 7469: #    request  - The original request message (used by Reply
 7470: #               to debug if that's enabled.
 7471: # Implicit outputs:
 7472: #    $Failures- The number of failures is incremented.
 7473: #    Reply (invoked here) sends a message to the 
 7474: #    client:
 7475: #
 7476: sub Failure {
 7477:     my $fd      = shift;
 7478:     my $reply   = shift;
 7479:     my $request = shift;
 7480:    
 7481:     $Failures++;
 7482:     Reply($fd, $reply, $request);      # That's simple eh?
 7483: }
 7484: # ------------------------------------------------------------------ Log status
 7485: 
 7486: sub logstatus {
 7487:     &status("Doing logging");
 7488:     my $docdir=$perlvar{'lonDocRoot'};
 7489:     {
 7490: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
 7491:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
 7492:         $fh->close();
 7493:     }
 7494:     &status("Finished $$.txt");
 7495:     {
 7496: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
 7497: 	flock(LOG,LOCK_EX);
 7498: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
 7499: 	    .$status."\t".$lastlog."\t $keymode\n";
 7500: 	flock(LOG,LOCK_UN);
 7501: 	close(LOG);
 7502:     }
 7503:     &status("Finished logging");
 7504: }
 7505: 
 7506: sub initnewstatus {
 7507:     my $docdir=$perlvar{'lonDocRoot'};
 7508:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
 7509:     my $now=time();
 7510:     my $local=localtime($now);
 7511:     print $fh "LOND status $local - parent $$\n\n";
 7512:     opendir(DIR,"$docdir/lon-status/londchld");
 7513:     while (my $filename=readdir(DIR)) {
 7514:         unlink("$docdir/lon-status/londchld/$filename");
 7515:     }
 7516:     closedir(DIR);
 7517: }
 7518: 
 7519: # -------------------------------------------------------------- Status setting
 7520: 
 7521: sub status {
 7522:     my $what=shift;
 7523:     my $now=time;
 7524:     my $local=localtime($now);
 7525:     $status=$local.': '.$what;
 7526:     $0='lond: '.$what.' '.$local;
 7527: }
 7528: 
 7529: # -------------------------------------------------------------- Talk to lonsql
 7530: 
 7531: sub sql_reply {
 7532:     my ($cmd)=@_;
 7533:     my $answer=&sub_sql_reply($cmd);
 7534:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
 7535:     return $answer;
 7536: }
 7537: 
 7538: sub sub_sql_reply {
 7539:     my ($cmd)=@_;
 7540:     my $unixsock="mysqlsock";
 7541:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
 7542:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
 7543:                                       Type    => SOCK_STREAM,
 7544:                                       Timeout => 10)
 7545:        or return "con_lost";
 7546:     print $sclient "$cmd:$currentdomainid\n";
 7547:     my $answer=<$sclient>;
 7548:     chomp($answer);
 7549:     if (!$answer) { $answer="con_lost"; }
 7550:     return $answer;
 7551: }
 7552: 
 7553: # --------------------------------------- Is this the home server of an author?
 7554: 
 7555: sub ishome {
 7556:     my $author=shift;
 7557:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 7558:     my ($udom,$uname)=split(/\//,$author);
 7559:     my $proname=propath($udom,$uname);
 7560:     if (-e $proname) {
 7561: 	return 'owner';
 7562:     } else {
 7563:         return 'not_owner';
 7564:     }
 7565: }
 7566: 
 7567: # ======================================================= Continue main program
 7568: # ---------------------------------------------------- Fork once and dissociate
 7569: 
 7570: my $fpid=fork;
 7571: exit if $fpid;
 7572: die "Couldn't fork: $!" unless defined ($fpid);
 7573: 
 7574: POSIX::setsid() or die "Can't start new session: $!";
 7575: 
 7576: # ------------------------------------------------------- Write our PID on disk
 7577: 
 7578: my $execdir=$perlvar{'lonDaemons'};
 7579: open (PIDSAVE,">$execdir/logs/lond.pid");
 7580: print PIDSAVE "$$\n";
 7581: close(PIDSAVE);
 7582: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
 7583: &status('Starting');
 7584: 
 7585: 
 7586: 
 7587: # ----------------------------------------------------- Install signal handlers
 7588: 
 7589: 
 7590: $SIG{CHLD} = \&REAPER;
 7591: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 7592: $SIG{HUP}  = \&HUPSMAN;
 7593: $SIG{USR1} = \&checkchildren;
 7594: $SIG{USR2} = \&UpdateHosts;
 7595: 
 7596: #  Read the host hashes:
 7597: &Apache::lonnet::load_hosts_tab();
 7598: my %iphost = &Apache::lonnet::get_iphost(1);
 7599: 
 7600: $dist=`$perlvar{'lonDaemons'}/distprobe`;
 7601: 
 7602: my $arch = `uname -i`;
 7603: chomp($arch);
 7604: if ($arch eq 'unknown') {
 7605:     $arch = `uname -m`;
 7606:     chomp($arch);
 7607: }
 7608: 
 7609: unless (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
 7610:     &logthis('<font color="blue">No connectionrules table. Will fallback to loncapa.conf</font>');
 7611: }
 7612: 
 7613: # --------------------------------------------------------------
 7614: #   Accept connections.  When a connection comes in, it is validated
 7615: #   and if good, a child process is created to process transactions
 7616: #   along the connection.
 7617: 
 7618: while (1) {
 7619:     &status('Starting accept');
 7620:     $client = $server->accept() or next;
 7621:     &status('Accepted '.$client.' off to spawn');
 7622:     make_new_child($client);
 7623:     &status('Finished spawning');
 7624: }
 7625: 
 7626: sub make_new_child {
 7627:     my $pid;
 7628: #    my $cipher;     # Now global
 7629:     my $sigset;
 7630: 
 7631:     $client = shift;
 7632:     &status('Starting new child '.$client);
 7633:     &logthis('<font color="green"> Attempting to start child ('.$client.
 7634: 	     ")</font>");    
 7635:     # block signal for fork
 7636:     $sigset = POSIX::SigSet->new(SIGINT);
 7637:     sigprocmask(SIG_BLOCK, $sigset)
 7638:         or die "Can't block SIGINT for fork: $!\n";
 7639: 
 7640:     die "fork: $!" unless defined ($pid = fork);
 7641: 
 7642:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
 7643: 	                               # connection liveness.
 7644: 
 7645:     #
 7646:     #  Figure out who we're talking to so we can record the peer in 
 7647:     #  the pid hash.
 7648:     #
 7649:     my $caller = getpeername($client);
 7650:     my ($port,$iaddr);
 7651:     if (defined($caller) && length($caller) > 0) {
 7652: 	($port,$iaddr)=unpack_sockaddr_in($caller);
 7653:     } else {
 7654: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
 7655:     }
 7656:     if (defined($iaddr)) {
 7657: 	$clientip  = inet_ntoa($iaddr);
 7658: 	Debug("Connected with $clientip");
 7659:     } else {
 7660: 	&logthis("Unable to determine clientip");
 7661: 	$clientip='Unavailable';
 7662:     }
 7663:     
 7664:     if ($pid) {
 7665:         # Parent records the child's birth and returns.
 7666:         sigprocmask(SIG_UNBLOCK, $sigset)
 7667:             or die "Can't unblock SIGINT for fork: $!\n";
 7668:         $children{$pid} = $clientip;
 7669:         &status('Started child '.$pid);
 7670: 	close($client);
 7671:         return;
 7672:     } else {
 7673:         # Child can *not* return from this subroutine.
 7674:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
 7675:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
 7676:                                 #don't get intercepted
 7677:         $SIG{USR1}= \&logstatus;
 7678:         $SIG{ALRM}= \&timeout;
 7679: 	#
 7680: 	# Block sigpipe as it gets thrownon socket disconnect and we want to 
 7681: 	# deal with that as a read faiure instead.
 7682: 	#
 7683: 	my $blockset = POSIX::SigSet->new(SIGPIPE);
 7684: 	sigprocmask(SIG_BLOCK, $blockset);
 7685: 
 7686:         $lastlog='Forked ';
 7687:         $status='Forked';
 7688: 
 7689:         # unblock signals
 7690:         sigprocmask(SIG_UNBLOCK, $sigset)
 7691:             or die "Can't unblock SIGINT for fork: $!\n";
 7692: 
 7693: #        my $tmpsnum=0;            # Now global
 7694: #---------------------------------------------------- kerberos 5 initialization
 7695:         &Authen::Krb5::init_context();
 7696: 
 7697:         my $no_ets;
 7698:         if ($dist =~ /^(?:centos|rhes|scientific|oracle)(\d+)$/) {
 7699:             if ($1 >= 7) {
 7700:                 $no_ets = 1;
 7701:             }
 7702:         } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
 7703:             if (($1 eq '9.3') || ($1 >= 12.2)) {
 7704:                 $no_ets = 1; 
 7705:             }
 7706:         } elsif ($dist =~ /^sles(\d+)$/) {
 7707:             if ($1 > 11) {
 7708:                 $no_ets = 1;
 7709:             }
 7710:         } elsif ($dist =~ /^fedora(\d+)$/) {
 7711:             if ($1 < 7) {
 7712:                 $no_ets = 1;
 7713:             }
 7714:         }
 7715:         unless ($no_ets) {
 7716: 	    &Authen::Krb5::init_ets();
 7717: 	}
 7718: 
 7719: 	&status('Accepted connection');
 7720: # =============================================================================
 7721:             # do something with the connection
 7722: # -----------------------------------------------------------------------------
 7723: 	# see if we know client and 'check' for spoof IP by ineffective challenge
 7724: 
 7725: 	my $outsideip=$clientip;
 7726: 	if ($clientip eq '127.0.0.1') {
 7727: 	    $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
 7728: 	}
 7729: 	&ReadManagerTable();
 7730: 	my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
 7731: 	my $ismanager=($managers{$outsideip}    ne undef);
 7732: 	$clientname  = "[unknown]";
 7733: 	if($clientrec) {	# Establish client type.
 7734: 	    $ConnectionType = "client";
 7735: 	    $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
 7736: 	    if($ismanager) {
 7737: 		$ConnectionType = "both";
 7738: 	    }
 7739: 	} else {
 7740: 	    $ConnectionType = "manager";
 7741: 	    $clientname = $managers{$outsideip};
 7742: 	}
 7743: 	my $clientok;
 7744: 
 7745: 	if ($clientrec || $ismanager) {
 7746: 	    &status("Waiting for init from $clientip $clientname");
 7747: 	    &logthis('<font color="yellow">INFO: Connection, '.
 7748: 		     $clientip.
 7749: 		  " ($clientname) connection type = $ConnectionType </font>" );
 7750: 	    &status("Connecting $clientip  ($clientname))"); 
 7751: 	    my $remotereq=<$client>;
 7752: 	    chomp($remotereq);
 7753: 	    Debug("Got init: $remotereq");
 7754: 
 7755: 	    if ($remotereq =~ /^init/) {
 7756: 		&sethost("sethost:$perlvar{'lonHostID'}");
 7757: 		#
 7758: 		#  If the remote is attempting a local init... give that a try:
 7759: 		#
 7760: 		(my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
 7761:         # For LON-CAPA 2.9, the  client session will have sent its LON-CAPA
 7762:         # version when initiating the connection. For LON-CAPA 2.8 and older,
 7763:         # the version is retrieved from the global %loncaparevs in lonnet.pm.            
 7764:         # $clientversion contains path to keyfile if $inittype eq 'local'
 7765:         # it's overridden below in this case
 7766:         $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
 7767: 
 7768: 		# If the connection type is ssl, but I didn't get my
 7769: 		# certificate files yet, then I'll drop  back to 
 7770: 		# insecure (if allowed).
 7771: 
 7772:                 if ($inittype eq "ssl") {
 7773:                     my $context;
 7774:                     if ($clientsamedom) {
 7775:                         $context = 'dom';
 7776:                         if ($secureconf{'connfrom'}{'dom'} eq 'no') {
 7777:                             $inittype = "";
 7778:                         }
 7779:                     } elsif ($clientsameinst) {
 7780:                         $context = 'intdom';
 7781:                         if ($secureconf{'connfrom'}{'intdom'} eq 'no') {
 7782:                             $inittype = "";
 7783:                         }
 7784:                     } else {
 7785:                         $context = 'other';
 7786:                         if ($secureconf{'connfrom'}{'other'} eq 'no') {
 7787:                             $inittype = "";
 7788:                         }
 7789:                     }
 7790:                     if ($inittype eq '') {
 7791:                         &logthis("<font color=\"blue\"> Domain config set "
 7792:                                 ."to no ssl for $clientname (context: $context)"
 7793:                                 ." -- trying insecure auth</font>");
 7794:                     }
 7795:                 }
 7796: 
 7797: 		if($inittype eq "ssl") {
 7798: 		    my ($ca, $cert) = lonssl::CertificateFile;
 7799: 		    my $kfile       = lonssl::KeyFile;
 7800: 		    if((!$ca)   || 
 7801: 		       (!$cert) || 
 7802: 		       (!$kfile)) {
 7803: 			$inittype = ""; # This forces insecure attempt.
 7804: 			&logthis("<font color=\"blue\"> Certificates not "
 7805: 				 ."installed -- trying insecure auth</font>");
 7806: 		    } else {	# SSL certificates are in place so
 7807: 		    }		# Leave the inittype alone.
 7808: 		}
 7809: 
 7810: 		if($inittype eq "local") {
 7811:                     $clientversion = $perlvar{'lonVersion'};
 7812: 		    my $key = LocalConnection($client, $remotereq);
 7813: 		    if($key) {
 7814: 			Debug("Got local key $key");
 7815: 			$clientok     = 1;
 7816: 			my $cipherkey = pack("H32", $key);
 7817: 			$cipher       = new IDEA($cipherkey);
 7818: 			print $client "ok:local\n";
 7819: 			&logthis('<font color="green">'
 7820: 				 . "Successful local authentication </font>");
 7821: 			$keymode = "local"
 7822: 		    } else {
 7823: 			Debug("Failed to get local key");
 7824: 			$clientok = 0;
 7825: 			shutdown($client, 3);
 7826: 			close $client;
 7827: 		    }
 7828: 		} elsif ($inittype eq "ssl") {
 7829: 		    my $key = SSLConnection($client,$clientname);
 7830: 		    if ($key) {
 7831: 			$clientok = 1;
 7832: 			my $cipherkey = pack("H32", $key);
 7833: 			$cipher       = new IDEA($cipherkey);
 7834: 			&logthis('<font color="green">'
 7835: 				 ."Successfull ssl authentication with $clientname </font>");
 7836: 			$keymode = "ssl";
 7837: 	     
 7838: 		    } else {
 7839: 			$clientok = 0;
 7840: 			close $client;
 7841: 		    }
 7842: 	   
 7843: 		} else {
 7844: 		    my $ok = InsecureConnection($client);
 7845: 		    if($ok) {
 7846: 			$clientok = 1;
 7847: 			&logthis('<font color="green">'
 7848: 				 ."Successful insecure authentication with $clientname </font>");
 7849: 			print $client "ok\n";
 7850: 			$keymode = "insecure";
 7851: 		    } else {
 7852: 			&logthis('<font color="yellow">'
 7853: 				  ."Attempted insecure connection disallowed </font>");
 7854: 			close $client;
 7855: 			$clientok = 0;
 7856: 		    }
 7857: 		}
 7858: 	    } else {
 7859: 		&logthis(
 7860: 			 "<font color='blue'>WARNING: "
 7861: 			 ."$clientip failed to initialize: >$remotereq< </font>");
 7862: 		&status('No init '.$clientip);
 7863: 	    }
 7864: 	} else {
 7865: 	    &logthis(
 7866: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
 7867: 	    &status('Hung up on '.$clientip);
 7868: 	}
 7869:  
 7870: 	if ($clientok) {
 7871: # ---------------- New known client connecting, could mean machine online again
 7872: 	    if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip 
 7873: 		&& $clientip ne '127.0.0.1') {
 7874: 		&Apache::lonnet::reconlonc($clientname);
 7875: 	    }
 7876: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
 7877: 	    &status('Will listen to '.$clientname);
 7878: # ------------------------------------------------------------ Process requests
 7879: 	    my $keep_going = 1;
 7880: 	    my $user_input;
 7881: 
 7882: 	    while(($user_input = get_request) && $keep_going) {
 7883: 		alarm(120);
 7884: 		Debug("Main: Got $user_input\n");
 7885: 		$keep_going = &process_request($user_input);
 7886: 		alarm(0);
 7887: 		&status('Listening to '.$clientname." ($keymode)");	   
 7888: 	    }
 7889: 
 7890: # --------------------------------------------- client unknown or fishy, refuse
 7891: 	}  else {
 7892: 	    print $client "refused\n";
 7893: 	    $client->close();
 7894: 	    &logthis("<font color='blue'>WARNING: "
 7895: 		     ."Rejected client $clientip, closing connection</font>");
 7896: 	}
 7897:     }
 7898:     
 7899: # =============================================================================
 7900:     
 7901:     &logthis("<font color='red'>CRITICAL: "
 7902: 	     ."Disconnect from $clientip ($clientname)</font>");    
 7903:     
 7904:     
 7905:     # this exit is VERY important, otherwise the child will become
 7906:     # a producer of more and more children, forking yourself into
 7907:     # process death.
 7908:     exit;
 7909:     
 7910: }
 7911: 
 7912: #
 7913: #  Used to determine if a particular client is from the same domain
 7914: #  as the current server, or from the same internet domain, and
 7915: #  also if the client can host sessions for the domain's users.
 7916: #  A hash is populated with keys set to commands sent by the client
 7917: #  which may not be executed for this domain.
 7918: #
 7919: #  Optional input -- the client to check for domain and internet domain.
 7920: #  If not specified, defaults to the package variable: $clientname
 7921: #
 7922: #  If called in array context will not set package variables, but will
 7923: #  instead return an array of two values - (a) true if client is in the
 7924: #  same domain as the server, and (b) true if client is in the same 
 7925: #  internet domain.
 7926: #
 7927: #  If called in scalar context, sets package variables for current client:
 7928: #
 7929: #  $clienthomedom    - LonCAPA domain of homeID for client.
 7930: #  $clientsamedom    - LonCAPA domain same for this host and client.
 7931: #  $clientintdom     - LonCAPA "internet domain" for client.
 7932: #  $clientsameinst   - LonCAPA "internet domain" same for this host & client.
 7933: #  $clientremoteok   - If current domain permits hosting on this client: 1
 7934: #  %clientprohibited - Commands prohibited for domain's users for this client.
 7935: #
 7936: #  if the host and client have the same "internet domain", then the value
 7937: #  of $clientremoteok is not used, and no commands are prohibited.
 7938: #
 7939: #  returns 1 to indicate package variables have been set for current client.
 7940: #
 7941: 
 7942: sub set_client_info {
 7943:     my ($lonhost) = @_;
 7944:     $lonhost ||= $clientname;
 7945:     my $clienthost = &Apache::lonnet::hostname($lonhost);
 7946:     my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
 7947:     my $homedom = &Apache::lonnet::host_domain($clientserverhomeID);
 7948:     my $samedom = 0;
 7949:     if ($perlvar{'lonDefDomain'} eq $homedom) {
 7950:         $samedom = 1;
 7951:     }
 7952:     my $intdom = &Apache::lonnet::internet_dom($clientserverhomeID);
 7953:     my $sameinst = 0;
 7954:     if ($intdom ne '') {
 7955:         my $internet_names = &Apache::lonnet::get_internet_names($currenthostid);
 7956:         if (ref($internet_names) eq 'ARRAY') {
 7957:             if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 7958:                 $sameinst = 1;
 7959:             }
 7960:         }
 7961:     }
 7962:     if (wantarray) {
 7963:         return ($samedom,$sameinst);
 7964:     } else {
 7965:         $clienthomedom = $homedom;
 7966:         $clientsamedom = $samedom;
 7967:         $clientintdom = $intdom;
 7968:         $clientsameinst = $sameinst;
 7969:         if ($clientsameinst) {
 7970:             undef($clientremoteok);
 7971:             undef(%clientprohibited);
 7972:         } else {
 7973:             $clientremoteok = &get_remote_hostable($currentdomainid);
 7974:             %clientprohibited = &get_prohibited($currentdomainid);
 7975:         }
 7976:         return 1;
 7977:     }
 7978: }
 7979: 
 7980: #
 7981: #   Determine if a user is an author for the indicated domain.
 7982: #
 7983: # Parameters:
 7984: #    domain          - domain to check in .
 7985: #    user            - Name of user to check.
 7986: #
 7987: # Return:
 7988: #     1             - User is an author for domain.
 7989: #     0             - User is not an author for domain.
 7990: sub is_author {
 7991:     my ($domain, $user) = @_;
 7992: 
 7993:     &Debug("is_author: $user @ $domain");
 7994: 
 7995:     my $hashref = &tie_user_hash($domain, $user, "roles",
 7996: 				 &GDBM_READER());
 7997: 
 7998:     #  Author role should show up as a key /domain/_au
 7999: 
 8000:     my $value;
 8001:     if ($hashref) {
 8002: 
 8003: 	my $key    = "/$domain/_au";
 8004: 	if (defined($hashref)) {
 8005: 	    $value = $hashref->{$key};
 8006: 	    if(!untie_user_hash($hashref)) {
 8007: 		return 'error: ' .  ($!+0)." untie (GDBM) Failed";
 8008: 	    }
 8009: 	}
 8010: 	
 8011: 	if(defined($value)) {
 8012: 	    &Debug("$user @ $domain is an author");
 8013: 	}
 8014:     } else {
 8015: 	return 'error: '.($!+0)." tie (GDBM) Failed";
 8016:     }
 8017: 
 8018:     return defined($value);
 8019: }
 8020: #
 8021: #   Checks to see if the input roleput request was to set
 8022: # an author role.  If so, creates construction space 
 8023: # Parameters:
 8024: #    request   - The request sent to the rolesput subchunk.
 8025: #                We're looking for  /domain/_au
 8026: #    domain    - The domain in which the user is having roles doctored.
 8027: #    user      - Name of the user for which the role is being put.
 8028: #    authtype  - The authentication type associated with the user.
 8029: #
 8030: sub manage_permissions {
 8031:     my ($request, $domain, $user, $authtype) = @_;
 8032:     # See if the request is of the form /$domain/_au
 8033:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
 8034:         my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
 8035:         unless (-e $path) {        
 8036:            mkdir($path);
 8037:         }
 8038:         unless (-e $path.'/'.$user) {
 8039:            mkdir($path.'/'.$user);
 8040:         }
 8041:     }
 8042: }
 8043: 
 8044: 
 8045: #
 8046: #  Return the full path of a user password file, whether it exists or not.
 8047: # Parameters:
 8048: #   domain     - Domain in which the password file lives.
 8049: #   user       - name of the user.
 8050: # Returns:
 8051: #    Full passwd path:
 8052: #
 8053: sub password_path {
 8054:     my ($domain, $user) = @_;
 8055:     return &propath($domain, $user).'/passwd';
 8056: }
 8057: 
 8058: #   Password Filename
 8059: #   Returns the path to a passwd file given domain and user... only if
 8060: #  it exists.
 8061: # Parameters:
 8062: #   domain    - Domain in which to search.
 8063: #   user      - username.
 8064: # Returns:
 8065: #   - If the password file exists returns its path.
 8066: #   - If the password file does not exist, returns undefined.
 8067: #
 8068: sub password_filename {
 8069:     my ($domain, $user) = @_;
 8070: 
 8071:     Debug ("PasswordFilename called: dom = $domain user = $user");
 8072: 
 8073:     my $path  = &password_path($domain, $user);
 8074:     Debug("PasswordFilename got path: $path");
 8075:     if(-e $path) {
 8076: 	return $path;
 8077:     } else {
 8078: 	return undef;
 8079:     }
 8080: }
 8081: 
 8082: #
 8083: #   Rewrite the contents of the user's passwd file.
 8084: #  Parameters:
 8085: #    domain    - domain of the user.
 8086: #    name      - User's name.
 8087: #    contents  - New contents of the file.
 8088: #    saveold   - (optional). If true save old file in a passwd.bak file.
 8089: # Returns:
 8090: #   0    - Failed.
 8091: #   1    - Success.
 8092: #
 8093: sub rewrite_password_file {
 8094:     my ($domain, $user, $contents, $saveold) = @_;
 8095: 
 8096:     my $file = &password_filename($domain, $user);
 8097:     if (defined $file) {
 8098:         if ($saveold) {
 8099:             my $bakfile = $file.'.bak';
 8100:             if (CopyFile($file,$bakfile)) {
 8101:                 chmod(0400,$bakfile);
 8102:                 &logthis("Old password saved in passwd.bak for internally authenticated user: $user:$domain");
 8103:             } else {
 8104:                 &logthis("Failed to save old password in passwd.bak for internally authenticated user: $user:$domain");
 8105:             }
 8106:         }
 8107: 	my $pf = IO::File->new(">$file");
 8108: 	if($pf) {
 8109: 	    print $pf "$contents\n";
 8110: 	    return 1;
 8111: 	} else {
 8112: 	    return 0;
 8113: 	}
 8114:     } else {
 8115: 	return 0;
 8116:     }
 8117: 
 8118: }
 8119: 
 8120: #
 8121: #   get_auth_type - Determines the authorization type of a user in a domain.
 8122: 
 8123: #     Returns the authorization type or nouser if there is no such user.
 8124: #
 8125: sub get_auth_type {
 8126:     my ($domain, $user)  = @_;
 8127: 
 8128:     Debug("get_auth_type( $domain, $user ) \n");
 8129:     my $proname    = &propath($domain, $user); 
 8130:     my $passwdfile = "$proname/passwd";
 8131:     if( -e $passwdfile ) {
 8132: 	my $pf = IO::File->new($passwdfile);
 8133: 	my $realpassword = <$pf>;
 8134: 	chomp($realpassword);
 8135: 	Debug("Password info = $realpassword\n");
 8136: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
 8137: 	Debug("Authtype = $authtype, content = $contentpwd\n");
 8138: 	return "$authtype:$contentpwd";     
 8139:     } else {
 8140: 	Debug("Returning nouser");
 8141: 	return "nouser";
 8142:     }
 8143: }
 8144: 
 8145: #
 8146: #  Validate a user given their domain, name and password.  This utility
 8147: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
 8148: #  to validate the login credentials of a user.
 8149: # Parameters:
 8150: #    $domain    - The domain being logged into (this is required due to
 8151: #                 the capability for multihomed systems.
 8152: #    $user      - The name of the user being validated.
 8153: #    $password  - The user's propoposed password.
 8154: #
 8155: # Returns:
 8156: #     1        - The domain,user,pasword triplet corresponds to a valid
 8157: #                user.
 8158: #     0        - The domain,user,password triplet is not a valid user.
 8159: #
 8160: sub validate_user {
 8161:     my ($domain, $user, $password, $checkdefauth) = @_;
 8162: 
 8163:     # Why negative ~pi you may well ask?  Well this function is about
 8164:     # authentication, and therefore very important to get right.
 8165:     # I've initialized the flag that determines whether or not I've 
 8166:     # validated correctly to a value it's not supposed to get.
 8167:     # At the end of this function. I'll ensure that it's not still that
 8168:     # value so we don't just wind up returning some accidental value
 8169:     # as a result of executing an unforseen code path that
 8170:     # did not set $validated.  At the end of valid execution paths,
 8171:     # validated shoule be 1 for success or 0 for failuer.
 8172: 
 8173:     my $validated = -3.14159;
 8174: 
 8175:     #  How we authenticate is determined by the type of authentication
 8176:     #  the user has been assigned.  If the authentication type is
 8177:     #  "nouser", the user does not exist so we will return 0.
 8178: 
 8179:     my $contents = &get_auth_type($domain, $user);
 8180:     my ($howpwd, $contentpwd) = split(/:/, $contents);
 8181: 
 8182:     my $null = pack("C",0);	# Used by kerberos auth types.
 8183: 
 8184:     if ($howpwd eq 'nouser') {
 8185:         if ($checkdefauth) {
 8186:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 8187:             if ($domdefaults{'auth_def'} eq 'localauth') {
 8188:                 $howpwd = $domdefaults{'auth_def'};
 8189:                 $contentpwd = $domdefaults{'auth_arg_def'};
 8190:             } elsif ((($domdefaults{'auth_def'} eq 'krb4') || 
 8191:                       ($domdefaults{'auth_def'} eq 'krb5')) &&
 8192:                      ($domdefaults{'auth_arg_def'} ne '')) {
 8193:                 $howpwd = $domdefaults{'auth_def'};
 8194:                 $contentpwd = $domdefaults{'auth_arg_def'}; 
 8195:             }
 8196:         }
 8197:     }
 8198:     if ($howpwd ne 'nouser') {
 8199: 	if($howpwd eq "internal") { # Encrypted is in local password file.
 8200:             if (length($contentpwd) == 13) {
 8201:                 $validated = (crypt($password,$contentpwd) eq $contentpwd);
 8202:                 if ($validated) {
 8203:                     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 8204:                     if ($domdefaults{'intauth_switch'}) {
 8205:                         my $ncpass = &hash_passwd($domain,$password);
 8206:                         my $saveold;
 8207:                         if ($domdefaults{'intauth_switch'} == 2) {
 8208:                             $saveold = 1;
 8209:                         }
 8210:                         if (&rewrite_password_file($domain,$user,"$howpwd:$ncpass",$saveold)) {
 8211:                             &update_passwd_history($user,$domain,$howpwd,'conversion');
 8212:                             &logthis("Validated password hashed with bcrypt for $user:$domain");
 8213:                         }
 8214:                     }
 8215:                 }
 8216:             } else {
 8217:                 $validated = &check_internal_passwd($password,$contentpwd,$domain,$user);
 8218:             }
 8219: 	}
 8220: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
 8221: 	    $contentpwd = (getpwnam($user))[1];
 8222: 	    if($contentpwd) {
 8223: 		if($contentpwd eq 'x') { # Shadow password file...
 8224: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
 8225: 		    open PWAUTH,  "|$pwauth_path" or
 8226: 			die "Cannot invoke authentication";
 8227: 		    print PWAUTH "$user\n$password\n";
 8228: 		    close PWAUTH;
 8229: 		    $validated = ! $?;
 8230: 
 8231: 		} else { 	         # Passwords in /etc/passwd. 
 8232: 		    $validated = (crypt($password,
 8233: 					$contentpwd) eq $contentpwd);
 8234: 		}
 8235: 	    } else {
 8236: 		$validated = 0;
 8237: 	    }
 8238: 	} elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
 8239:             my $checkwithkrb5 = 0;
 8240:             if ($dist =~/^fedora(\d+)$/) {
 8241:                 if ($1 > 11) {
 8242:                     $checkwithkrb5 = 1;
 8243:                 }
 8244:             } elsif ($dist =~ /^suse([\d.]+)$/) {
 8245:                 if ($1 > 11.1) {
 8246:                     $checkwithkrb5 = 1; 
 8247:                 }
 8248:             }
 8249:             if ($checkwithkrb5) {
 8250:                 $validated = &krb5_authen($password,$null,$user,$contentpwd);
 8251:             } else {
 8252:                 $validated = &krb4_authen($password,$null,$user,$contentpwd);
 8253:             }
 8254: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
 8255:             $validated = &krb5_authen($password,$null,$user,$contentpwd);
 8256: 	} elsif ($howpwd eq "localauth") { 
 8257: 	    #  Authenticate via installation specific authentcation method:
 8258: 	    $validated = &localauth::localauth($user, 
 8259: 					       $password, 
 8260: 					       $contentpwd,
 8261: 					       $domain);
 8262: 	    if ($validated < 0) {
 8263: 		&logthis("localauth for $contentpwd $user:$domain returned a $validated");
 8264: 		$validated = 0;
 8265: 	    }
 8266: 	} else {			# Unrecognized auth is also bad.
 8267: 	    $validated = 0;
 8268: 	}
 8269:     } else {
 8270: 	$validated = 0;
 8271:     }
 8272:     #
 8273:     #  $validated has the correct stat of the authentication:
 8274:     #
 8275: 
 8276:     unless ($validated != -3.14159) {
 8277: 	#  I >really really< want to know if this happens.
 8278: 	#  since it indicates that user authentication is badly
 8279: 	#  broken in some code path.
 8280:         #
 8281: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
 8282:     }
 8283:     return $validated;
 8284: }
 8285: 
 8286: sub check_internal_passwd {
 8287:     my ($plainpass,$stored,$domain,$user) = @_;
 8288:     my (undef,$method,@rest) = split(/!/,$stored);
 8289:     if ($method eq 'bcrypt') {
 8290:         my $result = &hash_passwd($domain,$plainpass,@rest);
 8291:         if ($result ne $stored) {
 8292:             return 0;
 8293:         }
 8294:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 8295:         if ($domdefaults{'intauth_check'}) {
 8296:             # Upgrade to a larger number of rounds if necessary
 8297:             my $defaultcost = $domdefaults{'intauth_cost'};
 8298:             if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
 8299:                 $defaultcost = 10;
 8300:             }
 8301:             if (int($rest[0])<int($defaultcost)) {
 8302:                 if ($domdefaults{'intauth_check'} == 1) { 
 8303:                     my $ncpass = &hash_passwd($domain,$plainpass);
 8304:                     if (&rewrite_password_file($domain,$user,"internal:$ncpass")) {
 8305:                         &update_passwd_history($user,$domain,'internal','update cost');
 8306:                         &logthis("Validated password hashed with bcrypt for $user:$domain");
 8307:                     }
 8308:                     return 1;
 8309:                 } elsif ($domdefaults{'intauth_check'} == 2) {
 8310:                     return 0;
 8311:                 }
 8312:             }
 8313:         } else {
 8314:             return 1;
 8315:         }
 8316:     }
 8317:     return 0;
 8318: }
 8319: 
 8320: sub get_last_authchg {
 8321:     my ($domain,$user) = @_;
 8322:     my $lastmod;
 8323:     my $logname = &propath($domain,$user).'/passwd.log';
 8324:     if (-e "$logname") {
 8325:         $lastmod = (stat("$logname"))[9];
 8326:     }
 8327:     return $lastmod;
 8328: }
 8329: 
 8330: sub krb4_authen {
 8331:     my ($password,$null,$user,$contentpwd) = @_;
 8332:     my $validated = 0;
 8333:     if (!($password =~ /$null/) ) {  # Null password not allowed.
 8334:         eval {
 8335:             require Authen::Krb4;
 8336:         };
 8337:         if (!$@) {
 8338:             my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
 8339:                                                        "",
 8340:                                                        $contentpwd,,
 8341:                                                        'krbtgt',
 8342:                                                        $contentpwd,
 8343:                                                        1,
 8344:                                                        $password);
 8345:             if(!$k4error) {
 8346:                 $validated = 1;
 8347:             } else {
 8348:                 $validated = 0;
 8349:                 &logthis('krb4: '.$user.', '.$contentpwd.', '.
 8350:                           &Authen::Krb4::get_err_txt($Authen::Krb4::error));
 8351:             }
 8352:         } else {
 8353:             $validated = krb5_authen($password,$null,$user,$contentpwd);
 8354:         }
 8355:     }
 8356:     return $validated;
 8357: }
 8358: 
 8359: sub krb5_authen {
 8360:     my ($password,$null,$user,$contentpwd) = @_;
 8361:     my $validated = 0;
 8362:     if(!($password =~ /$null/)) { # Null password not allowed.
 8363:         my $krbclient = &Authen::Krb5::parse_name($user.'@'
 8364:                                                   .$contentpwd);
 8365:         my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
 8366:         my $krbserver  = &Authen::Krb5::parse_name($krbservice);
 8367:         my $credentials= &Authen::Krb5::cc_default();
 8368:         $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
 8369:                                                             .$contentpwd));
 8370:         my $krbreturn;
 8371:         if (exists(&Authen::Krb5::get_init_creds_password)) {
 8372:             $krbreturn =
 8373:                 &Authen::Krb5::get_init_creds_password($krbclient,$password,
 8374:                                                           $krbservice);
 8375:             $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
 8376:         } else {
 8377:             $krbreturn  =
 8378:                 &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
 8379:                                                          $password,$credentials);
 8380:             $validated = ($krbreturn == 1);
 8381:         }
 8382:         if (!$validated) {
 8383:             &logthis('krb5: '.$user.', '.$contentpwd.', '.
 8384:                      &Authen::Krb5::error());
 8385:         }
 8386:     }
 8387:     return $validated;
 8388: }
 8389: 
 8390: sub addline {
 8391:     my ($fname,$hostid,$ip,$newline)=@_;
 8392:     my $contents;
 8393:     my $found=0;
 8394:     my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
 8395:     my $sh;
 8396:     if ($sh=IO::File->new("$fname.subscription")) {
 8397: 	while (my $subline=<$sh>) {
 8398: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
 8399: 	}
 8400: 	$sh->close();
 8401:     }
 8402:     $sh=IO::File->new(">$fname.subscription");
 8403:     if ($contents) { print $sh $contents; }
 8404:     if ($newline) { print $sh $newline; }
 8405:     $sh->close();
 8406:     return $found;
 8407: }
 8408: 
 8409: sub get_chat {
 8410:     my ($cdom,$cname,$udom,$uname,$group)=@_;
 8411: 
 8412:     my @entries=();
 8413:     my $namespace = 'nohist_chatroom';
 8414:     my $namespace_inroom = 'nohist_inchatroom';
 8415:     if ($group ne '') {
 8416:         $namespace .= '_'.$group;
 8417:         $namespace_inroom .= '_'.$group;
 8418:     }
 8419:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
 8420: 				 &GDBM_READER());
 8421:     if ($hashref) {
 8422: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
 8423: 	&untie_user_hash($hashref);
 8424:     }
 8425:     my @participants=();
 8426:     my $cutoff=time-60;
 8427:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
 8428: 			      &GDBM_WRCREAT());
 8429:     if ($hashref) {
 8430:         $hashref->{$uname.':'.$udom}=time;
 8431:         foreach my $user (sort(keys(%$hashref))) {
 8432: 	    if ($hashref->{$user}>$cutoff) {
 8433: 		push(@participants, 'active_participant:'.$user);
 8434:             }
 8435:         }
 8436:         &untie_user_hash($hashref);
 8437:     }
 8438:     return (@participants,@entries);
 8439: }
 8440: 
 8441: sub chat_add {
 8442:     my ($cdom,$cname,$newchat,$group)=@_;
 8443:     my @entries=();
 8444:     my $time=time;
 8445:     my $namespace = 'nohist_chatroom';
 8446:     my $logfile = 'chatroom.log';
 8447:     if ($group ne '') {
 8448:         $namespace .= '_'.$group;
 8449:         $logfile = 'chatroom_'.$group.'.log';
 8450:     }
 8451:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
 8452: 				 &GDBM_WRCREAT());
 8453:     if ($hashref) {
 8454: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
 8455: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
 8456: 	my ($thentime,$idnum)=split(/\_/,$lastid);
 8457: 	my $newid=$time.'_000000';
 8458: 	if ($thentime==$time) {
 8459: 	    $idnum=~s/^0+//;
 8460: 	    $idnum++;
 8461: 	    $idnum=substr('000000'.$idnum,-6,6);
 8462: 	    $newid=$time.'_'.$idnum;
 8463: 	}
 8464: 	$hashref->{$newid}=$newchat;
 8465: 	my $expired=$time-3600;
 8466: 	foreach my $comment (keys(%$hashref)) {
 8467: 	    my ($thistime) = ($comment=~/(\d+)\_/);
 8468: 	    if ($thistime<$expired) {
 8469: 		delete $hashref->{$comment};
 8470: 	    }
 8471: 	}
 8472: 	{
 8473: 	    my $proname=&propath($cdom,$cname);
 8474: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
 8475: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
 8476: 	    }
 8477: 	    close(CHATLOG);
 8478: 	}
 8479: 	&untie_user_hash($hashref);
 8480:     }
 8481: }
 8482: 
 8483: sub unsub {
 8484:     my ($fname,$clientip)=@_;
 8485:     my $result;
 8486:     my $unsubs = 0;		# Number of successful unsubscribes:
 8487: 
 8488: 
 8489:     # An old way subscriptions were handled was to have a 
 8490:     # subscription marker file:
 8491: 
 8492:     Debug("Attempting unlink of $fname.$clientname");
 8493:     if (unlink("$fname.$clientname")) {
 8494: 	$unsubs++;		# Successful unsub via marker file.
 8495:     } 
 8496: 
 8497:     # The more modern way to do it is to have a subscription list
 8498:     # file:
 8499: 
 8500:     if (-e "$fname.subscription") {
 8501: 	my $found=&addline($fname,$clientname,$clientip,'');
 8502: 	if ($found) { 
 8503: 	    $unsubs++;
 8504: 	}
 8505:     } 
 8506: 
 8507:     #  If either or both of these mechanisms succeeded in unsubscribing a 
 8508:     #  resource we can return ok:
 8509: 
 8510:     if($unsubs) {
 8511: 	$result = "ok\n";
 8512:     } else {
 8513: 	$result = "not_subscribed\n";
 8514:     }
 8515: 
 8516:     return $result;
 8517: }
 8518: 
 8519: sub currentversion {
 8520:     my $fname=shift;
 8521:     my $version=-1;
 8522:     my $ulsdir='';
 8523:     if ($fname=~/^(.+)\/[^\/]+$/) {
 8524:        $ulsdir=$1;
 8525:     }
 8526:     my ($fnamere1,$fnamere2);
 8527:     # remove version if already specified
 8528:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
 8529:     # get the bits that go before and after the version number
 8530:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
 8531: 	$fnamere1=$1;
 8532: 	$fnamere2='.'.$2;
 8533:     }
 8534:     if (-e $fname) { $version=1; }
 8535:     if (-e $ulsdir) {
 8536: 	if(-d $ulsdir) {
 8537: 	    if (opendir(LSDIR,$ulsdir)) {
 8538: 		my $ulsfn;
 8539: 		while ($ulsfn=readdir(LSDIR)) {
 8540: # see if this is a regular file (ignore links produced earlier)
 8541: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
 8542: 		    unless (-l $thisfile) {
 8543: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
 8544: 			    if ($1>$version) { $version=$1; }
 8545: 			}
 8546: 		    }
 8547: 		}
 8548: 		closedir(LSDIR);
 8549: 		$version++;
 8550: 	    }
 8551: 	}
 8552:     }
 8553:     return $version;
 8554: }
 8555: 
 8556: sub thisversion {
 8557:     my $fname=shift;
 8558:     my $version=-1;
 8559:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
 8560: 	$version=$1;
 8561:     }
 8562:     return $version;
 8563: }
 8564: 
 8565: sub subscribe {
 8566:     my ($userinput,$clientip)=@_;
 8567:     my $result;
 8568:     my ($cmd,$fname)=split(/:/,$userinput,2);
 8569:     my $ownership=&ishome($fname);
 8570:     if ($ownership eq 'owner') {
 8571: # explitly asking for the current version?
 8572:         unless (-e $fname) {
 8573:             my $currentversion=&currentversion($fname);
 8574: 	    if (&thisversion($fname)==$currentversion) {
 8575:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
 8576: 		    my $root=$1;
 8577:                     my $extension=$2;
 8578:                     symlink($root.'.'.$extension,
 8579:                             $root.'.'.$currentversion.'.'.$extension);
 8580:                     unless ($extension=~/\.meta$/) {
 8581:                        symlink($root.'.'.$extension.'.meta',
 8582:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
 8583: 		    }
 8584:                 }
 8585:             }
 8586:         }
 8587: 	if (-e $fname) {
 8588: 	    if (-d $fname) {
 8589: 		$result="directory\n";
 8590: 	    } else {
 8591: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
 8592: 		my $now=time;
 8593: 		my $found=&addline($fname,$clientname,$clientip,
 8594: 				   "$clientname:$clientip:$now\n");
 8595: 		if ($found) { $result="$fname\n"; }
 8596: 		# if they were subscribed to only meta data, delete that
 8597:                 # subscription, when you subscribe to a file you also get
 8598:                 # the metadata
 8599: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
 8600: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
 8601:                 my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
 8602:                 $protocol = 'http' if ($protocol ne 'https');
 8603: 		$fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
 8604: 		$result="$fname\n";
 8605: 	    }
 8606: 	} else {
 8607: 	    $result="not_found\n";
 8608: 	}
 8609:     } else {
 8610: 	$result="rejected\n";
 8611:     }
 8612:     return $result;
 8613: }
 8614: #  Change the passwd of a unix user.  The caller must have
 8615: #  first verified that the user is a loncapa user.
 8616: #
 8617: # Parameters:
 8618: #    user      - Unix user name to change.
 8619: #    pass      - New password for the user.
 8620: # Returns:
 8621: #    ok    - if success
 8622: #    other - Some meaningfule error message string.
 8623: # NOTE:
 8624: #    invokes a setuid script to change the passwd.
 8625: sub change_unix_password {
 8626:     my ($user, $pass) = @_;
 8627: 
 8628:     &Debug("change_unix_password");
 8629:     my $execdir=$perlvar{'lonDaemons'};
 8630:     &Debug("Opening lcpasswd pipeline");
 8631:     my $pf = IO::File->new("|$execdir/lcpasswd > "
 8632: 			   ."$perlvar{'lonDaemons'}"
 8633: 			   ."/logs/lcpasswd.log");
 8634:     print $pf "$user\n$pass\n$pass\n";
 8635:     close $pf;
 8636:     my $err = $?;
 8637:     return ($err < @passwderrors) ? $passwderrors[$err] : 
 8638: 	"pwchange_falure - unknown error";
 8639: 
 8640:     
 8641: }
 8642: 
 8643: 
 8644: sub make_passwd_file {
 8645:     my ($uname,$udom,$umode,$npass,$passfilename,$action)=@_;
 8646:     my $result="ok";
 8647:     if ($umode eq 'krb4' or $umode eq 'krb5') {
 8648: 	{
 8649: 	    my $pf = IO::File->new(">$passfilename");
 8650: 	    if ($pf) {
 8651: 		print $pf "$umode:$npass\n";
 8652:                 &update_passwd_history($uname,$udom,$umode,$action);
 8653: 	    } else {
 8654: 		$result = "pass_file_failed_error";
 8655: 	    }
 8656: 	}
 8657:     } elsif ($umode eq 'internal') {
 8658:         my $ncpass = &hash_passwd($udom,$npass);
 8659: 	{
 8660: 	    &Debug("Creating internal auth");
 8661: 	    my $pf = IO::File->new(">$passfilename");
 8662: 	    if($pf) {
 8663: 		print $pf "internal:$ncpass\n";
 8664:                 &update_passwd_history($uname,$udom,$umode,$action); 
 8665: 	    } else {
 8666: 		$result = "pass_file_failed_error";
 8667: 	    }
 8668: 	}
 8669:     } elsif ($umode eq 'localauth') {
 8670: 	{
 8671: 	    my $pf = IO::File->new(">$passfilename");
 8672: 	    if($pf) {
 8673: 		print $pf "localauth:$npass\n";
 8674:                 &update_passwd_history($uname,$udom,$umode,$action);
 8675: 	    } else {
 8676: 		$result = "pass_file_failed_error";
 8677: 	    }
 8678: 	}
 8679:     } elsif ($umode eq 'unix') {
 8680: 	&logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
 8681: 	$result="no_new_unix_accounts";
 8682:     } elsif ($umode eq 'none') {
 8683: 	{
 8684: 	    my $pf = IO::File->new("> $passfilename");
 8685: 	    if($pf) {
 8686: 		print $pf "none:\n";
 8687: 	    } else {
 8688: 		$result = "pass_file_failed_error";
 8689: 	    }
 8690: 	}
 8691:     } elsif ($umode eq 'lti') {
 8692:         my $pf = IO::File->new(">$passfilename");
 8693:         if($pf) {
 8694:             print $pf "lti:\n";
 8695:             &update_passwd_history($uname,$udom,$umode,$action);
 8696:         } else {
 8697:             $result = "pass_file_failed_error";
 8698:         }
 8699:     } else {
 8700: 	$result="auth_mode_error";
 8701:     }
 8702:     return $result;
 8703: }
 8704: 
 8705: sub convert_photo {
 8706:     my ($start,$dest)=@_;
 8707:     system("convert $start $dest");
 8708: }
 8709: 
 8710: sub sethost {
 8711:     my ($remotereq) = @_;
 8712:     my (undef,$hostid)=split(/:/,$remotereq);
 8713:     # ignore sethost if we are already correct
 8714:     if ($hostid eq $currenthostid) {
 8715: 	return 'ok';
 8716:     }
 8717: 
 8718:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
 8719:     if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'}) 
 8720: 	eq &Apache::lonnet::get_host_ip($hostid)) {
 8721: 	$currenthostid  =$hostid;
 8722: 	$currentdomainid=&Apache::lonnet::host_domain($hostid);
 8723:         &set_client_info();
 8724: #	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
 8725:     } else {
 8726: 	&logthis("Requested host id $hostid not an alias of ".
 8727: 		 $perlvar{'lonHostID'}." refusing connection");
 8728: 	return 'unable_to_set';
 8729:     }
 8730:     return 'ok';
 8731: }
 8732: 
 8733: sub version {
 8734:     my ($userinput)=@_;
 8735:     $remoteVERSION=(split(/:/,$userinput))[1];
 8736:     return "version:$VERSION";
 8737: }
 8738: 
 8739: sub get_usersession_config {
 8740:     my ($dom,$name) = @_;
 8741:     my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
 8742:     if (defined($cached)) {
 8743:         return $usersessionconf;
 8744:     } else {
 8745:         my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
 8746:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
 8747:         return $domconfig{'usersessions'};
 8748:     }
 8749:     return;
 8750: }
 8751: 
 8752: sub get_usersearch_config {
 8753:     my ($dom,$name) = @_;
 8754:     my ($usersearchconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
 8755:     if (defined($cached)) {
 8756:         return $usersearchconf;
 8757:     } else {
 8758:         my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$dom);
 8759:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'directorysrch'},600);
 8760:         return $domconfig{'directorysrch'};
 8761:     }
 8762:     return;
 8763: }
 8764: 
 8765: sub get_prohibited {
 8766:     my ($dom) = @_;
 8767:     my $name = 'trust';
 8768:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
 8769:     unless (defined($cached)) {
 8770:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$dom);
 8771:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'trust'},3600);
 8772:         $trustconfig = $domconfig{'trust'};
 8773:     }
 8774:     my %prohibited;
 8775:     if (ref($trustconfig)) {
 8776:         foreach my $prefix (keys(%{$trustconfig})) {
 8777:             if (ref($trustconfig->{$prefix}) eq 'HASH') {
 8778:                 my $reject;
 8779:                 if (ref($trustconfig->{$prefix}->{'exc'}) eq 'ARRAY') {
 8780:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'exc'}})) {
 8781:                         $reject = 1;
 8782:                     }
 8783:                 }
 8784:                 if (ref($trustconfig->{$prefix}->{'inc'}) eq 'ARRAY') {
 8785:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'inc'}})) {
 8786:                         $reject = 0;
 8787:                     } else {
 8788:                         $reject = 1;
 8789:                     }
 8790:                 }
 8791:                 if ($reject) {
 8792:                     $prohibited{$prefix} = 1;
 8793:                 }
 8794:             }
 8795:         }
 8796:     }
 8797:     return %prohibited;
 8798: }
 8799: 
 8800: sub get_remote_hostable {
 8801:     my ($dom) = @_;
 8802:     my $result;
 8803:     if ($clientintdom) {
 8804:         $result = 1;
 8805:         my $remsessconf = &get_usersession_config($dom,'remotesession');
 8806:         if (ref($remsessconf) eq 'HASH') {
 8807:             if (ref($remsessconf->{'remote'}) eq 'HASH') {
 8808:                 if (ref($remsessconf->{'remote'}->{'excludedomain'}) eq 'ARRAY') {
 8809:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'excludedomain'}})) {
 8810:                         $result = 0;
 8811:                     }
 8812:                 }
 8813:                 if (ref($remsessconf->{'remote'}->{'includedomain'}) eq 'ARRAY') {
 8814:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'includedomain'}})) {
 8815:                         $result = 1;
 8816:                     } else {
 8817:                         $result = 0;
 8818:                     }
 8819:                 }
 8820:             }
 8821:         }
 8822:     }
 8823:     return $result;
 8824: }
 8825: 
 8826: sub distro_and_arch {
 8827:     return $dist.':'.$arch;
 8828: }
 8829: 
 8830: # ----------------------------------- POD (plain old documentation, CPAN style)
 8831: 
 8832: =head1 NAME
 8833: 
 8834: lond - "LON Daemon" Server (port "LOND" 5663)
 8835: 
 8836: =head1 SYNOPSIS
 8837: 
 8838: Usage: B<lond>
 8839: 
 8840: Should only be run as user=www.  This is a command-line script which
 8841: is invoked by B<loncron>.  There is no expectation that a typical user
 8842: will manually start B<lond> from the command-line.  (In other words,
 8843: DO NOT START B<lond> YOURSELF.)
 8844: 
 8845: =head1 DESCRIPTION
 8846: 
 8847: There are two characteristics associated with the running of B<lond>,
 8848: PROCESS MANAGEMENT (starting, stopping, handling child processes)
 8849: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
 8850: subscriptions, etc).  These are described in two large
 8851: sections below.
 8852: 
 8853: B<PROCESS MANAGEMENT>
 8854: 
 8855: Preforker - server who forks first. Runs as a daemon. HUPs.
 8856: Uses IDEA encryption
 8857: 
 8858: B<lond> forks off children processes that correspond to the other servers
 8859: in the network.  Management of these processes can be done at the
 8860: parent process level or the child process level.
 8861: 
 8862: B<logs/lond.log> is the location of log messages.
 8863: 
 8864: The process management is now explained in terms of linux shell commands,
 8865: subroutines internal to this code, and signal assignments:
 8866: 
 8867: =over 4
 8868: 
 8869: =item *
 8870: 
 8871: PID is stored in B<logs/lond.pid>
 8872: 
 8873: This is the process id number of the parent B<lond> process.
 8874: 
 8875: =item *
 8876: 
 8877: SIGTERM and SIGINT
 8878: 
 8879: Parent signal assignment:
 8880:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 8881: 
 8882: Child signal assignment:
 8883:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
 8884: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
 8885:  to restart a new child.)
 8886: 
 8887: Command-line invocations:
 8888:  B<kill> B<-s> SIGTERM I<PID>
 8889:  B<kill> B<-s> SIGINT I<PID>
 8890: 
 8891: Subroutine B<HUNTSMAN>:
 8892:  This is only invoked for the B<lond> parent I<PID>.
 8893: This kills all the children, and then the parent.
 8894: The B<lonc.pid> file is cleared.
 8895: 
 8896: =item *
 8897: 
 8898: SIGHUP
 8899: 
 8900: Current bug:
 8901:  This signal can only be processed the first time
 8902: on the parent process.  Subsequent SIGHUP signals
 8903: have no effect.
 8904: 
 8905: Parent signal assignment:
 8906:  $SIG{HUP}  = \&HUPSMAN;
 8907: 
 8908: Child signal assignment:
 8909:  none (nothing happens)
 8910: 
 8911: Command-line invocations:
 8912:  B<kill> B<-s> SIGHUP I<PID>
 8913: 
 8914: Subroutine B<HUPSMAN>:
 8915:  This is only invoked for the B<lond> parent I<PID>,
 8916: This kills all the children, and then the parent.
 8917: The B<lond.pid> file is cleared.
 8918: 
 8919: =item *
 8920: 
 8921: SIGUSR1
 8922: 
 8923: Parent signal assignment:
 8924:  $SIG{USR1} = \&USRMAN;
 8925: 
 8926: Child signal assignment:
 8927:  $SIG{USR1}= \&logstatus;
 8928: 
 8929: Command-line invocations:
 8930:  B<kill> B<-s> SIGUSR1 I<PID>
 8931: 
 8932: Subroutine B<USRMAN>:
 8933:  When invoked for the B<lond> parent I<PID>,
 8934: SIGUSR1 is sent to all the children, and the status of
 8935: each connection is logged.
 8936: 
 8937: =item *
 8938: 
 8939: SIGUSR2
 8940: 
 8941: Parent Signal assignment:
 8942:     $SIG{USR2} = \&UpdateHosts
 8943: 
 8944: Child signal assignment:
 8945:     NONE
 8946: 
 8947: 
 8948: =item *
 8949: 
 8950: SIGCHLD
 8951: 
 8952: Parent signal assignment:
 8953:  $SIG{CHLD} = \&REAPER;
 8954: 
 8955: Child signal assignment:
 8956:  none
 8957: 
 8958: Command-line invocations:
 8959:  B<kill> B<-s> SIGCHLD I<PID>
 8960: 
 8961: Subroutine B<REAPER>:
 8962:  This is only invoked for the B<lond> parent I<PID>.
 8963: Information pertaining to the child is removed.
 8964: The socket port is cleaned up.
 8965: 
 8966: =back
 8967: 
 8968: B<SERVER-SIDE ACTIVITIES>
 8969: 
 8970: Server-side information can be accepted in an encrypted or non-encrypted
 8971: method.
 8972: 
 8973: =over 4
 8974: 
 8975: =item ping
 8976: 
 8977: Query a client in the hosts.tab table; "Are you there?"
 8978: 
 8979: =item pong
 8980: 
 8981: Respond to a ping query.
 8982: 
 8983: =item ekey
 8984: 
 8985: Read in encrypted key, make cipher.  Respond with a buildkey.
 8986: 
 8987: =item load
 8988: 
 8989: Respond with CPU load based on a computation upon /proc/loadavg.
 8990: 
 8991: =item currentauth
 8992: 
 8993: Reply with current authentication information (only over an
 8994: encrypted channel).
 8995: 
 8996: =item auth
 8997: 
 8998: Only over an encrypted channel, reply as to whether a user's
 8999: authentication information can be validated.
 9000: 
 9001: =item passwd
 9002: 
 9003: Allow for a password to be set.
 9004: 
 9005: =item makeuser
 9006: 
 9007: Make a user.
 9008: 
 9009: =item changeuserauth
 9010: 
 9011: Allow for authentication mechanism and password to be changed.
 9012: 
 9013: =item home
 9014: 
 9015: Respond to a question "are you the home for a given user?"
 9016: 
 9017: =item update
 9018: 
 9019: Update contents of a subscribed resource.
 9020: 
 9021: =item unsubscribe
 9022: 
 9023: The server is unsubscribing from a resource.
 9024: 
 9025: =item subscribe
 9026: 
 9027: The server is subscribing to a resource.
 9028: 
 9029: =item log
 9030: 
 9031: Place in B<logs/lond.log>
 9032: 
 9033: =item put
 9034: 
 9035: stores hash in namespace
 9036: 
 9037: =item rolesput
 9038: 
 9039: put a role into a user's environment
 9040: 
 9041: =item get
 9042: 
 9043: returns hash with keys from array
 9044: reference filled in from namespace
 9045: 
 9046: =item eget
 9047: 
 9048: returns hash with keys from array
 9049: reference filled in from namesp (encrypts the return communication)
 9050: 
 9051: =item rolesget
 9052: 
 9053: get a role from a user's environment
 9054: 
 9055: =item del
 9056: 
 9057: deletes keys out of array from namespace
 9058: 
 9059: =item keys
 9060: 
 9061: returns namespace keys
 9062: 
 9063: =item dump
 9064: 
 9065: dumps the complete (or key matching regexp) namespace into a hash
 9066: 
 9067: =item store
 9068: 
 9069: stores hash permanently
 9070: for this url; hashref needs to be given and should be a \%hashname; the
 9071: remaining args aren't required and if they aren't passed or are '' they will
 9072: be derived from the ENV
 9073: 
 9074: =item restore
 9075: 
 9076: returns a hash for a given url
 9077: 
 9078: =item querysend
 9079: 
 9080: Tells client about the lonsql process that has been launched in response
 9081: to a sent query.
 9082: 
 9083: =item queryreply
 9084: 
 9085: Accept information from lonsql and make appropriate storage in temporary
 9086: file space.
 9087: 
 9088: =item idput
 9089: 
 9090: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
 9091: for each student, defined perhaps by the institutional Registrar.)
 9092: 
 9093: =item idget
 9094: 
 9095: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
 9096: for each student, defined perhaps by the institutional Registrar.)
 9097: 
 9098: =item iddel
 9099: 
 9100: Deletes one or more ids in a domain's id database.
 9101: 
 9102: =item tmpput
 9103: 
 9104: Accept and store information in temporary space.
 9105: 
 9106: =item tmpget
 9107: 
 9108: Send along temporarily stored information.
 9109: 
 9110: =item ls
 9111: 
 9112: List part of a user's directory.
 9113: 
 9114: =item pushtable
 9115: 
 9116: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
 9117: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
 9118: must be restored manually in case of a problem with the new table file.
 9119: pushtable requires that the request be encrypted and validated via
 9120: ValidateManager.  The form of the command is:
 9121: enc:pushtable tablename <tablecontents> \n
 9122: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
 9123: cleartext newline.
 9124: 
 9125: =item Hanging up (exit or init)
 9126: 
 9127: What to do when a client tells the server that they (the client)
 9128: are leaving the network.
 9129: 
 9130: =item unknown command
 9131: 
 9132: If B<lond> is sent an unknown command (not in the list above),
 9133: it replys to the client "unknown_cmd".
 9134: 
 9135: 
 9136: =item UNKNOWN CLIENT
 9137: 
 9138: If the anti-spoofing algorithm cannot verify the client,
 9139: the client is rejected (with a "refused" message sent
 9140: to the client, and the connection is closed.
 9141: 
 9142: =back
 9143: 
 9144: =head1 PREREQUISITES
 9145: 
 9146: IO::Socket
 9147: IO::File
 9148: Apache::File
 9149: POSIX
 9150: Crypt::IDEA
 9151: GDBM_File
 9152: Authen::Krb4
 9153: Authen::Krb5
 9154: 
 9155: =head1 COREQUISITES
 9156: 
 9157: none
 9158: 
 9159: =head1 OSNAMES
 9160: 
 9161: linux
 9162: 
 9163: =head1 SCRIPT CATEGORIES
 9164: 
 9165: Server/Process
 9166: 
 9167: =cut
 9168: 
 9169: 
 9170: =pod
 9171: 
 9172: =head1 LOG MESSAGES
 9173: 
 9174: The messages below can be emitted in the lond log.  This log is located
 9175: in ~httpd/perl/logs/lond.log  Many log messages have HTML encapsulation
 9176: to provide coloring if examined from inside a web page. Some do not.
 9177: Where color is used, the colors are; Red for sometihhng to get excited
 9178: about and to follow up on. Yellow for something to keep an eye on to
 9179: be sure it does not get worse, Green,and Blue for informational items.
 9180: 
 9181: In the discussions below, sometimes reference is made to ~httpd
 9182: when describing file locations.  There isn't really an httpd 
 9183: user, however there is an httpd directory that gets installed in the
 9184: place that user home directories go.  On linux, this is usually
 9185: (always?) /home/httpd.
 9186: 
 9187: 
 9188: Some messages are colorless.  These are usually (not always)
 9189: Green/Blue color level messages.
 9190: 
 9191: =over 2
 9192: 
 9193: =item (Red)  LocalConnection rejecting non local: <ip> ne 127.0.0.1
 9194: 
 9195: A local connection negotiation was attempted by
 9196: a host whose IP address was not 127.0.0.1.
 9197: The socket is closed and the child will exit.
 9198: lond has three ways to establish an encyrption
 9199: key with a client:
 9200: 
 9201: =over 2
 9202: 
 9203: =item local 
 9204: 
 9205: The key is written and read from a file.
 9206: This is only valid for connections from localhost.
 9207: 
 9208: =item insecure 
 9209: 
 9210: The key is generated by the server and
 9211: transmitted to the client.
 9212: 
 9213: =item  ssl (secure)
 9214: 
 9215: An ssl connection is negotiated with the client,
 9216: the key is generated by the server and sent to the 
 9217: client across this ssl connection before the
 9218: ssl connectionis terminated and clear text
 9219: transmission resumes.
 9220: 
 9221: =back
 9222: 
 9223: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
 9224: 
 9225: The client is local but has not sent an initialization
 9226: string that is the literal "init:local"  The connection
 9227: is closed and the child exits.
 9228: 
 9229: =item Red CRITICAL Can't get key file <error>        
 9230: 
 9231: SSL key negotiation is being attempted but the call to
 9232: lonssl::KeyFile failed.  This usually means that the
 9233: configuration file is not correctly defining or protecting
 9234: the directories/files lonCertificateDirectory or
 9235: lonnetPrivateKey
 9236: <error> is a string that describes the reason that
 9237: the key file could not be located.
 9238: 
 9239: =item (Red) CRITICAL  Can't get certificates <error>  
 9240: 
 9241: SSL key negotiation failed because we were not able to retrives our certificate
 9242: or the CA's certificate in the call to lonssl::CertificateFile
 9243: <error> is the textual reason this failed.  Usual reasons:
 9244: 
 9245: =over 2
 9246: 
 9247: =item Apache config file for loncapa  incorrect:
 9248: 
 9249: one of the variables 
 9250: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
 9251: undefined or incorrect
 9252: 
 9253: =item Permission error:
 9254: 
 9255: The directory pointed to by lonCertificateDirectory is not readable by lond
 9256: 
 9257: =item Permission error:
 9258: 
 9259: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
 9260: 
 9261: =item Installation error:                         
 9262: 
 9263: Either the certificate authority file or the certificate have not
 9264: been installed in lonCertificateDirectory.
 9265: 
 9266: =item (Red) CRITICAL SSL Socket promotion failed:  <err> 
 9267: 
 9268: The promotion of the connection from plaintext to SSL failed
 9269: <err> is the reason for the failure.  There are two
 9270: system calls involved in the promotion (one of which failed), 
 9271: a dup to produce
 9272: a second fd on the raw socket over which the encrypted data
 9273: will flow and IO::SOcket::SSL->new_from_fd which creates
 9274: the SSL connection on the duped fd.
 9275: 
 9276: =item (Blue)   WARNING client did not respond to challenge 
 9277: 
 9278: This occurs on an insecure (non SSL) connection negotiation request.
 9279: lond generates some number from the time, the PID and sends it to
 9280: the client.  The client must respond by echoing this information back.
 9281: If the client does not do so, that's a violation of the challenge
 9282: protocols and the connection will be failed.
 9283: 
 9284: =item (Red) No manager table. Nobody can manage!!    
 9285: 
 9286: lond has the concept of privileged hosts that
 9287: can perform remote management function such
 9288: as update the hosts.tab.   The manager hosts
 9289: are described in the 
 9290: ~httpd/lonTabs/managers.tab file.
 9291: this message is logged if this file is missing.
 9292: 
 9293: 
 9294: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
 9295: 
 9296: Reports the successful parse and registration
 9297: of a specific manager. 
 9298: 
 9299: =item Green existing host <clustername:dnsname>  
 9300: 
 9301: The manager host is already defined in the hosts.tab
 9302: the information in that table, rather than the info in the
 9303: manager table will be used to determine the manager's ip.
 9304: 
 9305: =item (Red) Unable to craete <filename>                 
 9306: 
 9307: lond has been asked to create new versions of an administrative
 9308: file (by a manager).  When this is done, the new file is created
 9309: in a temp file and then renamed into place so that there are always
 9310: usable administrative files, even if the update fails.  This failure
 9311: message means that the temp file could not be created.
 9312: The update is abandoned, and the old file is available for use.
 9313: 
 9314: =item (Green) CopyFile from <oldname> to <newname> failed
 9315: 
 9316: In an update of administrative files, the copy of the existing file to a
 9317: backup file failed.  The installation of the new file may still succeed,
 9318: but there will not be a back up file to rever to (this should probably
 9319: be yellow).
 9320: 
 9321: =item (Green) Pushfile: backed up <oldname> to <newname>
 9322: 
 9323: See above, the backup of the old administrative file succeeded.
 9324: 
 9325: =item (Red)  Pushfile: Unable to install <filename> <reason>
 9326: 
 9327: The new administrative file could not be installed.  In this case,
 9328: the old administrative file is still in use.
 9329: 
 9330: =item (Green) Installed new < filename>.                      
 9331: 
 9332: The new administrative file was successfullly installed.                                               
 9333: 
 9334: =item (Red) Reinitializing lond pid=<pid>                    
 9335: 
 9336: The lonc child process <pid> will be sent a USR2 
 9337: signal.
 9338: 
 9339: =item (Red) Reinitializing self                                    
 9340: 
 9341: We've been asked to re-read our administrative files,and
 9342: are doing so.
 9343: 
 9344: =item (Yellow) error:Invalid process identifier <ident>  
 9345: 
 9346: A reinit command was received, but the target part of the 
 9347: command was not valid.  It must be either
 9348: 'lond' or 'lonc' but was <ident>
 9349: 
 9350: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
 9351: 
 9352: Checking to see if lond has been handed a valid edit
 9353: command.  It is possible the edit command is not valid
 9354: in that case there are no log messages to indicate that.
 9355: 
 9356: =item Result of password change for  <username> pwchange_success
 9357: 
 9358: The password for <username> was
 9359: successfully changed.
 9360: 
 9361: =item Unable to open <user> passwd to change password
 9362: 
 9363: Could not rewrite the 
 9364: internal password file for a user
 9365: 
 9366: =item Result of password change for <user> : <result>
 9367: 
 9368: A unix password change for <user> was attempted 
 9369: and the pipe returned <result>  
 9370: 
 9371: =item LWP GET: <message> for <fname> (<remoteurl>)
 9372: 
 9373: The lightweight process fetch for a resource failed
 9374: with <message> the local filename that should
 9375: have existed/been created was  <fname> the
 9376: corresponding URI: <remoteurl>  This is emitted in several
 9377: places.
 9378: 
 9379: =item Unable to move <transname> to <destname>     
 9380: 
 9381: From fetch_user_file_handler - the user file was replicated but could not
 9382: be mv'd to its final location.
 9383: 
 9384: =item Looking for <domain> <username>              
 9385: 
 9386: From user_has_session_handler - This should be a Debug call instead
 9387: it indicates lond is about to check whether the specified user has a 
 9388: session active on the specified domain on the local host.
 9389: 
 9390: =item Client <ip> (<name>) hanging up: <input>     
 9391: 
 9392: lond has been asked to exit by its client.  The <ip> and <name> identify the
 9393: client systemand <input> is the full exit command sent to the server.
 9394: 
 9395: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
 9396: 
 9397: A lond child terminated.  NOte that this termination can also occur when the
 9398: child receives the QUIT or DIE signals.  <pid> is the process id of the child,
 9399: <hostname> the host lond is working for, and <message> the reason the child died
 9400: to the best of our ability to get it (I would guess that any numeric value
 9401: represents and errno value).  This is immediately followed by
 9402: 
 9403: =item  Famous last words: Catching exception - <log> 
 9404: 
 9405: Where log is some recent information about the state of the child.
 9406: 
 9407: =item Red CRITICAL: TIME OUT <pid>                     
 9408: 
 9409: Some timeout occured for server <pid>.  THis is normally a timeout on an LWP
 9410: doing an HTTP::GET.
 9411: 
 9412: =item child <pid> died                              
 9413: 
 9414: The reaper caught a SIGCHILD for the lond child process <pid>
 9415: This should be modified to also display the IP of the dying child
 9416: $children{$pid}
 9417: 
 9418: =item Unknown child 0 died                           
 9419: A child died but the wait for it returned a pid of zero which really should not
 9420: ever happen. 
 9421: 
 9422: =item Child <which> - <pid> looks like we missed it's death 
 9423: 
 9424: When a sigchild is received, the reaper process checks all children to see if they are
 9425: alive.  If children are dying quite quickly, the lack of signal queuing can mean
 9426: that a signal hearalds the death of more than one child.  If so this message indicates
 9427: which other one died. <which> is the ip of a dead child
 9428: 
 9429: =item Free socket: <shutdownretval>                
 9430: 
 9431: The HUNTSMAN sub was called due to a SIGINT in a child process.  The socket is being shutdown.
 9432: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
 9433: to return anything. This is followed by: 
 9434: 
 9435: =item Red CRITICAL: Shutting down                       
 9436: 
 9437: Just prior to exit.
 9438: 
 9439: =item Free socket: <shutdownretval>                 
 9440: 
 9441: The HUPSMAN sub was called due to a SIGHUP.  all children get killsed, and lond execs itself.
 9442: This is followed by:
 9443: 
 9444: =item (Red) CRITICAL: Restarting                         
 9445: 
 9446: lond is about to exec itself to restart.
 9447: 
 9448: =item (Blue) Updating connections                        
 9449: 
 9450: (In response to a USR2).  All the children (except the one for localhost)
 9451: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
 9452: 
 9453: =item (Blue) UpdateHosts killing child <pid> for ip <ip>   
 9454: 
 9455: Due to USR2 as above.
 9456: 
 9457: =item (Green) keeping child for ip <ip> (pid = <pid>)    
 9458: 
 9459: In response to USR2 as above, the child indicated is not being restarted because
 9460: it's assumed that we'll always need a child for the localhost.
 9461: 
 9462: 
 9463: =item Going to check on the children                
 9464: 
 9465: Parent is about to check on the health of the child processes.
 9466: Note that this is in response to a USR1 sent to the parent lond.
 9467: there may be one or more of the next two messages:
 9468: 
 9469: =item <pid> is dead                                 
 9470: 
 9471: A child that we have in our child hash as alive has evidently died.
 9472: 
 9473: =item  Child <pid> did not respond                   
 9474: 
 9475: In the health check the child <pid> did not update/produce a pid_.txt
 9476: file when sent it's USR1 signal.  That process is killed with a 9 signal, as it's
 9477: assumed to be hung in some un-fixable way.
 9478: 
 9479: =item Finished checking children                   
 9480: 
 9481: Master processs's USR1 processing is cojmplete.
 9482: 
 9483: =item (Red) CRITICAL: ------- Starting ------            
 9484: 
 9485: (There are more '-'s on either side).  Lond has forked itself off to 
 9486: form a new session and is about to start actual initialization.
 9487: 
 9488: =item (Green) Attempting to start child (<client>)       
 9489: 
 9490: Started a new child process for <client>.  Client is IO::Socket object
 9491: connected to the child.  This was as a result of a TCP/IP connection from a client.
 9492: 
 9493: =item Unable to determine who caller was, getpeername returned nothing
 9494: 
 9495: In child process initialization.  either getpeername returned undef or
 9496: a zero sized object was returned.  Processing continues, but in my opinion,
 9497: this should be cause for the child to exit.
 9498: 
 9499: =item Unable to determine clientip                  
 9500: 
 9501: In child process initialization.  The peer address from getpeername was not defined.
 9502: The client address is stored as "Unavailable" and processing continues.
 9503: 
 9504: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
 9505: 
 9506: In child initialization.  A good connectionw as received from <ip>.
 9507: 
 9508: =over 2
 9509: 
 9510: =item <name> 
 9511: 
 9512: is the name of the client from hosts.tab.
 9513: 
 9514: =item <type> 
 9515: 
 9516: Is the connection type which is either 
 9517: 
 9518: =over 2
 9519: 
 9520: =item manager 
 9521: 
 9522: The connection is from a manager node, not in hosts.tab
 9523: 
 9524: =item client  
 9525: 
 9526: the connection is from a non-manager in the hosts.tab
 9527: 
 9528: =item both
 9529: 
 9530: The connection is from a manager in the hosts.tab.
 9531: 
 9532: =back
 9533: 
 9534: =back
 9535: 
 9536: =item (Blue) Certificates not installed -- trying insecure auth
 9537: 
 9538: One of the certificate file, key file or
 9539: certificate authority file could not be found for a client attempting
 9540: SSL connection intiation.  COnnection will be attemptied in in-secure mode.
 9541: (this would be a system with an up to date lond that has not gotten a 
 9542: certificate from us).
 9543: 
 9544: =item (Green)  Successful local authentication            
 9545: 
 9546: A local connection successfully negotiated the encryption key. 
 9547: In this case the IDEA key is in a file (that is hopefully well protected).
 9548: 
 9549: =item (Green) Successful ssl authentication with <client>  
 9550: 
 9551: The client (<client> is the peer's name in hosts.tab), has successfully
 9552: negotiated an SSL connection with this child process.
 9553: 
 9554: =item (Green) Successful insecure authentication with <client>
 9555: 
 9556: 
 9557: The client has successfully negotiated an  insecure connection withthe child process.
 9558: 
 9559: =item (Yellow) Attempted insecure connection disallowed    
 9560: 
 9561: The client attempted and failed to successfully negotiate a successful insecure
 9562: connection.  This can happen either because the variable londAllowInsecure is false
 9563: or undefined, or becuse the child did not successfully echo back the challenge
 9564: string.
 9565: 
 9566: 
 9567: =back
 9568: 
 9569: =back
 9570: 
 9571: 
 9572: =cut

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