File:  [LON-CAPA] / loncom / lond
Revision 1.583: download - view: text, annotated - select for diffs
Fri Dec 27 02:32:56 2024 UTC (8 weeks ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- Support copying of directories and/or files from Course Authoring Space
  to a user's authoring space in the case where the course's homeserver is
  not the current server.
- Display last modification date and if published when listing files in
  Course Authoring Space.

    1: #!/usr/bin/perl
    2: # The LearningOnline Network
    3: # lond "LON Daemon" Server (port "LOND" 5663)
    4: #
    5: # $Id: lond,v 1.583 2024/12/27 02:32:56 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.583 $'; #' stupid emacs
   69: my $remoteVERSION;
   70: my $currenthostid="default";
   71: my $currentdomainid;
   72: 
   73: my $client;
   74: my $clientip;			# IP address of client.
   75: my $clientname;			# LonCAPA name of client.
   76: my $clientversion;              # LonCAPA version running on client.
   77: my $clienthomedom;              # LonCAPA domain of homeID for client. 
   78: my $clientintdom;               # LonCAPA "internet domain" for client.
   79: my $clientsamedom;              # LonCAPA domain same for this host 
   80:                                 # and client.
   81: my $clientsameinst;             # LonCAPA "internet domain" same for 
   82:                                 # this host and client.
   83: my $clientremoteok;             # Current domain permits hosting on client
   84:                                 # (not set if host and client share "internet domain").
   85:                                 # Values are 0 or 1; 1 if allowed.
   86: my %clientprohibited;           # Commands from client prohibited for domain's
   87:                                 # users.
   88: 
   89: my $server;
   90: 
   91: my $keymode;
   92: 
   93: my $cipher;			# Cipher key negotiated with client
   94: my $tmpsnum = 0;		# Id of tmpputs.
   95: 
   96: # 
   97: #   Connection type is:
   98: #      client                   - All client actions are allowed
   99: #      manager                  - only management functions allowed.
  100: #      both                     - Both management and client actions are allowed
  101: #
  102: 
  103: my $ConnectionType;
  104: 
  105: my %managers;			# Ip -> manager names
  106: 
  107: my %perlvar;			# Will have the apache conf defined perl vars.
  108: 
  109: my %secureconf;                 # Will have requirements for security 
  110:                                 # of lond connections
  111: 
  112: my %crlchecked;                 # Will contain clients for which the client's SSL
  113:                                 # has been checked against the cluster's Certificate
  114:                                 # Revocation List.
  115: 
  116: my $dist;
  117: 
  118: #
  119: #   The hash below is used for command dispatching, and is therefore keyed on the request keyword.
  120: #    Each element of the hash contains a reference to an array that contains:
  121: #          A reference to a sub that executes the request corresponding to the keyword.
  122: #          A flag that is true if the request must be encoded to be acceptable.
  123: #          A mask with bits as follows:
  124: #                      CLIENT_OK    - Set when the function is allowed by ordinary clients
  125: #                      MANAGER_OK   - Set when the function is allowed to manager clients.
  126: #
  127: my $CLIENT_OK  = 1;
  128: my $MANAGER_OK = 2;
  129: my %Dispatcher;
  130: 
  131: 
  132: #
  133: #  The array below are password error strings."
  134: #
  135: my $lastpwderror    = 13;		# Largest error number from lcpasswd.
  136: my @passwderrors = ("ok",
  137: 		   "pwchange_failure - lcpasswd must be run as user 'www'",
  138: 		   "pwchange_failure - lcpasswd got incorrect number of arguments",
  139: 		   "pwchange_failure - lcpasswd did not get the right nubmer of input text lines",
  140: 		   "pwchange_failure - lcpasswd too many simultaneous pwd changes in progress",
  141: 		   "pwchange_failure - lcpasswd User does not exist.",
  142: 		   "pwchange_failure - lcpasswd Incorrect current passwd",
  143: 		   "pwchange_failure - lcpasswd Unable to su to root.",
  144: 		   "pwchange_failure - lcpasswd Cannot set new passwd.",
  145: 		   "pwchange_failure - lcpasswd Username has invalid characters",
  146: 		   "pwchange_failure - lcpasswd Invalid characters in password",
  147: 		   "pwchange_failure - lcpasswd User already exists", 
  148:                    "pwchange_failure - lcpasswd Something went wrong with user addition.",
  149: 		   "pwchange_failure - lcpasswd Password mismatch",
  150: 		   "pwchange_failure - lcpasswd Error filename is invalid");
  151: 
  152: 
  153: # This array are the errors from lcinstallfile:
  154: 
  155: my @installerrors = ("ok",
  156: 		     "Initial user id of client not that of www",
  157: 		     "Usage error, not enough command line arguments",
  158: 		     "Source filename does not exist",
  159: 		     "Destination filename does not exist",
  160: 		     "Some file operation failed",
  161: 		     "Invalid table filename."
  162: 		     );
  163: 
  164: #
  165: # The %trust hash classifies commands according to type of trust 
  166: # required for execution of the command.
  167: #
  168: # When clients from a different institution request execution of a
  169: # particular command, the trust settings for that institution set
  170: # for this domain (or default domain for a multi-domain server) will
  171: # be checked to see if running the command is allowed.
  172: #
  173: # Trust types which depend on the "Trust" domain configuration
  174: # for the machine's default domain are:
  175: #
  176: # content   ("Access to this domain's content by others")
  177: # shared    ("Access to other domain's content by this domain")
  178: # enroll    ("Enrollment in this domain's courses by others")
  179: # coaurem   ("Co-author roles for this domain's users elsewhere")
  180: # othcoau   ("Co-author roles in this domain for others")
  181: # domroles  ("Domain roles in this domain assignable to others")
  182: # catalog   ("Course Catalog for this domain displayed elsewhere")
  183: # reqcrs    ("Requests for creation of courses in this domain by others")
  184: # msg       ("Users in other domains can send messages to this domain")
  185: # 
  186: # Trust type which depends on the User Session Hosting (remote) 
  187: # domain configuration for machine's default domain is: "remote".
  188: #
  189: # Trust types which depend on contents of manager.tab in 
  190: # /home/httpd/lonTabs is: "manageronly".
  191: # 
  192: # Trust type which requires client to share the same LON-CAPA
  193: # "internet domain" (i.e., same institution as this server) is:
  194: # "institutiononly".
  195: #
  196: 
  197: my %trust = (
  198:                auth => {remote => 1},
  199:                autocreatepassword => {remote => 1},
  200:                autocrsreqchecks => {remote => 1, reqcrs => 1},
  201:                autocrsrequpdate => {remote => 1},
  202:                autocrsreqvalidation => {remote => 1},
  203:                autogetsections => {remote => 1},
  204:                autoinstcodedefaults => {remote => 1, catalog => 1},
  205:                autoinstcodeformat => {remote => 1, catalog => 1},
  206:                autonewcourse => {remote => 1, reqcrs => 1},
  207:                autophotocheck => {remote => 1, enroll => 1},
  208:                autophotochoice => {remote => 1},
  209:                autophotopermission => {remote => 1, enroll => 1},
  210:                autopossibleinstcodes => {remote => 1, reqcrs => 1},
  211:                autoretrieve => {remote => 1, enroll => 1, catalog => 1},
  212:                autorun => {remote => 1, enroll => 1, reqcrs => 1},
  213:                autovalidateclass_sec => {catalog => 1},
  214:                autovalidatecourse => {remote => 1, enroll => 1},
  215:                autovalidateinstcode => {domroles => 1, remote => 1, enroll => 1},
  216:                autovalidateinstcrosslist => {remote => 1, enroll => 1},
  217:                autoinstsecreformat => {remote => 1, enroll => 1},
  218:                changeuserauth => {remote => 1, domroles => 1},
  219:                chatretr => {remote => 1, enroll => 1},
  220:                chatsend => {remote => 1, enroll => 1},
  221:                courseiddump => {remote => 1, domroles => 1, enroll => 1},
  222:                courseidput => {remote => 1, domroles => 1, enroll => 1},
  223:                courseidputhash => {remote => 1, domroles => 1, enroll => 1},
  224:                courselastaccess => {remote => 1, domroles => 1, enroll => 1},
  225:                coursesessions => {institutiononly => 1},
  226:                crsfilefrompriv => {remote => 1, enroll => 1},
  227:                currentauth => {remote => 1, domroles => 1, enroll => 1},
  228:                currentdump => {remote => 1, enroll => 1},
  229:                currentversion => {remote=> 1, content => 1},
  230:                dcmaildump => {remote => 1, domroles => 1},
  231:                dcmailput => {remote => 1, domroles => 1},
  232:                del => {remote => 1, domroles => 1, enroll => 1, content => 1},
  233:                delbalcookie => {institutiononly => 1},
  234:                delusersession => {institutiononly => 1},
  235:                deldom => {remote => 1, domroles => 1}, # not currently used
  236:                devalidatecache => {institutiononly => 1},
  237:                domroleput => {remote => 1, enroll => 1},
  238:                domrolesdump => {remote => 1, catalog => 1},
  239:                du => {remote => 1, enroll => 1},
  240:                du2 => {remote => 1, enroll => 1},
  241:                dump => {remote => 1, enroll => 1, domroles => 1},
  242:                edit => {institutiononly => 1},  #not used currently
  243:                edump => {remote => 1, enroll => 1, domroles => 1},
  244:                eget => {remote => 1, domroles => 1, enroll => 1}, #not used currently
  245:                egetdom => {remote => 1, domroles => 1, enroll => 1, },
  246:                ekey => {anywhere => 1},
  247:                exit => {anywhere => 1},
  248:                fetchuserfile => {remote => 1, enroll => 1},
  249:                get => {remote => 1, domroles => 1, enroll => 1},
  250:                getdom => {anywhere => 1},
  251:                home => {anywhere => 1},
  252:                iddel => {remote => 1, enroll => 1},
  253:                idget => {remote => 1, enroll => 1},
  254:                idput => {remote => 1, domroles => 1, enroll => 1},
  255:                inc => {remote => 1, enroll => 1},
  256:                init => {anywhere => 1},
  257:                inst_usertypes => {remote => 1, domroles => 1, enroll => 1},
  258:                instemailrules => {remote => 1, domroles => 1},
  259:                instidrulecheck => {remote => 1, domroles => 1,},
  260:                instidrules => {remote => 1, domroles => 1,},
  261:                instrulecheck => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
  262:                instselfcreatecheck => {institutiononly => 1},
  263:                instunamemapcheck => {remote => 1,},  
  264:                instuserrules => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
  265:                keys => {remote => 1,},
  266:                load => {anywhere => 1},
  267:                log => {anywhere => 1},
  268:                ls => {remote => 1, enroll => 1, content => 1,},
  269:                ls2 => {remote => 1, enroll => 1, content => 1,},
  270:                ls3 => {remote => 1, enroll => 1, content => 1,},
  271:                lti => {institutiononly => 1},
  272:                makeuser => {remote => 1, enroll => 1, domroles => 1,},
  273:                mkdiruserfile => {remote => 1, enroll => 1,},
  274:                newput => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1,},
  275:                passwd => {remote => 1},
  276:                ping => {anywhere => 1},
  277:                pong => {anywhere => 1},
  278:                pushfile => {manageronly => 1},
  279:                put => {remote => 1, enroll => 1, domroles => 1, msg => 1, content => 1, shared => 1},
  280:                putdom => {remote => 1, domroles => 1,},
  281:                putstore => {remote => 1, enroll => 1},
  282:                queryreply => {anywhere => 1},
  283:                querysend => {anywhere => 1},
  284:                querysend_activitylog => {remote => 1},
  285:                querysend_allusers => {remote => 1, domroles => 1},
  286:                querysend_courselog => {remote => 1},
  287:                querysend_fetchenrollment => {remote => 1},
  288:                querysend_getinstuser => {remote => 1},
  289:                querysend_getmultinstusers => {remote => 1},
  290:                querysend_instdirsearch => {remote => 1, domroles => 1, coaurem => 1},
  291:                querysend_institutionalphotos => {remote => 1},
  292:                querysend_portfolio_metadata => {remote => 1, content => 1},
  293:                querysend_userlog => {remote => 1, domroles => 1},
  294:                querysend_usersearch => {remote => 1, enroll => 1, coaurem => 1},
  295:                quit => {anywhere => 1},
  296:                readlonnetglobal => {institutiononly => 1},
  297:                reinit => {manageronly => 1}, #not used currently
  298:                removeuserfile => {remote => 1, enroll => 1},
  299:                renameuserfile => {remote => 1,},
  300:                restore => {remote => 1, enroll => 1, reqcrs => 1,},
  301:                rolesdel => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
  302:                rolesput => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
  303:                servercerts => {institutiononly => 1},
  304:                serverdistarch => {anywhere => 1},
  305:                serverhomeID => {anywhere => 1},
  306:                serverloncaparev => {anywhere => 1},
  307:                servertimezone => {remote => 1, enroll => 1},
  308:                setannounce => {remote => 1, domroles => 1},
  309:                sethost => {anywhere => 1},
  310:                signlti => {remote => 1},
  311:                store => {remote => 1, enroll => 1, reqcrs => 1,},
  312:                studentphoto => {remote => 1, enroll => 1},
  313:                sub => {content => 1,},
  314:                tmpdel => {institutiononly => 1},
  315:                tmpget => {institutiononly => 1},
  316:                tmpput => {remote => 1, othcoau => 1},
  317:                tokenauthuserfile => {anywhere => 1},
  318:                unamemaprules => {remote => 1,},
  319:                unsub => {content => 1,},
  320:                update => {shared => 1},
  321:                updatebalcookie => {institutiononly => 1},
  322:                updateclickers => {remote => 1},
  323:                userhassession => {anywhere => 1},
  324:                userload => {anywhere => 1},
  325:                version => {anywhere => 1}, #not used
  326:             );
  327: 
  328: #
  329: #   Statistics that are maintained and dislayed in the status line.
  330: #
  331: my $Transactions = 0;		# Number of attempted transactions.
  332: my $Failures     = 0;		# Number of transcations failed.
  333: 
  334: #   ResetStatistics: 
  335: #      Resets the statistics counters:
  336: #
  337: sub ResetStatistics {
  338:     $Transactions = 0;
  339:     $Failures     = 0;
  340: }
  341: 
  342: #------------------------------------------------------------------------
  343: #
  344: #   LocalConnection
  345: #     Completes the formation of a locally authenticated connection.
  346: #     This function will ensure that the 'remote' client is really the
  347: #     local host.  If not, the connection is closed, and the function fails.
  348: #     If so, initcmd is parsed for the name of a file containing the
  349: #     IDEA session key.  The fie is opened, read, deleted and the session
  350: #     key returned to the caller.
  351: #
  352: # Parameters:
  353: #   $Socket      - Socket open on client.
  354: #   $initcmd     - The full text of the init command.
  355: #
  356: # Returns:
  357: #     IDEA session key on success.
  358: #     undef on failure.
  359: #
  360: sub LocalConnection {
  361:     my ($Socket, $initcmd) = @_;
  362:     Debug("Attempting local connection: $initcmd client: $clientip");
  363:     if($clientip ne "127.0.0.1") {
  364: 	&logthis('<font color="red"> LocalConnection rejecting non local: '
  365: 		 ."$clientip ne 127.0.0.1 </font>");
  366: 	close $Socket;
  367: 	return undef;
  368:     }  else {
  369: 	chomp($initcmd);	# Get rid of \n in filename.
  370: 	my ($init, $type, $name) = split(/:/, $initcmd);
  371: 	Debug(" Init command: $init $type $name ");
  372: 
  373: 	# Require that $init = init, and $type = local:  Otherwise
  374: 	# the caller is insane:
  375: 
  376: 	if(($init ne "init") && ($type ne "local")) {
  377: 	    &logthis('<font color = "red"> LocalConnection: caller is insane! '
  378: 		     ."init = $init, and type = $type </font>");
  379: 	    close($Socket);;
  380: 	    return undef;
  381: 		
  382: 	}
  383: 	#  Now get the key filename:
  384: 
  385: 	my $IDEAKey = lonlocal::ReadKeyFile($name);
  386: 	return $IDEAKey;
  387:     }
  388: }
  389: #------------------------------------------------------------------------------
  390: #
  391: #  SSLConnection
  392: #   Completes the formation of an ssh authenticated connection. The
  393: #   socket is promoted to an ssl socket.  If this promotion and the associated
  394: #   certificate exchange are successful, the IDEA key is generated and sent
  395: #   to the remote peer via the SSL tunnel. The IDEA key is also returned to
  396: #   the caller after the SSL tunnel is torn down.
  397: #
  398: # Parameters:
  399: #   Name              Type             Purpose
  400: #   $Socket          IO::Socket::INET  Plaintext socket.
  401: #
  402: # Returns:
  403: #    IDEA key on success.
  404: #    undef on failure.
  405: #
  406: sub SSLConnection {
  407:     my $Socket   = shift;
  408: 
  409:     Debug("SSLConnection: ");
  410:     my $KeyFile         = lonssl::KeyFile();
  411:     if(!$KeyFile) {
  412: 	my $err = lonssl::LastError();
  413: 	&logthis("<font color=\"red\"> CRITICAL"
  414: 		 ."Can't get key file $err </font>");
  415: 	return undef;
  416:     }
  417:     my ($CACertificate,
  418: 	$Certificate) = lonssl::CertificateFile();
  419: 
  420: 
  421:     # If any of the key, certificate or certificate authority 
  422:     # certificate filenames are not defined, this can't work.
  423: 
  424:     if((!$Certificate) || (!$CACertificate)) {
  425: 	my $err = lonssl::LastError();
  426: 	&logthis("<font color=\"red\"> CRITICAL"
  427: 		 ."Can't get certificates: $err </font>");
  428: 
  429: 	return undef;
  430:     }
  431:     Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
  432: 
  433:     # Indicate to our peer that we can procede with
  434:     # a transition to ssl authentication:
  435: 
  436:     print $Socket "ok:ssl\n";
  437: 
  438:     Debug("Approving promotion -> ssl");
  439:     #  And do so:
  440: 
  441:     my $CRLFile;
  442:     unless ($crlchecked{$clientname}) {
  443:         $CRLFile = lonssl::CRLFile();
  444:         $crlchecked{$clientname} = 1;
  445:     }
  446: 
  447:     my $SSLSocket = lonssl::PromoteServerSocket($Socket,
  448: 						$CACertificate,
  449: 						$Certificate,
  450: 						$KeyFile,
  451: 						$clientname,
  452:                                                 $CRLFile,
  453:                                                 $clientversion);
  454:     if(! ($SSLSocket) ) {	# SSL socket promotion failed.
  455: 	my $err = lonssl::LastError();
  456: 	&logthis("<font color=\"red\"> CRITICAL "
  457: 		 ."SSL Socket promotion failed: $err </font>");
  458: 	return undef;
  459:     }
  460:     Debug("SSL Promotion successful");
  461: 
  462:     # 
  463:     #  The only thing we'll use the socket for is to send the IDEA key
  464:     #  to the peer:
  465: 
  466:     my $Key = lonlocal::CreateCipherKey();
  467:     print $SSLSocket "$Key\n";
  468: 
  469:     lonssl::Close($SSLSocket); 
  470: 
  471:     Debug("Key exchange complete: $Key");
  472: 
  473:     return $Key;
  474: }
  475: #
  476: #     InsecureConnection: 
  477: #        If insecure connections are allowd,
  478: #        exchange a challenge with the client to 'validate' the
  479: #        client (not really, but that's the protocol):
  480: #        We produce a challenge string that's sent to the client.
  481: #        The client must then echo the challenge verbatim to us.
  482: #
  483: #  Parameter:
  484: #      Socket      - Socket open on the client.
  485: #  Returns:
  486: #      1           - success.
  487: #      0           - failure (e.g.mismatch or insecure not allowed).
  488: #
  489: sub InsecureConnection {
  490:     my $Socket  =  shift;
  491: 
  492:     #   Don't even start if insecure connections are not allowed.
  493:     #   return 0 if Insecure connections not allowed.
  494:     #
  495:     if (ref($secureconf{'connfrom'}) eq 'HASH') {
  496:         if ($clientsamedom) {
  497:             if ($secureconf{'connfrom'}{'dom'} eq 'req') {
  498:                 return 0;
  499:             } 
  500:         } elsif ($clientsameinst) {
  501:             if ($secureconf{'connfrom'}{'intdom'} eq 'req') {
  502:                 return 0;
  503:             }
  504:         } else {
  505:             if ($secureconf{'connfrom'}{'other'} eq 'req') {
  506:                 return 0;
  507:             }
  508:         }
  509:     } elsif (!$perlvar{londAllowInsecure}) {
  510: 	return 0;
  511:     }
  512: 
  513:     #   Fabricate a challenge string and send it..
  514: 
  515:     my $challenge = "$$".time;	# pid + time.
  516:     print $Socket "$challenge\n";
  517:     &status("Waiting for challenge reply");
  518: 
  519:     my $answer = <$Socket>;
  520:     $answer    =~s/\W//g;
  521:     if($challenge eq $answer) {
  522: 	return 1;
  523:     } else {
  524: 	logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
  525: 	&status("No challenge reqply");
  526: 	return 0;
  527:     }
  528:     
  529: 
  530: }
  531: #
  532: #   Safely execute a command (as long as it's not a shel command and doesn
  533: #   not require/rely on shell escapes.   The function operates by doing a
  534: #   a pipe based fork and capturing stdout and stderr  from the pipe.
  535: #
  536: # Formal Parameters:
  537: #     $line                    - A line of text to be executed as a command.
  538: # Returns:
  539: #     The output from that command.  If the output is multiline the caller
  540: #     must know how to split up the output.
  541: #
  542: #
  543: sub execute_command {
  544:     my ($line)    = @_;
  545:     my @words     = split(/\s/, $line);	# Bust the command up into words.
  546:     my $output    = "";
  547: 
  548:     my $pid = open(CHILD, "-|");
  549:     
  550:     if($pid) {			# Parent process
  551: 	Debug("In parent process for execute_command");
  552: 	my @data = <CHILD>;	# Read the child's outupt...
  553: 	close CHILD;
  554: 	foreach my $output_line (@data) {
  555: 	    Debug("Adding $output_line");
  556: 	    $output .= $output_line; # Presumably has a \n on it.
  557: 	}
  558: 
  559:     } else {			# Child process
  560: 	close (STDERR);
  561: 	open  (STDERR, ">&STDOUT");# Combine stderr, and stdout...
  562: 	exec(@words);		# won't return.
  563:     }
  564:     return $output;
  565: }
  566: 
  567: 
  568: #   GetCertificate: Given a transaction that requires a certificate,
  569: #   this function will extract the certificate from the transaction
  570: #   request.  Note that at this point, the only concept of a certificate
  571: #   is the hostname to which we are connected.
  572: #
  573: #   Parameter:
  574: #      request   - The request sent by our client (this parameterization may
  575: #                  need to change when we really use a certificate granting
  576: #                  authority.
  577: #
  578: sub GetCertificate {
  579:     my $request = shift;
  580: 
  581:     return $clientip;
  582: }
  583: 
  584: #
  585: #   Return true if client is a manager.
  586: #
  587: sub isManager {
  588:     return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
  589: }
  590: #
  591: #   Return tru if client can do client functions
  592: #
  593: sub isClient {
  594:     return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
  595: }
  596: 
  597: 
  598: #
  599: #   ReadManagerTable: Reads in the current manager table. For now this is
  600: #                     done on each manager authentication because:
  601: #                     - These authentications are not frequent
  602: #                     - This allows dynamic changes to the manager table
  603: #                       without the need to signal to the lond.
  604: #
  605: sub ReadManagerTable {
  606: 
  607:     &Debug("Reading manager table");
  608:     #   Clean out the old table first..
  609: 
  610:    foreach my $key (keys %managers) {
  611:       delete $managers{$key};
  612:    }
  613: 
  614:    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
  615:    if (!open (MANAGERS, $tablename)) {
  616:        my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
  617:        if (&Apache::lonnet::is_LC_dns($hostname)) {
  618:            &logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
  619:        }
  620:        return;
  621:    }
  622:    while(my $host = <MANAGERS>) {
  623:       chomp($host);
  624:       if ($host =~ "^#") {                  # Comment line.
  625:          next;
  626:       }
  627:       if (!defined &Apache::lonnet::get_host_ip($host)) { # This is a non cluster member
  628: 	    #  The entry is of the form:
  629: 	    #    cluname:hostname
  630: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
  631: 	    #            the host key.
  632: 	    #  hostname- The dns name of the host.
  633: 	    #
  634:           my($cluname, $dnsname) = split(/:/, $host);
  635:           
  636:           my $ip = gethostbyname($dnsname);
  637:           if(defined($ip)) {                 # bad names don't deserve entry.
  638:             my $hostip = inet_ntoa($ip);
  639:             $managers{$hostip} = $cluname;
  640:             logthis('<font color="green"> registering manager '.
  641:                     "$dnsname as $cluname with $hostip </font>\n");
  642:          }
  643:       } else {
  644:          logthis('<font color="green"> existing host'." $host</font>\n");
  645:          $managers{&Apache::lonnet::get_host_ip($host)} = $host;  # Use info from cluster tab if cluster memeber
  646:       }
  647:    }
  648: }
  649: 
  650: #
  651: #  ValidManager: Determines if a given certificate represents a valid manager.
  652: #                in this primitive implementation, the 'certificate' is
  653: #                just the connecting loncapa client name.  This is checked
  654: #                against a valid client list in the configuration.
  655: #
  656: #                  
  657: sub ValidManager {
  658:     my $certificate = shift; 
  659: 
  660:     return isManager;
  661: }
  662: #
  663: #  CopyFile:  Called as part of the process of installing a 
  664: #             new configuration file.  This function copies an existing
  665: #             file to a backup file.
  666: # Parameters:
  667: #     oldfile  - Name of the file to backup.
  668: #     newfile  - Name of the backup file.
  669: # Return:
  670: #     0   - Failure (errno has failure reason).
  671: #     1   - Success.
  672: #
  673: sub CopyFile {
  674: 
  675:     my ($oldfile, $newfile) = @_;
  676: 
  677:     if (! copy($oldfile,$newfile)) {
  678:         return 0;
  679:     }
  680:     chmod(0660, $newfile);
  681:     return 1;
  682: }
  683: #
  684: #  Host files are passed out with externally visible host IPs.
  685: #  If, for example, we are behind a fire-wall or NAT host, our 
  686: #  internally visible IP may be different than the externally
  687: #  visible IP.  Therefore, we always adjust the contents of the
  688: #  host file so that the entry for ME is the IP that we believe
  689: #  we have.  At present, this is defined as the entry that
  690: #  DNS has for us.  If by some chance we are not able to get a
  691: #  DNS translation for us, then we assume that the host.tab file
  692: #  is correct.  
  693: #    BUGBUGBUG - in the future, we really should see if we can
  694: #       easily query the interface(s) instead.
  695: # Parameter(s):
  696: #     contents    - The contents of the host.tab to check.
  697: # Returns:
  698: #     newcontents - The adjusted contents.
  699: #
  700: #
  701: sub AdjustHostContents {
  702:     my $contents  = shift;
  703:     my $adjusted;
  704:     my $me        = $perlvar{'lonHostID'};
  705: 
  706:     foreach my $line (split(/\n/,$contents)) {
  707: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/) ||
  708:              ($line =~ /^\s*\^/))) {
  709: 	    chomp($line);
  710: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
  711: 	    if ($id eq $me) {
  712: 		my $ip = gethostbyname($name);
  713: 		my $ipnew = inet_ntoa($ip);
  714: 		$ip = $ipnew;
  715: 		#  Reconstruct the host line and append to adjusted:
  716: 		
  717: 		my $newline = "$id:$domain:$role:$name:$ip";
  718: 		if($maxcon ne "") { # Not all hosts have loncnew tuning params
  719: 		    $newline .= ":$maxcon:$idleto:$mincon";
  720: 		}
  721: 		$adjusted .= $newline."\n";
  722: 		
  723: 	    } else {		# Not me, pass unmodified.
  724: 		$adjusted .= $line."\n";
  725: 	    }
  726: 	} else {                  # Blank or comment never re-written.
  727: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
  728: 	}
  729:     }
  730:     return $adjusted;
  731: }
  732: #
  733: #   InstallFile: Called to install an administrative file:
  734: #       - The file is created int a temp directory called <name>.tmp
  735: #       - lcinstall file is called to install the file.
  736: #         since the web app has no direct write access to the table directory
  737: #
  738: #  Parameters:
  739: #       Name of the file
  740: #       File Contents.
  741: #  Return:
  742: #      nonzero - success.
  743: #      0       - failure and $! has an errno.
  744: # Assumptions:
  745: #    File installtion is a relatively infrequent
  746: #
  747: sub InstallFile {
  748: 
  749:     my ($Filename, $Contents) = @_;
  750: #     my $TempFile = $Filename.".tmp";
  751:     my $exedir = $perlvar{'lonDaemons'};
  752:     my $tmpdir = $exedir.'/tmp/';
  753:     my $TempFile = $tmpdir."TempTableFile.tmp";
  754: 
  755:     #  Open the file for write:
  756: 
  757:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
  758:     if(!(defined $fh)) {
  759: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
  760: 	return 0;
  761:     }
  762:     #  write the contents of the file:
  763: 
  764:     print $fh ($Contents); 
  765:     $fh->close;			# In case we ever have a filesystem w. locking
  766: 
  767:     chmod(0664, $TempFile);	# Everyone can write it.
  768: 
  769:     # Use lcinstall file to put the file in the table directory...
  770: 
  771:     &Debug("Opening pipe to $exedir/lcinstallfile $TempFile $Filename");
  772:     my $pf = IO::File->new("| $exedir/lcinstallfile   $TempFile $Filename > $exedir/logs/lcinstallfile.log");
  773:     close $pf;
  774:     my $err = $?;
  775:     &Debug("Status is $err");
  776:     if ($err != 0) {
  777: 	my $msg = $err;
  778: 	if ($err < @installerrors) {
  779: 	    $msg = $installerrors[$err];
  780: 	}
  781: 	&logthis("Install failed for table file $Filename : $msg");
  782: 	return 0;
  783:     }
  784: 
  785:     # Remove the temp file:
  786: 
  787:     unlink($TempFile);
  788: 
  789:     return 1;
  790: }
  791: 
  792: 
  793: #
  794: #   ConfigFileFromSelector: converts a configuration file selector
  795: #                 into a configuration file pathname.
  796: #                 Supports the following file selectors: 
  797: #                 hosts, domain, dns_hosts, dns_domain  
  798: #
  799: #
  800: #  Parameters:
  801: #      selector  - Configuration file selector.
  802: #  Returns:
  803: #      Full path to the file or undef if the selector is invalid.
  804: #
  805: sub ConfigFileFromSelector {
  806:     my $selector   = shift;
  807:     my $tablefile;
  808: 
  809:     if ($selector eq 'loncapaCAcrl') {
  810:         my $tabledir = $perlvar{'lonCertificateDirectory'};
  811:         if (-d $tabledir) {
  812:             $tablefile =  $tabledir.'/'.$selector.'.pem';
  813:         }
  814:     } else {
  815:         my $tabledir = $perlvar{'lonTabDir'}.'/';
  816:         if (($selector eq "hosts") || ($selector eq "domain") || 
  817:             ($selector eq "dns_hosts") || ($selector eq "dns_domain")) {
  818: 	    $tablefile =  $tabledir.$selector.'.tab';
  819:         }
  820:     }
  821:     return $tablefile;
  822: }
  823: #
  824: #   PushFile:  Called to do an administrative push of a file.
  825: #              - Ensure the file being pushed is one we support.
  826: #              - Backup the old file to <filename.saved>
  827: #              - Separate the contents of the new file out from the
  828: #                rest of the request.
  829: #              - Write the new file.
  830: #  Parameter:
  831: #     Request - The entire user request.  This consists of a : separated
  832: #               string pushfile:tablename:contents.
  833: #     NOTE:  The contents may have :'s in it as well making things a bit
  834: #            more interesting... but not much.
  835: #  Returns:
  836: #     String to send to client ("ok" or "refused" if bad file).
  837: #
  838: sub PushFile {
  839:     my $request = shift;
  840:     my ($command, $filename, $contents) = split(":", $request, 3);
  841:     &Debug("PushFile");
  842:     
  843:     #  At this point in time, pushes for only the following tables and
  844:     #  CRL file are supported:
  845:     #   hosts.tab  ($filename eq host).
  846:     #   domain.tab ($filename eq domain).
  847:     #   dns_hosts.tab ($filename eq dns_host).
  848:     #   dns_domain.tab ($filename eq dns_domain).
  849:     #   loncapaCAcrl.pem ($filename eq loncapaCAcrl).
  850:     # Construct the destination filename or reject the request.
  851:     #
  852:     # lonManage is supposed to ensure this, however this session could be
  853:     # part of some elaborate spoof that managed somehow to authenticate.
  854:     #
  855: 
  856: 
  857:     my $tablefile = ConfigFileFromSelector($filename);
  858:     if(! (defined $tablefile)) {
  859: 	return "refused";
  860:     }
  861: 
  862:     #  If the file being pushed is the host file, we adjust the entry for ourself so that the
  863:     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
  864:     #  to conceive of conditions where we don't have a DNS entry locally.  This is possible in a 
  865:     #  network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
  866:     #  that possibilty.
  867: 
  868:     if($filename eq "host") {
  869: 	$contents = AdjustHostContents($contents);
  870:     } elsif (($filename eq 'dns_hosts') || ($filename eq 'dns_domain') ||
  871:              ($filename eq 'loncapaCAcrl')) {
  872:         if ($contents eq '') {
  873:             &logthis('<font color="red"> Pushfile: unable to install '
  874:                     .$tablefile." - no data received from push. </font>");
  875:             return 'error: push had no data';
  876:         }
  877:         if (&Apache::lonnet::get_host_ip($clientname)) {
  878:             my $clienthost = &Apache::lonnet::hostname($clientname);
  879:             if ($managers{$clientip} eq $clientname) {
  880:                 my $clientprotocol = $Apache::lonnet::protocol{$clientname};
  881:                 $clientprotocol = 'http' if ($clientprotocol ne 'https');
  882:                 my $url;
  883:                 if ($filename eq 'loncapaCAcrl') {
  884:                     $url = '/adm/dns/loncapaCRL';
  885:                 } else {
  886:                     $url = '/adm/'.$filename;
  887:                     $url =~ s{_}{/};
  888:                 }
  889:                 my $request=new HTTP::Request('GET',"$clientprotocol://$clienthost$url");
  890:                 my $response = LONCAPA::LWPReq::makerequest($clientname,$request,'',\%perlvar,60,0);
  891:                 if ($response->is_error()) {
  892:                     &logthis('<font color="red"> Pushfile: unable to install '
  893:                             .$tablefile." - error attempting to pull data. </font>");
  894:                     return 'error: pull failed';
  895:                 } else {
  896:                     my $result = $response->content;
  897:                     chomp($result);
  898:                     unless ($result eq $contents) {
  899:                         &logthis('<font color="red"> Pushfile: unable to install '
  900:                                 .$tablefile." - pushed data and pulled data differ. </font>");
  901:                         my $pushleng = length($contents);
  902:                         my $pullleng = length($result);
  903:                         if ($pushleng != $pullleng) {
  904:                             return "error: $pushleng vs $pullleng bytes";
  905:                         } else {
  906:                             return "error: mismatch push and pull";
  907:                         }
  908:                     }
  909:                 }
  910:             }
  911:         }
  912:     }
  913: 
  914:     #  Install the new file:
  915: 
  916:     &logthis("Installing new $tablefile contents:\n$contents");
  917:     if(!InstallFile($tablefile, $contents)) {
  918: 	&logthis('<font color="red"> Pushfile: unable to install '
  919: 	 .$tablefile." $! </font>");
  920: 	return "error:$!";
  921:     } else {
  922: 	&logthis('<font color="green"> Installed new '.$tablefile
  923: 		 ." - transaction by: $clientname ($clientip)</font>");
  924:         my $adminmail = $perlvar{'lonAdmEMail'};
  925:         my $admindom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
  926:         if ($admindom ne '') {
  927:             my %domconfig =
  928:                 &Apache::lonnet::get_dom('configuration',['contacts'],$admindom);
  929:             if (ref($domconfig{'contacts'}) eq 'HASH') {
  930:                 if ($domconfig{'contacts'}{'adminemail'} ne '') {
  931:                     $adminmail = $domconfig{'contacts'}{'adminemail'};
  932:                 }
  933:             }
  934:         }
  935:         if ($adminmail =~ /^[^\@]+\@[^\@]+$/) {
  936:             my $msg = new Mail::Send;
  937:             $msg->to($adminmail);
  938:             $msg->subject('LON-CAPA DNS update on '.$perlvar{'lonHostID'});
  939:             $msg->add('Content-type','text/plain; charset=UTF-8');
  940:             if (my $fh = $msg->open()) {
  941:                 print $fh 'Update to '.$tablefile.' from Cluster Manager '.
  942:                           "$clientname ($clientip)\n";
  943:                 $fh->close;
  944:             }
  945:         }
  946:     }
  947: 
  948:     #  Indicate success:
  949:  
  950:     return "ok";
  951: 
  952: }
  953: 
  954: #
  955: #  Called to re-init either lonc or lond.
  956: #
  957: #  Parameters:
  958: #    request   - The full request by the client.  This is of the form
  959: #                reinit:<process>  
  960: #                where <process> is allowed to be either of 
  961: #                lonc or lond
  962: #
  963: #  Returns:
  964: #     The string to be sent back to the client either:
  965: #   ok         - Everything worked just fine.
  966: #   error:why  - There was a failure and why describes the reason.
  967: #
  968: #
  969: sub ReinitProcess {
  970:     my $request = shift;
  971: 
  972: 
  973:     # separate the request (reinit) from the process identifier and
  974:     # validate it producing the name of the .pid file for the process.
  975:     #
  976:     #
  977:     my ($junk, $process) = split(":", $request);
  978:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
  979:     if($process eq 'lonc') {
  980: 	$processpidfile = $processpidfile."lonc.pid";
  981: 	if (!open(PIDFILE, "< $processpidfile")) {
  982: 	    return "error:Open failed for $processpidfile";
  983: 	}
  984: 	my $loncpid = <PIDFILE>;
  985: 	close(PIDFILE);
  986: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
  987: 		."</font>");
  988: 	kill("USR2", $loncpid);
  989:     } elsif ($process eq 'lond') {
  990: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
  991: 	&UpdateHosts;			# Lond is us!!
  992:     } else {
  993: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
  994: 		 ."</font>");
  995: 	return "error:Invalid process identifier $process";
  996:     }
  997:     return 'ok';
  998: }
  999: #   Validate a line in a configuration file edit script:
 1000: #   Validation includes:
 1001: #     - Ensuring the command is valid.
 1002: #     - Ensuring the command has sufficient parameters
 1003: #   Parameters:
 1004: #     scriptline - A line to validate (\n has been stripped for what it's worth).
 1005: #
 1006: #   Return:
 1007: #      0     - Invalid scriptline.
 1008: #      1     - Valid scriptline
 1009: #  NOTE:
 1010: #     Only the command syntax is checked, not the executability of the
 1011: #     command.
 1012: #
 1013: sub isValidEditCommand {
 1014:     my $scriptline = shift;
 1015: 
 1016:     #   Line elements are pipe separated:
 1017: 
 1018:     my ($command, $key, $newline)  = split(/\|/, $scriptline);
 1019:     &logthis('<font color="green"> isValideditCommand checking: '.
 1020: 	     "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
 1021:     
 1022:     if ($command eq "delete") {
 1023: 	#
 1024: 	#   key with no newline.
 1025: 	#
 1026: 	if( ($key eq "") || ($newline ne "")) {
 1027: 	    return 0;		# Must have key but no newline.
 1028: 	} else {
 1029: 	    return 1;		# Valid syntax.
 1030: 	}
 1031:     } elsif ($command eq "replace") {
 1032: 	#
 1033: 	#   key and newline:
 1034: 	#
 1035: 	if (($key eq "") || ($newline eq "")) {
 1036: 	    return 0;
 1037: 	} else {
 1038: 	    return 1;
 1039: 	}
 1040:     } elsif ($command eq "append") {
 1041: 	if (($key ne "") && ($newline eq "")) {
 1042: 	    return 1;
 1043: 	} else {
 1044: 	    return 0;
 1045: 	}
 1046:     } else {
 1047: 	return 0;		# Invalid command.
 1048:     }
 1049:     return 0;			# Should not get here!!!
 1050: }
 1051: #
 1052: #   ApplyEdit - Applies an edit command to a line in a configuration 
 1053: #               file.  It is the caller's responsiblity to validate the
 1054: #               edit line.
 1055: #   Parameters:
 1056: #      $directive - A single edit directive to apply.  
 1057: #                   Edit directives are of the form:
 1058: #                  append|newline      - Appends a new line to the file.
 1059: #                  replace|key|newline - Replaces the line with key value 'key'
 1060: #                  delete|key          - Deletes the line with key value 'key'.
 1061: #      $editor   - A config file editor object that contains the
 1062: #                  file being edited.
 1063: #
 1064: sub ApplyEdit {
 1065: 
 1066:     my ($directive, $editor) = @_;
 1067: 
 1068:     # Break the directive down into its command and its parameters
 1069:     # (at most two at this point.  The meaning of the parameters, if in fact
 1070:     #  they exist depends on the command).
 1071: 
 1072:     my ($command, $p1, $p2) = split(/\|/, $directive);
 1073: 
 1074:     if($command eq "append") {
 1075: 	$editor->Append($p1);	          # p1 - key p2 null.
 1076:     } elsif ($command eq "replace") {
 1077: 	$editor->ReplaceLine($p1, $p2);   # p1 - key p2 = newline.
 1078:     } elsif ($command eq "delete") {
 1079: 	$editor->DeleteLine($p1);         # p1 - key p2 null.
 1080:     } else {			          # Should not get here!!!
 1081: 	die "Invalid command given to ApplyEdit $command"
 1082:     }
 1083: }
 1084: #
 1085: # AdjustOurHost:
 1086: #           Adjusts a host file stored in a configuration file editor object
 1087: #           for the true IP address of this host. This is necessary for hosts
 1088: #           that live behind a firewall.
 1089: #           Those hosts have a publicly distributed IP of the firewall, but
 1090: #           internally must use their actual IP.  We assume that a given
 1091: #           host only has a single IP interface for now.
 1092: # Formal Parameters:
 1093: #     editor   - The configuration file editor to adjust.  This
 1094: #                editor is assumed to contain a hosts.tab file.
 1095: # Strategy:
 1096: #    - Figure out our hostname.
 1097: #    - Lookup the entry for this host.
 1098: #    - Modify the line to contain our IP
 1099: #    - Do a replace for this host.
 1100: sub AdjustOurHost {
 1101:     my $editor        = shift;
 1102: 
 1103:     # figure out who I am.
 1104: 
 1105:     my $myHostName    = $perlvar{'lonHostID'}; # LonCAPA hostname.
 1106: 
 1107:     #  Get my host file entry.
 1108: 
 1109:     my $ConfigLine    = $editor->Find($myHostName);
 1110:     if(! (defined $ConfigLine)) {
 1111: 	die "AdjustOurHost - no entry for me in hosts file $myHostName";
 1112:     }
 1113:     # figure out my IP:
 1114:     #   Use the config line to get my hostname.
 1115:     #   Use gethostbyname to translate that into an IP address.
 1116:     #
 1117:     my ($id,$domain,$role,$name,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
 1118:     #
 1119:     #  Reassemble the config line from the elements in the list.
 1120:     #  Note that if the loncnew items were not present before, they will
 1121:     #  be now even if they would be empty
 1122:     #
 1123:     my $newConfigLine = $id;
 1124:     foreach my $item ($domain, $role, $name, $maxcon, $idleto, $mincon) {
 1125: 	$newConfigLine .= ":".$item;
 1126:     }
 1127:     #  Replace the line:
 1128: 
 1129:     $editor->ReplaceLine($id, $newConfigLine);
 1130:     
 1131: }
 1132: #
 1133: #   ReplaceConfigFile:
 1134: #              Replaces a configuration file with the contents of a
 1135: #              configuration file editor object.
 1136: #              This is done by:
 1137: #              - Copying the target file to <filename>.old
 1138: #              - Writing the new file to <filename>.tmp
 1139: #              - Moving <filename.tmp>  -> <filename>
 1140: #              This laborious process ensures that the system is never without
 1141: #              a configuration file that's at least valid (even if the contents
 1142: #              may be dated).
 1143: #   Parameters:
 1144: #        filename   - Name of the file to modify... this is a full path.
 1145: #        editor     - Editor containing the file.
 1146: #
 1147: sub ReplaceConfigFile {
 1148:     
 1149:     my ($filename, $editor) = @_;
 1150: 
 1151:     CopyFile ($filename, $filename.".old");
 1152: 
 1153:     my $contents  = $editor->Get(); # Get the contents of the file.
 1154: 
 1155:     InstallFile($filename, $contents);
 1156: }
 1157: #   
 1158: #
 1159: #   Called to edit a configuration table  file
 1160: #   Parameters:
 1161: #      request           - The entire command/request sent by lonc or lonManage
 1162: #   Return:
 1163: #      The reply to send to the client.
 1164: #
 1165: sub EditFile {
 1166:     my $request = shift;
 1167: 
 1168:     #  Split the command into it's pieces:  edit:filetype:script
 1169: 
 1170:     my ($cmd, $filetype, $script) = split(/:/, $request,3);	# : in script
 1171: 
 1172:     #  Check the pre-coditions for success:
 1173: 
 1174:     if($cmd != "edit") {	# Something is amiss afoot alack.
 1175: 	return "error:edit request detected, but request != 'edit'\n";
 1176:     }
 1177:     if( ($filetype ne "hosts")  &&
 1178: 	($filetype ne "domain")) {
 1179: 	return "error:edit requested with invalid file specifier: $filetype \n";
 1180:     }
 1181: 
 1182:     #   Split the edit script and check it's validity.
 1183: 
 1184:     my @scriptlines = split(/\n/, $script);  # one line per element.
 1185:     my $linecount   = scalar(@scriptlines);
 1186:     for(my $i = 0; $i < $linecount; $i++) {
 1187: 	chomp($scriptlines[$i]);
 1188: 	if(!isValidEditCommand($scriptlines[$i])) {
 1189: 	    return "error:edit with bad script line: '$scriptlines[$i]' \n";
 1190: 	}
 1191:     }
 1192: 
 1193:     #   Execute the edit operation.
 1194:     #   - Create a config file editor for the appropriate file and 
 1195:     #   - execute each command in the script:
 1196:     #
 1197:     my $configfile = ConfigFileFromSelector($filetype);
 1198:     if (!(defined $configfile)) {
 1199: 	return "refused\n";
 1200:     }
 1201:     my $editor = ConfigFileEdit->new($configfile);
 1202: 
 1203:     for (my $i = 0; $i < $linecount; $i++) {
 1204: 	ApplyEdit($scriptlines[$i], $editor);
 1205:     }
 1206:     # If the file is the host file, ensure that our host is
 1207:     # adjusted to have our ip:
 1208:     #
 1209:     if($filetype eq "host") {
 1210: 	AdjustOurHost($editor);
 1211:     }
 1212:     #  Finally replace the current file with our file.
 1213:     #
 1214:     ReplaceConfigFile($configfile, $editor);
 1215: 
 1216:     return "ok\n";
 1217: }
 1218: 
 1219: #   read_profile
 1220: #
 1221: #   Returns a set of specific entries from a user's profile file.
 1222: #   this is a utility function that is used by both get_profile_entry and
 1223: #   get_profile_entry_encrypted.
 1224: #
 1225: # Parameters:
 1226: #    udom       - Domain in which the user exists.
 1227: #    uname      - User's account name (loncapa account)
 1228: #    namespace  - The profile namespace to open.
 1229: #    what       - A set of & separated queries.
 1230: # Returns:
 1231: #    If all ok: - The string that needs to be shipped back to the user.
 1232: #    If failure - A string that starts with error: followed by the failure
 1233: #                 reason.. note that this probabyl gets shipped back to the
 1234: #                 user as well.
 1235: #
 1236: sub read_profile {
 1237:     my ($udom, $uname, $namespace, $what) = @_;
 1238:     
 1239:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 1240: 				 &GDBM_READER());
 1241:     if ($hashref) {
 1242:         my @queries=split(/\&/,$what);
 1243:         if ($namespace eq 'roles') {
 1244:             @queries = map { &unescape($_); } @queries; 
 1245:         }
 1246:         my $qresult='';
 1247: 	
 1248: 	for (my $i=0;$i<=$#queries;$i++) {
 1249: 	    $qresult.="$hashref->{$queries[$i]}&";    # Presumably failure gives empty string.
 1250: 	}
 1251: 	$qresult=~s/\&$//;              # Remove trailing & from last lookup.
 1252: 	if (&untie_user_hash($hashref)) {
 1253: 	    return $qresult;
 1254: 	} else {
 1255: 	    return "error: ".($!+0)." untie (GDBM) Failed";
 1256: 	}
 1257:     } else {
 1258: 	if ($!+0 == 2) {
 1259: 	    return "error:No such file or GDBM reported bad block error";
 1260: 	} else {
 1261: 	    return "error: ".($!+0)." tie (GDBM) Failed";
 1262: 	}
 1263:     }
 1264: 
 1265: }
 1266: #--------------------- Request Handlers --------------------------------------------
 1267: #
 1268: #   By convention each request handler registers itself prior to the sub 
 1269: #   declaration:
 1270: #
 1271: 
 1272: #++
 1273: #
 1274: #  Handles ping requests.
 1275: #  Parameters:
 1276: #      $cmd    - the actual keyword that invoked us.
 1277: #      $tail   - the tail of the request that invoked us.
 1278: #      $replyfd- File descriptor connected to the client
 1279: #  Implicit Inputs:
 1280: #      $currenthostid - Global variable that carries the name of the host we are
 1281: #                       known as.
 1282: #  Returns:
 1283: #      1       - Ok to continue processing.
 1284: #      0       - Program should exit.
 1285: #  Side effects:
 1286: #      Reply information is sent to the client.
 1287: sub ping_handler {
 1288:     my ($cmd, $tail, $client) = @_;
 1289:     Debug("$cmd $tail $client .. $currenthostid:");
 1290:    
 1291:     Reply( $client,\$currenthostid,"$cmd:$tail");
 1292:    
 1293:     return 1;
 1294: }
 1295: &register_handler("ping", \&ping_handler, 0, 1, 1);       # Ping unencoded, client or manager.
 1296: 
 1297: #++
 1298: #
 1299: # Handles pong requests.  Pong replies with our current host id, and
 1300: #                         the results of a ping sent to us via our lonc.
 1301: #
 1302: # Parameters:
 1303: #      $cmd    - the actual keyword that invoked us.
 1304: #      $tail   - the tail of the request that invoked us.
 1305: #      $replyfd- File descriptor connected to the client
 1306: #  Implicit Inputs:
 1307: #      $currenthostid - Global variable that carries the name of the host we are
 1308: #                       connected to.
 1309: #  Returns:
 1310: #      1       - Ok to continue processing.
 1311: #      0       - Program should exit.
 1312: #  Side effects:
 1313: #      Reply information is sent to the client.
 1314: sub pong_handler {
 1315:     my ($cmd, $tail, $replyfd) = @_;
 1316: 
 1317:     my $reply=&Apache::lonnet::reply("ping",$clientname);
 1318:     &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail"); 
 1319:     return 1;
 1320: }
 1321: &register_handler("pong", \&pong_handler, 0, 1, 1);       # Pong unencoded, client or manager
 1322: 
 1323: #++
 1324: #      Called to establish an encrypted session key with the remote client.
 1325: #      Note that with secure lond, in most cases this function is never
 1326: #      invoked.  Instead, the secure session key is established either
 1327: #      via a local file that's locked down tight and only lives for a short
 1328: #      time, or via an ssl tunnel...and is generated from a bunch-o-random
 1329: #      bits from /dev/urandom, rather than the predictable pattern used by
 1330: #      by this sub.  This sub is only used in the old-style insecure
 1331: #      key negotiation.
 1332: # Parameters:
 1333: #      $cmd    - the actual keyword that invoked us.
 1334: #      $tail   - the tail of the request that invoked us.
 1335: #      $replyfd- File descriptor connected to the client
 1336: #  Implicit Inputs:
 1337: #      $currenthostid - Global variable that carries the name of the host
 1338: #                       known as.
 1339: #      $clientname    - Global variable that carries the name of the host we're connected to.
 1340: #  Returns:
 1341: #      1       - Ok to continue processing.
 1342: #      0       - Program should exit.
 1343: #  Implicit Outputs:
 1344: #      Reply information is sent to the client.
 1345: #      $cipher is set with a reference to a new IDEA encryption object.
 1346: #
 1347: sub establish_key_handler {
 1348:     my ($cmd, $tail, $replyfd) = @_;
 1349: 
 1350:     my $buildkey=time.$$.int(rand 100000);
 1351:     $buildkey=~tr/1-6/A-F/;
 1352:     $buildkey=int(rand 100000).$buildkey.int(rand 100000);
 1353:     my $key=$currenthostid.$clientname;
 1354:     $key=~tr/a-z/A-Z/;
 1355:     $key=~tr/G-P/0-9/;
 1356:     $key=~tr/Q-Z/0-9/;
 1357:     $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
 1358:     $key=substr($key,0,32);
 1359:     my $cipherkey=pack("H32",$key);
 1360:     $cipher=new IDEA $cipherkey;
 1361:     &Reply($replyfd, \$buildkey, "$cmd:$tail"); 
 1362:    
 1363:     return 1;
 1364: 
 1365: }
 1366: &register_handler("ekey", \&establish_key_handler, 0, 1,1);
 1367: 
 1368: #     Handler for the load command.  Returns the current system load average
 1369: #     to the requestor.
 1370: #
 1371: # Parameters:
 1372: #      $cmd    - the actual keyword that invoked us.
 1373: #      $tail   - the tail of the request that invoked us.
 1374: #      $replyfd- File descriptor connected to the client
 1375: #  Implicit Inputs:
 1376: #      $currenthostid - Global variable that carries the name of the host
 1377: #                       known as.
 1378: #      $clientname    - Global variable that carries the name of the host we're connected to.
 1379: #  Returns:
 1380: #      1       - Ok to continue processing.
 1381: #      0       - Program should exit.
 1382: #  Side effects:
 1383: #      Reply information is sent to the client.
 1384: sub load_handler {
 1385:     my ($cmd, $tail, $replyfd) = @_;
 1386: 
 1387: 
 1388: 
 1389:    # Get the load average from /proc/loadavg and calculate it as a percentage of
 1390:    # the allowed load limit as set by the perl global variable lonLoadLim
 1391: 
 1392:     my $loadavg;
 1393:     my $loadfile=IO::File->new('/proc/loadavg');
 1394:    
 1395:     $loadavg=<$loadfile>;
 1396:     $loadavg =~ s/\s.*//g;                      # Extract the first field only.
 1397:    
 1398:     my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
 1399: 
 1400:     &Reply( $replyfd, \$loadpercent, "$cmd:$tail");
 1401:    
 1402:     return 1;
 1403: }
 1404: &register_handler("load", \&load_handler, 0, 1, 0);
 1405: 
 1406: #
 1407: #   Process the userload request.  This sub returns to the client the current
 1408: #  user load average.  It can be invoked either by clients or managers.
 1409: #
 1410: # Parameters:
 1411: #      $cmd    - the actual keyword that invoked us.
 1412: #      $tail   - the tail of the request that invoked us.
 1413: #      $replyfd- File descriptor connected to the client
 1414: #  Implicit Inputs:
 1415: #      $currenthostid - Global variable that carries the name of the host
 1416: #                       known as.
 1417: #      $clientname    - Global variable that carries the name of the host we're connected to.
 1418: #  Returns:
 1419: #      1       - Ok to continue processing.
 1420: #      0       - Program should exit
 1421: # Implicit inputs:
 1422: #     whatever the userload() function requires.
 1423: #  Implicit outputs:
 1424: #     the reply is written to the client.
 1425: #
 1426: sub user_load_handler {
 1427:     my ($cmd, $tail, $replyfd) = @_;
 1428: 
 1429:     my $userloadpercent=&Apache::lonnet::userload();
 1430:     &Reply($replyfd, \$userloadpercent, "$cmd:$tail");
 1431:     
 1432:     return 1;
 1433: }
 1434: &register_handler("userload", \&user_load_handler, 0, 1, 0);
 1435: 
 1436: #   Process a request for the authorization type of a user:
 1437: #   (userauth).
 1438: #
 1439: # Parameters:
 1440: #      $cmd    - the actual keyword that invoked us.
 1441: #      $tail   - the tail of the request that invoked us.
 1442: #      $replyfd- File descriptor connected to the client
 1443: #  Returns:
 1444: #      1       - Ok to continue processing.
 1445: #      0       - Program should exit
 1446: # Implicit outputs:
 1447: #    The user authorization type is written to the client.
 1448: #
 1449: sub user_authorization_type {
 1450:     my ($cmd, $tail, $replyfd) = @_;
 1451:    
 1452:     my $userinput = "$cmd:$tail";
 1453:    
 1454:     #  Pull the domain and username out of the command tail.
 1455:     # and call get_auth_type to determine the authentication type.
 1456:    
 1457:     my ($udom,$uname)=split(/:/,$tail);
 1458:     my $result = &get_auth_type($udom, $uname);
 1459:     if($result eq "nouser") {
 1460: 	&Failure( $replyfd, "unknown_user\n", $userinput);
 1461:     } else {
 1462: 	#
 1463: 	# We only want to pass the second field from get_auth_type
 1464: 	# for ^krb.. otherwise we'll be handing out the encrypted
 1465: 	# password for internals e.g.
 1466: 	#
 1467: 	my ($type,$otherinfo) = split(/:/,$result);
 1468: 	if($type =~ /^krb/) {
 1469: 	    $type = $result;
 1470: 	} else {
 1471:             $type .= ':';
 1472:         }
 1473: 	&Reply( $replyfd, \$type, $userinput);
 1474:     }
 1475:   
 1476:     return 1;
 1477: }
 1478: &register_handler("currentauth", \&user_authorization_type, 1, 1, 0);
 1479: 
 1480: #   Process a request by a manager to push a hosts or domain table 
 1481: #   to us.  We pick apart the command and pass it on to the subs
 1482: #   that already exist to do this.
 1483: #
 1484: # Parameters:
 1485: #      $cmd    - the actual keyword that invoked us.
 1486: #      $tail   - the tail of the request that invoked us.
 1487: #      $client - File descriptor connected to the client
 1488: #  Returns:
 1489: #      1       - Ok to continue processing.
 1490: #      0       - Program should exit
 1491: # Implicit Output:
 1492: #    a reply is written to the client.
 1493: sub push_file_handler {
 1494:     my ($cmd, $tail, $client) = @_;
 1495:     &Debug("In push file handler");
 1496:     my $userinput = "$cmd:$tail";
 1497: 
 1498:     # At this time we only know that the IP of our partner is a valid manager
 1499:     # the code below is a hook to do further authentication (e.g. to resolve
 1500:     # spoofing).
 1501: 
 1502:     my $cert = &GetCertificate($userinput);
 1503:     if(&ValidManager($cert)) {
 1504: 	&Debug("Valid manager: $client");
 1505: 
 1506: 	# Now presumably we have the bona fides of both the peer host and the
 1507: 	# process making the request.
 1508:       
 1509: 	my $reply = &PushFile($userinput);
 1510: 	&Reply($client, \$reply, $userinput);
 1511: 
 1512:     } else {
 1513: 	&logthis("push_file_handler $client is not valid");
 1514: 	&Failure( $client, "refused\n", $userinput);
 1515:     } 
 1516:     return 1;
 1517: }
 1518: &register_handler("pushfile", \&push_file_handler, 1, 0, 1);
 1519: 
 1520: # The du_handler routine should be considered obsolete and is retained
 1521: # for communication with legacy servers.  Please see the du2_handler.
 1522: #
 1523: #   du  - list the disk usage of a directory recursively. 
 1524: #    
 1525: #   note: stolen code from the ls file handler
 1526: #   under construction by Rick Banghart 
 1527: #    .
 1528: # Parameters:
 1529: #    $cmd        - The command that dispatched us (du).
 1530: #    $ududir     - The directory path to list... I'm not sure what this
 1531: #                  is relative as things like ls:. return e.g.
 1532: #                  no_such_dir.
 1533: #    $client     - Socket open on the client.
 1534: # Returns:
 1535: #     1 - indicating that the daemon should not disconnect.
 1536: # Side Effects:
 1537: #   The reply is written to  $client.
 1538: #
 1539: sub du_handler {
 1540:     my ($cmd, $ududir, $client) = @_;
 1541:     ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
 1542:     my $userinput = "$cmd:$ududir";
 1543: 
 1544:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
 1545: 	&Failure($client,"refused\n","$cmd:$ududir");
 1546: 	return 1;
 1547:     }
 1548:     #  Since $ududir could have some nasties in it,
 1549:     #  we will require that ududir is a valid
 1550:     #  directory.  Just in case someone tries to
 1551:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
 1552:     #  etc.
 1553:     #
 1554:     if (-d $ududir) {
 1555: 	my $total_size=0;
 1556: 	my $code=sub { 
 1557: 	    if ($_=~/\.\d+\./) { return;} 
 1558: 	    if ($_=~/\.meta$/) { return;}
 1559: 	    if (-d $_)         { return;}
 1560: 	    $total_size+=(stat($_))[7];
 1561: 	};
 1562: 	chdir($ududir);
 1563: 	find($code,$ududir);
 1564: 	$total_size=int($total_size/1024);
 1565: 	&Reply($client,\$total_size,"$cmd:$ududir");
 1566:     } else {
 1567: 	&Failure($client, "bad_directory:$ududir\n","$cmd:$ududir"); 
 1568:     }
 1569:     return 1;
 1570: }
 1571: &register_handler("du", \&du_handler, 0, 1, 0);
 1572: 
 1573: # Please also see the du_handler, which is obsoleted by du2. 
 1574: # du2_handler differs from du_handler in that required path to directory
 1575: # provided by &propath() is prepended in the handler instead of on the 
 1576: # client side.
 1577: #
 1578: #   du2  - list the disk usage of a directory recursively.
 1579: #
 1580: # Parameters:
 1581: #    $cmd        - The command that dispatched us (du).
 1582: #    $tail       - The tail of the request that invoked us.
 1583: #                  $tail is a : separated list of the following:
 1584: #                   - $ududir - directory path to list (before prepending)
 1585: #                   - $getpropath = 1 if &propath() should prepend
 1586: #                   - $uname - username to use for &propath or user dir
 1587: #                   - $udom - domain to use for &propath or user dir
 1588: #                   All are escaped.
 1589: #    $client     - Socket open on the client.
 1590: # Returns:
 1591: #     1 - indicating that the daemon should not disconnect.
 1592: # Side Effects:
 1593: #   The reply is written to $client.
 1594: #
 1595: 
 1596: sub du2_handler {
 1597:     my ($cmd, $tail, $client) = @_;
 1598:     my ($ududir,$getpropath,$uname,$udom) = map { &unescape($_) } (split(/:/, $tail));
 1599:     my $userinput = "$cmd:$tail";
 1600:     if (($ududir=~/\.\./) || (($ududir!~m|^/home/httpd/|) && (!$getpropath))) {
 1601:         &Failure($client,"refused\n","$cmd:$tail");
 1602:         return 1;
 1603:     }
 1604:     if ($getpropath) {
 1605:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
 1606:             $ududir = &propath($udom,$uname).'/'.$ududir;
 1607:         } else {
 1608:             &Failure($client,"refused\n","$cmd:$tail");
 1609:             return 1;
 1610:         }
 1611:     }
 1612:     #  Since $ududir could have some nasties in it,
 1613:     #  we will require that ududir is a valid
 1614:     #  directory.  Just in case someone tries to
 1615:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
 1616:     #  etc.
 1617:     #
 1618:     if (-d $ududir) {
 1619:         my $total_size=0;
 1620:         my $code=sub {
 1621:             if ($_=~/\.\d+\./) { return;}
 1622:             if ($_=~/\.meta$/) { return;}
 1623:             if (-d $_)         { return;}
 1624:             $total_size+=(stat($_))[7];
 1625:         };
 1626:         chdir($ududir);
 1627:         find($code,$ududir);
 1628:         $total_size=int($total_size/1024);
 1629:         &Reply($client,\$total_size,"$cmd:$ududir");
 1630:     } else {
 1631:         &Failure($client, "bad_directory:$ududir\n","$cmd:$tail");
 1632:     }
 1633:     return 1;
 1634: }
 1635: &register_handler("du2", \&du2_handler, 0, 1, 0);
 1636: 
 1637: #
 1638: # The ls_handler routine should be considered obsolete and is retained
 1639: # for communication with legacy servers.  Please see the ls3_handler.
 1640: #
 1641: #   ls  - list the contents of a directory.  For each file in the
 1642: #    selected directory the filename followed by the full output of
 1643: #    the stat function is returned.  The returned info for each
 1644: #    file are separated by ':'.  The stat fields are separated by &'s.
 1645: #
 1646: #    If the requested path contains /../ or is:
 1647: #
 1648: #    1. for a directory, and the path does not begin with one of:
 1649: #        (a) /home/httpd/html/res/<domain>
 1650: #        (b) /home/httpd/html/userfiles/
 1651: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
 1652: #    or is:
 1653: #
 1654: #    2. for a file, and the path (after prepending) does not begin with one of:
 1655: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
 1656: #        (b) /home/httpd/html/res/<domain>/<username>/
 1657: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
 1658: #
 1659: #    the response will be "refused".
 1660: #
 1661: # Parameters:
 1662: #    $cmd        - The command that dispatched us (ls).
 1663: #    $ulsdir     - The directory path to list... I'm not sure what this
 1664: #                  is relative as things like ls:. return e.g.
 1665: #                  no_such_dir.
 1666: #    $client     - Socket open on the client.
 1667: # Returns:
 1668: #     1 - indicating that the daemon should not disconnect.
 1669: # Side Effects:
 1670: #   The reply is written to  $client.
 1671: #
 1672: sub ls_handler {
 1673:     # obsoleted by ls2_handler
 1674:     my ($cmd, $ulsdir, $client) = @_;
 1675: 
 1676:     my $userinput = "$cmd:$ulsdir";
 1677: 
 1678:     my $obs;
 1679:     my $rights;
 1680:     my $ulsout='';
 1681:     my $ulsfn;
 1682:     if ($ulsdir =~m{/\.\./}) {
 1683:         &Failure($client,"refused\n",$userinput);
 1684:         return 1;
 1685:     }
 1686:     if (-e $ulsdir) {
 1687: 	if(-d $ulsdir) {
 1688:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
 1689:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
 1690:                 &Failure($client,"refused\n",$userinput);
 1691:                 return 1;
 1692:             }
 1693: 	    if (opendir(LSDIR,$ulsdir)) {
 1694: 		while ($ulsfn=readdir(LSDIR)) {
 1695: 		    undef($obs);
 1696: 		    undef($rights); 
 1697: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1698: 		    #We do some obsolete checking here
 1699: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
 1700: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
 1701: 			my @obsolete=<FILE>;
 1702: 			foreach my $obsolete (@obsolete) {
 1703: 			    if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
 1704: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
 1705: 			}
 1706: 		    }
 1707: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
 1708: 		    if($obs eq '1') { $ulsout.="&1"; }
 1709: 		    else { $ulsout.="&0"; }
 1710: 		    if($rights eq '1') { $ulsout.="&1:"; }
 1711: 		    else { $ulsout.="&0:"; }
 1712: 		}
 1713: 		closedir(LSDIR);
 1714: 	    }
 1715: 	} else {
 1716:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
 1717:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
 1718:                 &Failure($client,"refused\n",$userinput);
 1719:                 return 1;
 1720:             }
 1721: 	    my @ulsstats=stat($ulsdir);
 1722: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1723: 	}
 1724:     } else {
 1725: 	$ulsout='no_such_dir';
 1726:     }
 1727:     if ($ulsout eq '') { $ulsout='empty'; }
 1728:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
 1729:     
 1730:     return 1;
 1731: 
 1732: }
 1733: &register_handler("ls", \&ls_handler, 0, 1, 0);
 1734: 
 1735: # The ls2_handler routine should be considered obsolete and is retained
 1736: # for communication with legacy servers.  Please see the ls3_handler.
 1737: # Please also see the ls_handler, which was itself obsoleted by ls2.
 1738: # ls2_handler differs from ls_handler in that it escapes its return 
 1739: # values before concatenating them together with ':'s.
 1740: #
 1741: #   ls2  - list the contents of a directory.  For each file in the
 1742: #    selected directory the filename followed by the full output of
 1743: #    the stat function is returned.  The returned info for each
 1744: #    file are separated by ':'.  The stat fields are separated by &'s.
 1745: #
 1746: #    If the requested path contains /../ or is:
 1747: #
 1748: #    1. for a directory, and the path does not begin with one of:
 1749: #        (a) /home/httpd/html/res/<domain>
 1750: #        (b) /home/httpd/html/userfiles/
 1751: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
 1752: #    or is:
 1753: #
 1754: #    2. for a file, and the path (after prepending) does not begin with one of:
 1755: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
 1756: #        (b) /home/httpd/html/res/<domain>/<username>/
 1757: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
 1758: #
 1759: #    the response will be "refused".
 1760: #
 1761: # Parameters:
 1762: #    $cmd        - The command that dispatched us (ls).
 1763: #    $ulsdir     - The directory path to list... I'm not sure what this
 1764: #                  is relative as things like ls:. return e.g.
 1765: #                  no_such_dir.
 1766: #    $client     - Socket open on the client.
 1767: # Returns:
 1768: #     1 - indicating that the daemon should not disconnect.
 1769: # Side Effects:
 1770: #   The reply is written to  $client.
 1771: #
 1772: sub ls2_handler {
 1773:     my ($cmd, $ulsdir, $client) = @_;
 1774: 
 1775:     my $userinput = "$cmd:$ulsdir";
 1776: 
 1777:     my $obs;
 1778:     my $rights;
 1779:     my $ulsout='';
 1780:     my $ulsfn;
 1781:     if ($ulsdir =~m{/\.\./}) {
 1782:         &Failure($client,"refused\n",$userinput);
 1783:         return 1;
 1784:     }
 1785:     if (-e $ulsdir) {
 1786:         if(-d $ulsdir) {
 1787:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
 1788:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
 1789:                 &Failure($client,"refused\n","$userinput");
 1790:                 return 1;
 1791:             }
 1792:             if (opendir(LSDIR,$ulsdir)) {
 1793:                 while ($ulsfn=readdir(LSDIR)) {
 1794:                     undef($obs);
 1795: 		    undef($rights); 
 1796:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1797:                     #We do some obsolete checking here
 1798:                     if(-e $ulsdir.'/'.$ulsfn.".meta") { 
 1799:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
 1800:                         my @obsolete=<FILE>;
 1801:                         foreach my $obsolete (@obsolete) {
 1802:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
 1803:                             if($obsolete =~ m|(<copyright>)(default)|) {
 1804:                                 $rights = 1;
 1805:                             }
 1806:                         }
 1807:                     }
 1808:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
 1809:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1810:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1811:                     $ulsout.= &escape($tmp).':';
 1812:                 }
 1813:                 closedir(LSDIR);
 1814:             }
 1815:         } else {
 1816:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
 1817:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
 1818:                 &Failure($client,"refused\n",$userinput);
 1819:                 return 1;
 1820:             }
 1821:             my @ulsstats=stat($ulsdir);
 1822:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1823:         }
 1824:     } else {
 1825:         $ulsout='no_such_dir';
 1826:    }
 1827:    if ($ulsout eq '') { $ulsout='empty'; }
 1828:    &Reply($client, \$ulsout, $userinput); # This supports debug logging.
 1829:    return 1;
 1830: }
 1831: &register_handler("ls2", \&ls2_handler, 0, 1, 0);
 1832: #
 1833: #   ls3  - list the contents of a directory.  For each file in the
 1834: #    selected directory the filename followed by the full output of
 1835: #    the stat function is returned.  The returned info for each
 1836: #    file are separated by ':'.  The stat fields are separated by &'s.
 1837: #
 1838: #    If the requested path (after prepending) contains /../ or is:
 1839: #
 1840: #    1. for a directory, and the path does not begin with one of:
 1841: #        (a) /home/httpd/html/res/<domain>
 1842: #        (b) /home/httpd/html/userfiles/
 1843: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
 1844: #        (d) /home/httpd/html/priv/<domain> and client is the homeserver
 1845: #
 1846: #    or is:
 1847: #
 1848: #    2. for a file, and the path (after prepending) does not begin with one of:
 1849: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
 1850: #        (b) /home/httpd/html/res/<domain>/<username>/
 1851: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
 1852: #        (d) /home/httpd/html/priv/<domain>/<username>/ and client is the homeserver
 1853: #
 1854: #    the response will be "refused".
 1855: #
 1856: # Parameters:
 1857: #    $cmd        - The command that dispatched us (ls).
 1858: #    $tail       - The tail of the request that invoked us.
 1859: #                  $tail is a : separated list of the following:
 1860: #                   - $ulsdir - directory path to list (before prepending)
 1861: #                   - $getpropath = 1 if &propath() should prepend
 1862: #                   - $getuserdir = 1 if path to user dir in lonUsers should
 1863: #                                     prepend
 1864: #                   - $alternate_root - path to prepend
 1865: #                   - $uname - username to use for &propath or user dir
 1866: #                   - $udom - domain to use for &propath or user dir
 1867: #            All of these except $getpropath and &getuserdir are escaped.    
 1868: #                  no_such_dir.
 1869: #    $client     - Socket open on the client.
 1870: # Returns:
 1871: #     1 - indicating that the daemon should not disconnect.
 1872: # Side Effects:
 1873: #   The reply is written to $client.
 1874: #
 1875: 
 1876: sub ls3_handler {
 1877:     my ($cmd, $tail, $client) = @_;
 1878:     my $userinput = "$cmd:$tail";
 1879:     my ($ulsdir,$getpropath,$getuserdir,$alternate_root,$uname,$udom) =
 1880:         split(/:/,$tail);
 1881:     if (defined($ulsdir)) {
 1882:         $ulsdir = &unescape($ulsdir);
 1883:     }
 1884:     if (defined($alternate_root)) {
 1885:         $alternate_root = &unescape($alternate_root);
 1886:     }
 1887:     if (defined($uname)) {
 1888:         $uname = &unescape($uname);
 1889:     }
 1890:     if (defined($udom)) {
 1891:         $udom = &unescape($udom);
 1892:     }
 1893: 
 1894:     my $dir_root = $perlvar{'lonDocRoot'};
 1895:     if (($getpropath) || ($getuserdir)) {
 1896:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
 1897:             $dir_root = &propath($udom,$uname);
 1898:             $dir_root =~ s/\/$//;
 1899:         } else {
 1900:             &Failure($client,"refused\n",$userinput);
 1901:             return 1;
 1902:         }
 1903:     } elsif ($alternate_root ne '') {
 1904:         $dir_root = $alternate_root;
 1905:     }
 1906:     if (($dir_root ne '') && ($dir_root ne '/')) {
 1907:         if ($ulsdir =~ /^\//) {
 1908:             $ulsdir = $dir_root.$ulsdir;
 1909:         } else {
 1910:             $ulsdir = $dir_root.'/'.$ulsdir;
 1911:         }
 1912:     }
 1913:     if ($ulsdir =~m{/\.\./}) {
 1914:         &Failure($client,"refused\n",$userinput);
 1915:         return 1;
 1916:     }
 1917:     my $islocal;
 1918:     my @machine_ids = &Apache::lonnet::current_machine_ids();
 1919:     if (grep(/^\Q$clientname\E$/,@machine_ids)) {
 1920:         $islocal = 1;
 1921:     }
 1922:     my $obs;
 1923:     my $rights;
 1924:     my $ulsout='';
 1925:     my $ulsfn;
 1926: 
 1927:     my ($crscheck,$toplevel,$currdom,$currnum,$skip,$privdir_for_course);
 1928:     unless ($islocal) {
 1929:         my ($major,$minor) = split(/\./,$clientversion);
 1930:         if (($major < 2) || ($major == 2 && $minor < 12)) {
 1931:             $crscheck = 1;
 1932:         }
 1933:         if ($ulsdir =~ m{^/home/httpd/html/priv/($LONCAPA::match_domain)/($LONCAPA::match_courseid)}) {
 1934:             my ($currdom,$currnum) = ($1,$2);
 1935:             if (&LONCAPA::Lond::is_course($currdom,$currnum)) {
 1936:                 $privdir_for_course = 1;
 1937:             }
 1938:         }
 1939:     }
 1940:     if (-e $ulsdir) {
 1941:         if(-d $ulsdir) {
 1942:             unless (($getpropath) || ($getuserdir) ||
 1943:                     ($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
 1944:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles}) ||
 1945:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain}) && ($islocal)) ||
 1946:                     ($privdir_for_course)) {
 1947:                 &Failure($client,"refused\n",$userinput);
 1948:                 return 1;
 1949:             }
 1950:             if (($crscheck) &&
 1951:                 ($ulsdir =~ m{^/home/httpd/html/res/($LONCAPA::match_domain)(/?$|/$LONCAPA::match_courseid)})) {
 1952:                 ($currdom,my $posscnum) = ($1,$2);
 1953:                 if (($posscnum eq '') || ($posscnum eq '/')) {
 1954:                     $toplevel = 1;
 1955:                 } else {
 1956:                     $posscnum =~ s{^/+}{};
 1957:                     if (&LONCAPA::Lond::is_course($currdom,$posscnum)) {
 1958:                         $skip = 1;
 1959:                     }
 1960:                 }
 1961:             }
 1962:             if ((!$skip) && (opendir(LSDIR,$ulsdir))) {
 1963:                 while ($ulsfn=readdir(LSDIR)) {
 1964:                     if (($crscheck) && ($toplevel) && ($currdom ne '') &&
 1965:                         ($ulsfn =~ /^$LONCAPA::match_courseid$/) && (-d "$ulsdir/$ulsfn")) {
 1966:                         if (&LONCAPA::Lond::is_course($currdom,$ulsfn)) {
 1967:                             next;
 1968:                         }
 1969:                     }
 1970:                     undef($obs);
 1971:                     undef($rights);
 1972:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1973:                     #We do some obsolete checking here
 1974:                     if(-e $ulsdir.'/'.$ulsfn.".meta") {
 1975:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
 1976:                         my @obsolete=<FILE>;
 1977:                         foreach my $obsolete (@obsolete) {
 1978:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
 1979:                             if($obsolete =~ m|(<copyright>)(default)|) {
 1980:                                 $rights = 1;
 1981:                             }
 1982:                         }
 1983:                     }
 1984:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
 1985:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1986:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1987:                     $ulsout.= &escape($tmp).':';
 1988:                 }
 1989:                 closedir(LSDIR);
 1990:             }
 1991:         } else {
 1992:             unless (($getpropath) || ($getuserdir) ||
 1993:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
 1994:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/}) ||
 1995:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain/$LONCAPA::match_name/}) && ($islocal))) {
 1996:                 &Failure($client,"refused\n",$userinput);
 1997:                 return 1;
 1998:             }
 1999:             my @ulsstats=stat($ulsdir);
 2000:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 2001:         }
 2002:     } else {
 2003:         $ulsout='no_such_dir';
 2004:     }
 2005:     if ($ulsout eq '') { $ulsout='empty'; }
 2006:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
 2007:     return 1;
 2008: }
 2009: &register_handler("ls3", \&ls3_handler, 0, 1, 0);
 2010: 
 2011: sub read_lonnet_global {
 2012:     my ($cmd,$tail,$client) = @_;
 2013:     my $userinput = "$cmd:$tail";
 2014:     my $requested = &Apache::lonnet::thaw_unescape($tail);
 2015:     my $result;
 2016:     my %packagevars = (
 2017:                         spareid => \%Apache::lonnet::spareid,
 2018:                         perlvar => \%Apache::lonnet::perlvar,
 2019:                       );
 2020:     my %limit_to = (
 2021:                     perlvar => {
 2022:                                  lonOtherAuthen  => 1,
 2023:                                  lonBalancer     => 1,
 2024:                                  lonVersion      => 1,
 2025:                                  lonAdmEMail     => 1,
 2026:                                  lonSupportEMail => 1,  
 2027:                                  lonSysEMail     => 1,
 2028:                                  lonHostID       => 1,
 2029:                                  lonRole         => 1,
 2030:                                  lonDefDomain    => 1,
 2031:                                  lonLoadLim      => 1,
 2032:                                  lonUserLoadLim  => 1,
 2033:                                }
 2034:                   );
 2035:     if (ref($requested) eq 'HASH') {
 2036:         foreach my $what (keys(%{$requested})) {
 2037:             my $response;
 2038:             my $items = {};
 2039:             if (exists($packagevars{$what})) {
 2040:                 if (ref($limit_to{$what}) eq 'HASH') {
 2041:                     foreach my $varname (keys(%{$packagevars{$what}})) {
 2042:                         if ($limit_to{$what}{$varname}) {
 2043:                             $items->{$varname} = $packagevars{$what}{$varname};
 2044:                         }
 2045:                     }
 2046:                 } else {
 2047:                     $items = $packagevars{$what};
 2048:                 }
 2049:                 if ($what eq 'perlvar') {
 2050:                     if (!exists($packagevars{$what}{'lonBalancer'})) {
 2051:                         if ($dist =~ /^(centos|rhes|fedora|scientific|oracle|rocky|alma)/) {
 2052:                             my $othervarref=LONCAPA::Configuration::read_conf('httpd.conf');
 2053:                             if (ref($othervarref) eq 'HASH') {
 2054:                                 $items->{'lonBalancer'} = $othervarref->{'lonBalancer'};
 2055:                             }
 2056:                         }
 2057:                     }
 2058:                 }
 2059:                 $response = &Apache::lonnet::freeze_escape($items);
 2060:             }
 2061:             $result .= &escape($what).'='.$response.'&';
 2062:         }
 2063:     }
 2064:     $result =~ s/\&$//;
 2065:     &Reply($client,\$result,$userinput);
 2066:     return 1;
 2067: }
 2068: &register_handler("readlonnetglobal", \&read_lonnet_global, 0, 1, 0);
 2069: 
 2070: sub server_devalidatecache_handler {
 2071:     my ($cmd,$tail,$client) = @_;
 2072:     my $userinput = "$cmd:$tail";
 2073:     my $items = &unescape($tail);
 2074:     my @cached = split(/\&/,$items);
 2075:     foreach my $key (@cached) {
 2076:         if ($key =~ /:/) {
 2077:             my ($name,$id) = map { &unescape($_); } split(/:/,$key);
 2078:             &Apache::lonnet::devalidate_cache_new($name,$id);
 2079:         }
 2080:     }
 2081:     my $result = 'ok';
 2082:     &Reply($client,\$result,$userinput);
 2083:     return 1;
 2084: }
 2085: &register_handler("devalidatecache", \&server_devalidatecache_handler, 0, 1, 0);
 2086: 
 2087: sub server_timezone_handler {
 2088:     my ($cmd,$tail,$client) = @_;
 2089:     my $userinput = "$cmd:$tail";
 2090:     my $timezone;
 2091:     my $clockfile = '/etc/sysconfig/clock'; # Fedora/CentOS/SuSE
 2092:     my $tzfile = '/etc/timezone'; # Debian/Ubuntu
 2093:     if (-e $clockfile) {
 2094:         if (open(my $fh,"<$clockfile")) {
 2095:             while (<$fh>) {
 2096:                 next if (/^[\#\s]/);
 2097:                 if (/^(?:TIME)?ZONE\s*=\s*['"]?\s*([\w\/]+)/) {
 2098:                     $timezone = $1;
 2099:                     last;
 2100:                 }
 2101:             }
 2102:             close($fh);
 2103:         }
 2104:     } elsif (-e $tzfile) {
 2105:         if (open(my $fh,"<$tzfile")) {
 2106:             $timezone = <$fh>;
 2107:             close($fh);
 2108:             chomp($timezone);
 2109:             if ($timezone =~ m{^Etc/(\w+)$}) {
 2110:                 $timezone = $1;
 2111:             }
 2112:         }
 2113:     }
 2114:     &Reply($client,\$timezone,$userinput); # This supports debug logging.
 2115:     return 1;
 2116: }
 2117: &register_handler("servertimezone", \&server_timezone_handler, 0, 1, 0);
 2118: 
 2119: sub server_loncaparev_handler {
 2120:     my ($cmd,$tail,$client) = @_;
 2121:     my $userinput = "$cmd:$tail";
 2122:     &Reply($client,\$perlvar{'lonVersion'},$userinput);
 2123:     return 1;
 2124: }
 2125: &register_handler("serverloncaparev", \&server_loncaparev_handler, 0, 1, 0);
 2126: 
 2127: sub server_homeID_handler {
 2128:     my ($cmd,$tail,$client) = @_;
 2129:     my $userinput = "$cmd:$tail";
 2130:     &Reply($client,\$perlvar{'lonHostID'},$userinput);
 2131:     return 1;
 2132: }
 2133: &register_handler("serverhomeID", \&server_homeID_handler, 0, 1, 0);
 2134: 
 2135: sub server_distarch_handler {
 2136:     my ($cmd,$tail,$client) = @_;
 2137:     my $userinput = "$cmd:$tail";
 2138:     my $reply = &distro_and_arch();
 2139:     &Reply($client,\$reply,$userinput);
 2140:     return 1;
 2141: }
 2142: &register_handler("serverdistarch", \&server_distarch_handler, 0, 1, 0);
 2143: 
 2144: sub server_certs_handler {
 2145:     my ($cmd,$tail,$client) = @_;
 2146:     my $userinput = "$cmd:$tail";
 2147:     my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
 2148:     my $result = &LONCAPA::Lond::server_certs(\%perlvar,$perlvar{'lonHostID'},$hostname);
 2149:     &Reply($client,\$result,$userinput);
 2150:     return;
 2151: }
 2152: &register_handler("servercerts", \&server_certs_handler, 0, 1, 0);
 2153: 
 2154: #   Process a reinit request.  Reinit requests that either
 2155: #   lonc or lond be reinitialized so that an updated 
 2156: #   host.tab or domain.tab can be processed.
 2157: #
 2158: # Parameters:
 2159: #      $cmd    - the actual keyword that invoked us.
 2160: #      $tail   - the tail of the request that invoked us.
 2161: #      $client - File descriptor connected to the client
 2162: #  Returns:
 2163: #      1       - Ok to continue processing.
 2164: #      0       - Program should exit
 2165: #  Implicit output:
 2166: #     a reply is sent to the client.
 2167: #
 2168: sub reinit_process_handler {
 2169:     my ($cmd, $tail, $client) = @_;
 2170:    
 2171:     my $userinput = "$cmd:$tail";
 2172:    
 2173:     my $cert = &GetCertificate($userinput);
 2174:     if(&ValidManager($cert)) {
 2175: 	chomp($userinput);
 2176: 	my $reply = &ReinitProcess($userinput);
 2177: 	&Reply( $client,  \$reply, $userinput);
 2178:     } else {
 2179: 	&Failure( $client, "refused\n", $userinput);
 2180:     }
 2181:     return 1;
 2182: }
 2183: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
 2184: 
 2185: #  Process the editing script for a table edit operation.
 2186: #  the editing operation must be encrypted and requested by
 2187: #  a manager host.
 2188: #
 2189: # Parameters:
 2190: #      $cmd    - the actual keyword that invoked us.
 2191: #      $tail   - the tail of the request that invoked us.
 2192: #      $client - File descriptor connected to the client
 2193: #  Returns:
 2194: #      1       - Ok to continue processing.
 2195: #      0       - Program should exit
 2196: #  Implicit output:
 2197: #     a reply is sent to the client.
 2198: #
 2199: sub edit_table_handler {
 2200:     my ($command, $tail, $client) = @_;
 2201:    
 2202:     my $userinput = "$command:$tail";
 2203: 
 2204:     my $cert = &GetCertificate($userinput);
 2205:     if(&ValidManager($cert)) {
 2206: 	my($filetype, $script) = split(/:/, $tail);
 2207: 	if (($filetype eq "hosts") || 
 2208: 	    ($filetype eq "domain")) {
 2209: 	    if($script ne "") {
 2210: 		&Reply($client,              # BUGBUG - EditFile
 2211: 		      &EditFile($userinput), #   could fail.
 2212: 		      $userinput);
 2213: 	    } else {
 2214: 		&Failure($client,"refused\n",$userinput);
 2215: 	    }
 2216: 	} else {
 2217: 	    &Failure($client,"refused\n",$userinput);
 2218: 	}
 2219:     } else {
 2220: 	&Failure($client,"refused\n",$userinput);
 2221:     }
 2222:     return 1;
 2223: }
 2224: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
 2225: 
 2226: #
 2227: #   Authenticate a user against the LonCAPA authentication
 2228: #   database.  Note that there are several authentication
 2229: #   possibilities:
 2230: #   - unix     - The user can be authenticated against the unix
 2231: #                password file.
 2232: #   - internal - The user can be authenticated against a purely 
 2233: #                internal per user password file.
 2234: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
 2235: #                ticket granting authority.
 2236: #   - user     - The person tailoring LonCAPA can supply a user authentication
 2237: #                mechanism that is per system.
 2238: #
 2239: # Parameters:
 2240: #    $cmd      - The command that got us here.
 2241: #    $tail     - Tail of the command (remaining parameters).
 2242: #    $client   - File descriptor connected to client.
 2243: # Returns
 2244: #     0        - Requested to exit, caller should shut down.
 2245: #     1        - Continue processing.
 2246: # Implicit inputs:
 2247: #    The authentication systems describe above have their own forms of implicit
 2248: #    input into the authentication process that are described above.
 2249: #
 2250: sub authenticate_handler {
 2251:     my ($cmd, $tail, $client) = @_;
 2252: 
 2253:     
 2254:     #  Regenerate the full input line 
 2255:     
 2256:     my $userinput  = $cmd.":".$tail;
 2257:     
 2258:     #  udom    - User's domain.
 2259:     #  uname   - Username.
 2260:     #  upass   - User's password.
 2261:     #  checkdefauth - Pass to validate_user() to try authentication
 2262:     #                 with default auth type(s) if no user account.
 2263:     #  clientcancheckhost - Passed by clients with functionality in lonauth.pm
 2264:     #                       to check if session can be hosted.
 2265:     
 2266:     my ($udom, $uname, $upass, $checkdefauth, $clientcancheckhost)=split(/:/,$tail);
 2267:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass,  checkdefauth = $checkdefauth");
 2268:     chomp($upass);
 2269:     $upass=&unescape($upass);
 2270: 
 2271:     my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
 2272:     if($pwdcorrect) {
 2273:         my $canhost = 1;
 2274:         unless ($clientcancheckhost) {
 2275:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 2276:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 2277:             my @intdoms;
 2278:             my $internet_names = &Apache::lonnet::get_internet_names($clientname);
 2279:             if (ref($internet_names) eq 'ARRAY') {
 2280:                 @intdoms = @{$internet_names};
 2281:             }
 2282:             unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
 2283:                 my ($remote,$hosted);
 2284:                 my $remotesession = &get_usersession_config($udom,'remotesession');
 2285:                 if (ref($remotesession) eq 'HASH') {
 2286:                     $remote = $remotesession->{'remote'};
 2287:                 }
 2288:                 my $hostedsession = &get_usersession_config($clienthomedom,'hostedsession');
 2289:                 if (ref($hostedsession) eq 'HASH') {
 2290:                     $hosted = $hostedsession->{'hosted'};
 2291:                 }
 2292:                 $canhost = &Apache::lonnet::can_host_session($udom,$clientname,
 2293:                                                              $clientversion,
 2294:                                                              $remote,$hosted);
 2295:             }
 2296:         }
 2297:         if ($canhost) {               
 2298:             &Reply( $client, "authorized\n", $userinput);
 2299:         } else {
 2300:             &Reply( $client, "not_allowed_to_host\n", $userinput);
 2301:         }
 2302: 	#
 2303: 	#  Bad credentials: Failed to authorize
 2304: 	#
 2305:     } else {
 2306: 	&Failure( $client, "non_authorized\n", $userinput);
 2307:     }
 2308: 
 2309:     return 1;
 2310: }
 2311: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
 2312: 
 2313: #
 2314: #   Change a user's password.  Note that this function is complicated by
 2315: #   the fact that a user may be authenticated in more than one way:
 2316: #   At present, we are not able to change the password for all types of
 2317: #   authentication methods.  Only for:
 2318: #      unix    - unix password or shadow passoword style authentication.
 2319: #      local   - Locally written authentication mechanism.
 2320: #   For now, kerb4 and kerb5 password changes are not supported and result
 2321: #   in an error.
 2322: # FUTURE WORK:
 2323: #    Support kerberos passwd changes?
 2324: # Parameters:
 2325: #    $cmd      - The command that got us here.
 2326: #    $tail     - Tail of the command (remaining parameters).
 2327: #    $client   - File descriptor connected to client.
 2328: # Returns
 2329: #     0        - Requested to exit, caller should shut down.
 2330: #     1        - Continue processing.
 2331: # Implicit inputs:
 2332: #    The authentication systems describe above have their own forms of implicit
 2333: #    input into the authentication process that are described above.
 2334: sub change_password_handler {
 2335:     my ($cmd, $tail, $client) = @_;
 2336: 
 2337:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
 2338: 
 2339:     #
 2340:     #  udom  - user's domain.
 2341:     #  uname - Username.
 2342:     #  upass - Current password.
 2343:     #  npass - New password.
 2344:     #  context - Context in which this was called 
 2345:     #            (preferences or reset_by_email).
 2346:     #  lonhost - HostID of server where request originated 
 2347:    
 2348:     my ($udom,$uname,$upass,$npass,$context,$lonhost)=split(/:/,$tail);
 2349: 
 2350:     $upass=&unescape($upass);
 2351:     $npass=&unescape($npass);
 2352:     &Debug("Trying to change password for $uname");
 2353: 
 2354:     # First require that the user can be authenticated with their
 2355:     # old password unless context was 'reset_by_email':
 2356:     
 2357:     my ($validated,$failure);
 2358:     if ($context eq 'reset_by_email') {
 2359:         if ($lonhost eq '') {
 2360:             $failure = 'invalid_client';
 2361:         } else {
 2362:             $validated = 1;
 2363:         }
 2364:     } else {
 2365:         $validated = &validate_user($udom, $uname, $upass);
 2366:     }
 2367:     if($validated) {
 2368: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
 2369: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
 2370:         my $notunique;
 2371: 	if ($howpwd eq 'internal') {
 2372: 	    &Debug("internal auth");
 2373:             my $ncpass = &hash_passwd($udom,$npass);
 2374:             my (undef,$method,@rest) = split(/!/,$contentpwd);
 2375:             if ($method eq 'bcrypt') {
 2376:                 my %passwdconf = &Apache::lonnet::get_passwdconf($udom);
 2377:                 if (($passwdconf{'numsaved'}) && ($passwdconf{'numsaved'} =~ /^\d+$/)) {
 2378:                     my @oldpasswds;
 2379:                     my $userpath = &propath($udom,$uname);
 2380:                     my $fullpath = $userpath.'/oldpasswds';
 2381:                     if (-d $userpath) {
 2382:                         my @oldfiles;
 2383:                         if (-e $fullpath) {
 2384:                             if (opendir(my $dir,$fullpath)) {
 2385:                                 (@oldfiles) = grep(/^\d+$/,readdir($dir));
 2386:                                 closedir($dir);
 2387:                             }
 2388:                             if (@oldfiles) {
 2389:                                 @oldfiles = sort { $b <=> $a } (@oldfiles);
 2390:                                 my $numremoved = 0;
 2391:                                 for (my $i=0; $i<@oldfiles; $i++) {
 2392:                                     if ($i>=$passwdconf{'numsaved'}) {
 2393:                                         if (-f "$fullpath/$oldfiles[$i]") {
 2394:                                             if (unlink("$fullpath/$oldfiles[$i]")) {
 2395:                                                 $numremoved ++;
 2396:                                             }
 2397:                                         }
 2398:                                     } elsif (open(my $fh,'<',"$fullpath/$oldfiles[$i]")) {
 2399:                                         while (my $line = <$fh>) {
 2400:                                             push(@oldpasswds,$line);
 2401:                                         }
 2402:                                         close($fh);
 2403:                                     }
 2404:                                 }
 2405:                                 if ($numremoved) {
 2406:                                     &logthis("unlinked $numremoved old password files for $uname:$udom");
 2407:                                 }
 2408:                             }
 2409:                         }
 2410:                         push(@oldpasswds,$contentpwd);
 2411:                         foreach my $item (@oldpasswds) {
 2412:                             my (undef,$method,@rest) = split(/!/,$item);
 2413:                             if ($method eq 'bcrypt') {
 2414:                                 my $result = &hash_passwd($udom,$npass,@rest);
 2415:                                 if ($result eq $item) {
 2416:                                     $notunique = 1;
 2417:                                     last;
 2418:                                 }
 2419:                             }
 2420:                         }
 2421:                         unless ($notunique) {
 2422:                             unless (-e $fullpath) {
 2423:                                 if (&mkpath("$fullpath/")) {
 2424:                                     chmod(0700,$fullpath);
 2425:                                 }
 2426:                             }
 2427:                             if (-d $fullpath) {
 2428:                                 my $now = time;
 2429:                                 if (open(my $fh,'>',"$fullpath/$now")) {
 2430:                                     print $fh $contentpwd;
 2431:                                     close($fh);
 2432:                                     chmod(0400,"$fullpath/$now");
 2433:                                 }
 2434:                             }
 2435:                         }
 2436:                     }
 2437:                 }
 2438:             }
 2439:             if ($notunique) {
 2440:                 my $msg="Result of password change for $uname:$udom - password matches one used before";
 2441:                 if ($lonhost) {
 2442:                     $msg .= " - request originated from: $lonhost";
 2443:                 }
 2444:                 &logthis($msg);
 2445:                 &Reply($client, "prioruse\n", $userinput);
 2446: 	    } elsif (&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
 2447: 		my $msg="Result of password change for $uname: pwchange_success";
 2448:                 if ($lonhost) {
 2449:                     $msg .= " - request originated from: $lonhost";
 2450:                 }
 2451:                 &logthis($msg);
 2452:                 &update_passwd_history($uname,$udom,$howpwd,$context);
 2453: 		&Reply($client, "ok\n", $userinput);
 2454: 	    } else {
 2455: 		&logthis("Unable to open $uname passwd "               
 2456: 			 ."to change password");
 2457: 		&Failure( $client, "non_authorized\n",$userinput);
 2458: 	    }
 2459: 	} elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
 2460: 	    my $result = &change_unix_password($uname, $npass);
 2461:             if ($result eq 'ok') {
 2462:                 &update_passwd_history($uname,$udom,$howpwd,$context);
 2463:             }
 2464: 	    &logthis("Result of password change for $uname: ".
 2465: 		     $result);
 2466: 	    &Reply($client, \$result, $userinput);
 2467: 	} else {
 2468: 	    # this just means that the current password mode is not
 2469: 	    # one we know how to change (e.g the kerberos auth modes or
 2470: 	    # locally written auth handler).
 2471: 	    #
 2472: 	    &Failure( $client, "auth_mode_error\n", $userinput);
 2473: 	}  
 2474:     } else {
 2475: 	if ($failure eq '') {
 2476: 	    $failure = 'non_authorized';
 2477: 	}
 2478: 	&Failure( $client, "$failure\n", $userinput);
 2479:     }
 2480: 
 2481:     return 1;
 2482: }
 2483: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
 2484: 
 2485: sub hash_passwd {
 2486:     my ($domain,$plainpass,@rest) = @_;
 2487:     my ($salt,$cost);
 2488:     if (@rest) {
 2489:         $cost = $rest[0];
 2490:         # salt is first 22 characters, base-64 encoded by bcrypt
 2491:         my $plainsalt = substr($rest[1],0,22);
 2492:         $salt = Crypt::Eksblowfish::Bcrypt::de_base64($plainsalt);
 2493:     } else {
 2494:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2495:         my $defaultcost = $domdefaults{'intauth_cost'};
 2496:         if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
 2497:             $cost = 10;
 2498:         } else {
 2499:             $cost = $defaultcost;
 2500:         }
 2501:         # Generate random 16-octet base64 salt
 2502:         $salt = "";
 2503:         $salt .= pack("C", int rand(256)) for 1..16;
 2504:     }
 2505:     my $hash = &Crypt::Eksblowfish::Bcrypt::bcrypt_hash({
 2506:         key_nul => 1,
 2507:         cost    => $cost,
 2508:         salt    => $salt,
 2509:     }, Digest::SHA::sha512(Encode::encode('UTF-8',$plainpass)));
 2510: 
 2511:     my $result = join("!", "", "bcrypt", sprintf("%02d",$cost),
 2512:                 &Crypt::Eksblowfish::Bcrypt::en_base64($salt).
 2513:                 &Crypt::Eksblowfish::Bcrypt::en_base64($hash));
 2514:     return $result;
 2515: }
 2516: 
 2517: #
 2518: #   Create a new user.  User in this case means a lon-capa user.
 2519: #   The user must either already exist in some authentication realm
 2520: #   like kerberos or the /etc/passwd.  If not, a user completely local to
 2521: #   this loncapa system is created.
 2522: #
 2523: # Parameters:
 2524: #    $cmd      - The command that got us here.
 2525: #    $tail     - Tail of the command (remaining parameters).
 2526: #    $client   - File descriptor connected to client.
 2527: # Returns
 2528: #     0        - Requested to exit, caller should shut down.
 2529: #     1        - Continue processing.
 2530: # Implicit inputs:
 2531: #    The authentication systems describe above have their own forms of implicit
 2532: #    input into the authentication process that are described above.
 2533: sub add_user_handler {
 2534: 
 2535:     my ($cmd, $tail, $client) = @_;
 2536: 
 2537: 
 2538:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
 2539:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
 2540: 
 2541:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
 2542: 
 2543: 
 2544:     if($udom eq $currentdomainid) { # Reject new users for other domains...
 2545: 	
 2546: 	my $oldumask=umask(0077);
 2547: 	chomp($npass);
 2548: 	$npass=&unescape($npass);
 2549: 	my $passfilename  = &password_path($udom, $uname);
 2550: 	&Debug("Password file created will be:".$passfilename);
 2551: 	if (-e $passfilename) {
 2552: 	    &Failure( $client, "already_exists\n", $userinput);
 2553: 	} else {
 2554: 	    my $fperror='';
 2555: 	    if (!&mkpath($passfilename)) {
 2556: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
 2557: 		    ."makeuser";
 2558: 	    }
 2559: 	    unless ($fperror) {
 2560: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
 2561:                                              $passfilename,'makeuser');
 2562: 		&Reply($client,\$result, $userinput);     #BUGBUG - could be fail
 2563: 	    } else {
 2564: 		&Failure($client, \$fperror, $userinput);
 2565: 	    }
 2566: 	}
 2567: 	umask($oldumask);
 2568:     }  else {
 2569: 	&Failure($client, "not_right_domain\n",
 2570: 		$userinput);	# Even if we are multihomed.
 2571:     
 2572:     }
 2573:     return 1;
 2574: 
 2575: }
 2576: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
 2577: 
 2578: #
 2579: #   Change the authentication method of a user.  Note that this may
 2580: #   also implicitly change the user's password if, for example, the user is
 2581: #   joining an existing authentication realm.  Known authentication realms at
 2582: #   this time are:
 2583: #    internal   - Purely internal password file (only loncapa knows this user)
 2584: #    local      - Institutionally written authentication module.
 2585: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
 2586: #    kerb4      - kerberos version 4
 2587: #    kerb5      - kerberos version 5
 2588: #
 2589: # Parameters:
 2590: #    $cmd      - The command that got us here.
 2591: #    $tail     - Tail of the command (remaining parameters).
 2592: #    $client   - File descriptor connected to client.
 2593: # Returns
 2594: #     0        - Requested to exit, caller should shut down.
 2595: #     1        - Continue processing.
 2596: # Implicit inputs:
 2597: #    The authentication systems describe above have their own forms of implicit
 2598: #    input into the authentication process that are described above.
 2599: # NOTE:
 2600: #   This is also used to change the authentication credential values (e.g. passwd).
 2601: #   
 2602: #
 2603: sub change_authentication_handler {
 2604: 
 2605:     my ($cmd, $tail, $client) = @_;
 2606:    
 2607:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
 2608: 
 2609:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
 2610:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
 2611:     if ($udom ne $currentdomainid) {
 2612: 	&Failure( $client, "not_right_domain\n", $client);
 2613:     } else {
 2614: 	
 2615: 	chomp($npass);
 2616: 	
 2617: 	$npass=&unescape($npass);
 2618: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
 2619: 	my $passfilename = &password_path($udom, $uname);
 2620: 	if ($passfilename) {	# Not allowed to create a new user!!
 2621: 	    # If just changing the unix passwd. need to arrange to run
 2622: 	    # passwd since otherwise make_passwd_file will fail as 
 2623: 	    # creation of unix authenticated users is no longer supported
 2624:             # except from the command line, when running make_domain_coordinator.pl
 2625: 
 2626: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
 2627: 		my $result = &change_unix_password($uname, $npass);
 2628: 		&logthis("Result of password change for $uname: ".$result);
 2629: 		if ($result eq "ok") {
 2630:                     &update_passwd_history($uname,$udom,$umode,'changeuserauth'); 
 2631: 		    &Reply($client, \$result);
 2632: 		} else {
 2633: 		    &Failure($client, \$result);
 2634: 		}
 2635: 	    } else {
 2636: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
 2637:                                              $passfilename,'changeuserauth');
 2638: 		#
 2639: 		#  If the current auth mode is internal, and the old auth mode was
 2640: 		#  unix, or krb*,  and the user is an author for this domain,
 2641: 		#  re-run manage_permissions for that role in order to be able
 2642: 		#  to take ownership of the construction space back to www:www
 2643: 		#
 2644: 
 2645: 
 2646: 		&Reply($client, \$result, $userinput);
 2647: 	    }
 2648: 	       
 2649: 
 2650: 	} else {	       
 2651: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
 2652: 	}
 2653:     }
 2654:     return 1;
 2655: }
 2656: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
 2657: 
 2658: sub update_passwd_history {
 2659:     my ($uname,$udom,$umode,$context) = @_;
 2660:     my $proname=&propath($udom,$uname);
 2661:     my $now = time;
 2662:     if (open(my $fh,">>$proname/passwd.log")) {
 2663:         print $fh "$now:$umode:$context\n";
 2664:         close($fh);
 2665:     }
 2666:     return;
 2667: }
 2668: 
 2669: sub inst_unamemap_check {
 2670:     my ($cmd, $tail, $client)   = @_;
 2671:     my $userinput               = "$cmd:$tail";
 2672:     my %rulecheck;
 2673:     my $outcome;
 2674:     my ($udom,$uname,@rules) = split(/:/,$tail);
 2675:     $udom = &unescape($udom);
 2676:     $uname = &unescape($uname);
 2677:     @rules = map {&unescape($_);} (@rules);
 2678:     eval {
 2679:         local($SIG{__DIE__})='DEFAULT';
 2680:         $outcome = &localenroll::unamemap_check($udom,$uname,\@rules,\%rulecheck);
 2681:     };
 2682:     if (!$@) {
 2683:         if ($outcome eq 'ok') {
 2684:             my $result='';
 2685:             foreach my $key (keys(%rulecheck)) {
 2686:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
 2687:             }
 2688:             &Reply($client,\$result,$userinput);
 2689:         } else {
 2690:             &Reply($client,"error\n", $userinput);
 2691:         }
 2692:     } else {
 2693:         &Failure($client,"unknown_cmd\n",$userinput);
 2694:     }
 2695: }
 2696: &register_handler("instunamemapcheck",\&inst_unamemap_check,0,1,0);
 2697: 
 2698: 
 2699: #
 2700: #   Determines if this is the home server for a user.  The home server
 2701: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
 2702: #   to do is determine if this file exists.
 2703: #
 2704: # Parameters:
 2705: #    $cmd      - The command that got us here.
 2706: #    $tail     - Tail of the command (remaining parameters).
 2707: #    $client   - File descriptor connected to client.
 2708: # Returns
 2709: #     0        - Requested to exit, caller should shut down.
 2710: #     1        - Continue processing.
 2711: # Implicit inputs:
 2712: #    The authentication systems describe above have their own forms of implicit
 2713: #    input into the authentication process that are described above.
 2714: #
 2715: sub is_home_handler {
 2716:     my ($cmd, $tail, $client) = @_;
 2717:    
 2718:     my $userinput  = "$cmd:$tail";
 2719:    
 2720:     my ($udom,$uname)=split(/:/,$tail);
 2721:     chomp($uname);
 2722:     my $passfile = &password_filename($udom, $uname);
 2723:     if($passfile) {
 2724: 	&Reply( $client, "found\n", $userinput);
 2725:     } else {
 2726: 	&Failure($client, "not_found\n", $userinput);
 2727:     }
 2728:     return 1;
 2729: }
 2730: &register_handler("home", \&is_home_handler, 0,1,0);
 2731: 
 2732: #
 2733: #   Process an update request for a resource.
 2734: #   A resource has been modified that we hold a subscription to.
 2735: #   If the resource is not local, then we must update, or at least invalidate our
 2736: #   cached copy of the resource. 
 2737: # Parameters:
 2738: #    $cmd      - The command that got us here.
 2739: #    $tail     - Tail of the command (remaining parameters).
 2740: #    $client   - File descriptor connected to client.
 2741: # Returns
 2742: #     0        - Requested to exit, caller should shut down.
 2743: #     1        - Continue processing.
 2744: # Implicit inputs:
 2745: #    The authentication systems describe above have their own forms of implicit
 2746: #    input into the authentication process that are described above.
 2747: #
 2748: sub update_resource_handler {
 2749: 
 2750:     my ($cmd, $tail, $client) = @_;
 2751:    
 2752:     my $userinput = "$cmd:$tail";
 2753:    
 2754:     my $fname= $tail;		# This allows interactive testing
 2755: 
 2756: 
 2757:     my $ownership=ishome($fname);
 2758:     if ($ownership eq 'not_owner') {
 2759: 	if (-e $fname) {
 2760:             # Delete preview file, if exists
 2761:             unlink("$fname.tmp");
 2762:             # Get usage stats
 2763: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
 2764: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
 2765: 	    my $now=time;
 2766: 	    my $since=$now-$atime;
 2767:             # If the file has not been used within lonExpire seconds,
 2768:             # unsubscribe from it and delete local copy
 2769: 	    if ($since>$perlvar{'lonExpire'}) {
 2770: 		my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
 2771: 		&devalidate_meta_cache($fname);
 2772: 		unlink("$fname");
 2773: 		unlink("$fname.meta");
 2774: 	    } else {
 2775:             # Yes, this is in active use. Get a fresh copy. Since it might be in
 2776:             # very active use and huge (like a movie), copy it to "in.transfer" filename first.
 2777: 		my $transname="$fname.in.transfer";
 2778: 		my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
 2779: 		my $response;
 2780: # FIXME: cannot replicate files that take more than two minutes to transfer -- needs checking now 1200s timeout used
 2781: # for LWP request.
 2782: 		my $request=new HTTP::Request('GET',"$remoteurl");
 2783:                 $response=&LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,0,1);
 2784: 		if ($response->is_error()) {
 2785:                     my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
 2786:                     &devalidate_meta_cache($fname);
 2787:                     if (-e $transname) {
 2788:                         unlink($transname);
 2789:                     }
 2790:                     unlink($fname);
 2791: 		    my $message=$response->status_line;
 2792: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
 2793: 		} else {
 2794: 		    if ($remoteurl!~/\.meta$/) {
 2795: 			my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2796:                         my $mresponse = &LONCAPA::LWPReq::makerequest($clientname,$mrequest,$fname.'.meta',\%perlvar,120,0,1);
 2797: 			if ($mresponse->is_error()) {
 2798: 			    unlink($fname.'.meta');
 2799: 			}
 2800: 		    }
 2801:                     # we successfully transfered, copy file over to real name
 2802: 		    rename($transname,$fname);
 2803: 		    &devalidate_meta_cache($fname);
 2804: 		}
 2805: 	    }
 2806: 	    &Reply( $client, "ok\n", $userinput);
 2807: 	} else {
 2808: 	    &Failure($client, "not_found\n", $userinput);
 2809: 	}
 2810:     } else {
 2811: 	&Failure($client, "rejected\n", $userinput);
 2812:     }
 2813:     return 1;
 2814: }
 2815: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
 2816: 
 2817: sub devalidate_meta_cache {
 2818:     my ($url) = @_;
 2819:     use Cache::Memcached;
 2820:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
 2821:     $url = &Apache::lonnet::declutter($url);
 2822:     $url =~ s-\.meta$--;
 2823:     my $id = &escape('meta:'.$url);
 2824:     $memcache->delete($id);
 2825: }
 2826: 
 2827: #
 2828: # Copy a file from /home/httpd/html/priv/domain/coursenum/
 2829: # to /home/httpd/html/userfiles/domain/coursenum/priv
 2830: #
 2831: # Parameters:
 2832: #    $cmd      - The command that got us here.
 2833: #    $tail     - Tail of the command
 2834: #                : separated list of escaped values for
 2835: #                (a) relative path to a file in /priv/domain/coursenum
 2836: #                (b) coursenum
 2837: #                (c) domain
 2838: #    $client   - File descriptor connected to client.
 2839: # Returns
 2840: #     0        - Requested to exit, caller should shut down.
 2841: #     1        - Continue processing.
 2842: #
 2843: 
 2844: sub crs_filefrompriv_handler {
 2845:     my ($cmd, $tail, $client) = @_;
 2846:     my $userinput = "$cmd:$tail";
 2847:     my ($path,$cnum,$cdom) = map { &unescape($_); } split(/:/,$tail);
 2848:     $path =~ s/\.{2,}//g;
 2849:     if (($path eq '') || ($path eq '.')) {
 2850:         &Failure($client, "not_found\n", "$cmd:$tail");
 2851:     } else {
 2852:         $cdom = &LONCAPA::clean_domain($cdom);
 2853:         $cnum = &LONCAPA::clean_courseid($cnum);
 2854:         if (&LONCAPA::Lond::is_course($cdom,$cnum)) {
 2855:             my $toplevel = "/userfiles/$cdom/$cnum/priv";
 2856:             my $toppath = $perlvar{'lonDocRoot'}.$toplevel;
 2857:             my $dest = $toppath.'/'.$path;
 2858:             my $desturl = $toplevel.'/'.$path;
 2859:             my $src = $perlvar{'lonDocRoot'}.'/priv/'.$cdom.'/'.$cnum.'/'.$path;
 2860:             my ($dest_mtime, $src_mtime);
 2861:             if (-e $dest) {
 2862:                 ($dest_mtime) = (stat($dest))[9];
 2863:             }
 2864:             if (-e $src) {
 2865:                 my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
 2866:                 $protocol = 'http' if ($protocol ne 'https');
 2867:                 my $url = $protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'}).$desturl;
 2868:                 ($src_mtime) = (stat($src))[9];
 2869:                 if ((-e $dest) && ($dest_mtime >= $src_mtime)) {
 2870:                     my $result = &escape($url);
 2871:                     &Reply($client,\$result,$userinput);
 2872:                 } else {
 2873:                     my $reldir = $toplevel;
 2874:                     my ($subdir,$fname) = ($path =~ m{^(.+)/([^/]+)$});
 2875:                     if ($subdir eq '') {
 2876:                         $fname = $path;
 2877:                     } else {
 2878:                         $reldir .= '/'.$subdir;
 2879:                     }
 2880:                     my $targetdir = $perlvar{'lonDocRoot'};
 2881:                     my $dirfail;
 2882:                     foreach my $part (split(/\//,$reldir)) {
 2883:                         $targetdir .= '/'.$part;
 2884:                         if ((-e $targetdir)!=1) {
 2885:                             unless (mkdir($targetdir,0755)) {
 2886:                                 $dirfail = 1;
 2887:                                 last;
 2888:                             }
 2889:                         }
 2890:                     }
 2891:                     if ($dirfail) {
 2892:                         &Failure($client,"error: mkdir_failed\n", $userinput);
 2893:                     } else {
 2894:                         if (File::Copy::copy($src,$dest)) {
 2895:                             my $result = &escape($url);
 2896:                             &Reply($client,\$result,$userinput);
 2897:                         } else {
 2898:                             &Failure($client,"error: copy_failed\n", $userinput);
 2899:                         }
 2900:                     }
 2901:                 }
 2902:             } else {
 2903:                 &Failure($client,"error: not_found\n", $userinput);
 2904:             }
 2905:         } else {
 2906:             &Failure($client, "error: not_course\n", $userinput);
 2907:         }
 2908:     }
 2909:     return 1;
 2910: }
 2911: &register_handler("crsfilefrompriv", \&crs_filefrompriv_handler, 0, 1, 0);
 2912: 
 2913: #
 2914: #   Fetch a user file from a remote server to the user's home directory
 2915: #   userfiles subdir.
 2916: # Parameters:
 2917: #    $cmd      - The command that got us here.
 2918: #    $tail     - Tail of the command (remaining parameters).
 2919: #    $client   - File descriptor connected to client.
 2920: # Returns
 2921: #     0        - Requested to exit, caller should shut down.
 2922: #     1        - Continue processing.
 2923: #
 2924: sub fetch_user_file_handler {
 2925: 
 2926:     my ($cmd, $tail, $client) = @_;
 2927: 
 2928:     my $userinput = "$cmd:$tail";
 2929:     my $fname           = $tail;
 2930:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
 2931:     my $udir=&propath($udom,$uname).'/userfiles';
 2932:     unless (-e $udir) {
 2933: 	mkdir($udir,0770); 
 2934:     }
 2935:     Debug("fetch user file for $fname");
 2936:     if (-e $udir) {
 2937: 	$ufile=~s/^[\.\~]+//;
 2938: 
 2939: 	# IF necessary, create the path right down to the file.
 2940: 	# Note that any regular files in the way of this path are
 2941: 	# wiped out to deal with some earlier folly of mine.
 2942: 
 2943: 	if (!&mkpath($udir.'/'.$ufile)) {
 2944: 	    &Failure($client, "unable_to_create\n", $userinput);	    
 2945: 	}
 2946: 
 2947: 	my $destname=$udir.'/'.$ufile;
 2948: 	my $transname=$udir.'/'.$ufile.'.in.transit';
 2949:         my $clientprotocol=$Apache::lonnet::protocol{$clientname};
 2950:         $clientprotocol = 'http' if ($clientprotocol ne 'https');
 2951: 	my $clienthost = &Apache::lonnet::hostname($clientname);
 2952: 	my $remoteurl=$clientprotocol.'://'.$clienthost.'/userfiles/'.$fname;
 2953: 	my $response;
 2954: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
 2955: 	my $request=new HTTP::Request('GET',"$remoteurl");
 2956:         my $verifycert = 1;
 2957:         my @machine_ids = &Apache::lonnet::current_machine_ids();
 2958:         if (grep(/^\Q$clientname\E$/,@machine_ids)) {
 2959:             $verifycert = 0;
 2960:         }
 2961:         $response = &LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,$verifycert);
 2962: 	if ($response->is_error()) {
 2963: 	    unlink($transname);
 2964: 	    my $message=$response->status_line;
 2965: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
 2966: 	    &Failure($client, "failed\n", $userinput);
 2967: 	} else {
 2968: 	    Debug("Renaming $transname to $destname");
 2969: 	    if (!rename($transname,$destname)) {
 2970: 		&logthis("Unable to move $transname to $destname");
 2971: 		unlink($transname);
 2972: 		&Failure($client, "failed\n", $userinput);
 2973: 	    } else {
 2974:                 if ($fname =~ /^default.+\.(page|sequence)$/) {
 2975:                     my ($major,$minor) = split(/\./,$clientversion);
 2976:                     if (($major < 2) || ($major == 2 && $minor < 11)) {
 2977:                         my $now = time;
 2978:                         &Apache::lonnet::do_cache_new('crschange',$udom.'_'.$uname,$now,600);
 2979:                         my $key = &escape('internal.contentchange');
 2980:                         my $what = "$key=$now";
 2981:                         my $hashref = &tie_user_hash($udom,$uname,'environment',
 2982:                                                      &GDBM_WRCREAT(),"P",$what);
 2983:                         if ($hashref) {
 2984:                             $hashref->{$key}=$now;
 2985:                             if (!&untie_user_hash($hashref)) {
 2986:                                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
 2987:                                          "when updating internal.contentchange");
 2988:                             }
 2989:                         }
 2990:                     }
 2991:                 }
 2992: 		&Reply($client, "ok\n", $userinput);
 2993: 	    }
 2994: 	}   
 2995:     } else {
 2996: 	&Failure($client, "not_home\n", $userinput);
 2997:     }
 2998:     return 1;
 2999: }
 3000: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
 3001: 
 3002: #
 3003: #   Remove a file from a user's home directory userfiles subdirectory.
 3004: # Parameters:
 3005: #    cmd   - the Lond request keyword that got us here.
 3006: #    tail  - the part of the command past the keyword.
 3007: #    client- File descriptor connected with the client.
 3008: #
 3009: # Returns:
 3010: #    1    - Continue processing.
 3011: sub remove_user_file_handler {
 3012:     my ($cmd, $tail, $client) = @_;
 3013: 
 3014:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
 3015: 
 3016:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
 3017:     if ($ufile =~m|/\.\./|) {
 3018: 	# any files paths with /../ in them refuse 
 3019: 	# to deal with
 3020: 	&Failure($client, "refused\n", "$cmd:$tail");
 3021:     } else {
 3022: 	my $udir = &propath($udom,$uname);
 3023: 	if (-e $udir) {
 3024: 	    my $file=$udir.'/userfiles/'.$ufile;
 3025: 	    if (-e $file) {
 3026: 		#
 3027: 		#   If the file is a regular file unlink is fine...
 3028: 		#   However it's possible the client wants a dir 
 3029: 		#   removed, in which case rmdir is more appropriate.
 3030: 		#   Note: rmdir will only remove an empty directory.
 3031: 		#
 3032: 	        if (-f $file){
 3033: 		    unlink($file);
 3034:                     # for html files remove the associated .bak file 
 3035:                     # which may have been created by the editor.
 3036:                     if ($ufile =~ m{^((docs|supplemental)/(?:\d+|default)/\d+(?:|/.+)/)[^/]+\.x?html?$}i) {
 3037:                         my $path = $1;
 3038:                         if (-e $file.'.bak') {
 3039:                             unlink($file.'.bak');
 3040:                         }
 3041:                     }
 3042: 		} elsif(-d $file) {
 3043: 		    rmdir($file);
 3044: 		}
 3045: 		if (-e $file) {
 3046: 		    #  File is still there after we deleted it ?!?
 3047: 
 3048: 		    &Failure($client, "failed\n", "$cmd:$tail");
 3049: 		} else {
 3050: 		    &Reply($client, "ok\n", "$cmd:$tail");
 3051: 		}
 3052: 	    } else {
 3053: 		&Failure($client, "not_found\n", "$cmd:$tail");
 3054: 	    }
 3055: 	} else {
 3056: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 3057: 	}
 3058:     }
 3059:     return 1;
 3060: }
 3061: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
 3062: 
 3063: #
 3064: #   make a directory in a user's home directory userfiles subdirectory.
 3065: # Parameters:
 3066: #    cmd   - the Lond request keyword that got us here.
 3067: #    tail  - the part of the command past the keyword.
 3068: #    client- File descriptor connected with the client.
 3069: #
 3070: # Returns:
 3071: #    1    - Continue processing.
 3072: sub mkdir_user_file_handler {
 3073:     my ($cmd, $tail, $client) = @_;
 3074: 
 3075:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
 3076:     $dir=&unescape($dir);
 3077:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
 3078:     if ($ufile =~m|/\.\./|) {
 3079: 	# any files paths with /../ in them refuse 
 3080: 	# to deal with
 3081: 	&Failure($client, "refused\n", "$cmd:$tail");
 3082:     } else {
 3083: 	my $udir = &propath($udom,$uname);
 3084: 	if (-e $udir) {
 3085: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
 3086: 	    if (!&mkpath($newdir)) {
 3087: 		&Failure($client, "failed\n", "$cmd:$tail");
 3088: 	    }
 3089: 	    &Reply($client, "ok\n", "$cmd:$tail");
 3090: 	} else {
 3091: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 3092: 	}
 3093:     }
 3094:     return 1;
 3095: }
 3096: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
 3097: 
 3098: #
 3099: #   rename a file in a user's home directory userfiles subdirectory.
 3100: # Parameters:
 3101: #    cmd   - the Lond request keyword that got us here.
 3102: #    tail  - the part of the command past the keyword.
 3103: #    client- File descriptor connected with the client.
 3104: #
 3105: # Returns:
 3106: #    1    - Continue processing.
 3107: sub rename_user_file_handler {
 3108:     my ($cmd, $tail, $client) = @_;
 3109: 
 3110:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
 3111:     $old=&unescape($old);
 3112:     $new=&unescape($new);
 3113:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
 3114: 	# any files paths with /../ in them refuse to deal with
 3115: 	&Failure($client, "refused\n", "$cmd:$tail");
 3116:     } else {
 3117: 	my $udir = &propath($udom,$uname);
 3118: 	if (-e $udir) {
 3119: 	    my $oldfile=$udir.'/userfiles/'.$old;
 3120: 	    my $newfile=$udir.'/userfiles/'.$new;
 3121: 	    if (-e $newfile) {
 3122: 		&Failure($client, "exists\n", "$cmd:$tail");
 3123: 	    } elsif (! -e $oldfile) {
 3124: 		&Failure($client, "not_found\n", "$cmd:$tail");
 3125: 	    } else {
 3126: 		if (!rename($oldfile,$newfile)) {
 3127: 		    &Failure($client, "failed\n", "$cmd:$tail");
 3128: 		} else {
 3129: 		    &Reply($client, "ok\n", "$cmd:$tail");
 3130: 		}
 3131: 	    }
 3132: 	} else {
 3133: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 3134: 	}
 3135:     }
 3136:     return 1;
 3137: }
 3138: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
 3139: 
 3140: #
 3141: #  Checks if the specified user has an active session on the server
 3142: #  return ok if so, not_found if not
 3143: #
 3144: # Parameters:
 3145: #   cmd      - The request keyword that dispatched to tus.
 3146: #   tail     - The tail of the request (colon separated parameters).
 3147: #   client   - Filehandle open on the client.
 3148: # Return:
 3149: #    1.
 3150: sub user_has_session_handler {
 3151:     my ($cmd, $tail, $client) = @_;
 3152: 
 3153:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
 3154:     
 3155:     opendir(DIR,$perlvar{'lonIDsDir'});
 3156:     my $filename;
 3157:     while ($filename=readdir(DIR)) {
 3158: 	last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
 3159:     }
 3160:     if ($filename) {
 3161: 	&Reply($client, "ok\n", "$cmd:$tail");
 3162:     } else {
 3163: 	&Failure($client, "not_found\n", "$cmd:$tail");
 3164:     }
 3165:     return 1;
 3166: 
 3167: }
 3168: &register_handler("userhassession", \&user_has_session_handler, 0,1,0);
 3169: 
 3170: sub del_usersession_handler {
 3171:     my ($cmd, $tail, $client) = @_;
 3172: 
 3173:     my $result;
 3174:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
 3175:     if (($udom =~ /^$LONCAPA::match_domain$/) && ($uname =~ /^$LONCAPA::match_username$/)) {
 3176:         my $lonidsdir = $perlvar{'lonIDsDir'};
 3177:         if (-d $lonidsdir) {
 3178:             if (opendir(DIR,$lonidsdir)) {
 3179:                 my $filename;
 3180:                 while ($filename=readdir(DIR)) {
 3181:                     if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/) {
 3182:                         if (tie(my %oldenv,'GDBM_File',"$lonidsdir/$filename",
 3183:                                 &GDBM_READER(),0640)) {
 3184:                             my $linkedfile;
 3185:                             if (exists($oldenv{'user.linkedenv'})) {
 3186:                                 $linkedfile = $oldenv{'user.linkedenv'};
 3187:                             }
 3188:                             untie(%oldenv);
 3189:                             $result = unlink("$lonidsdir/$filename");
 3190:                             if ($result) {
 3191:                                 if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
 3192:                                     if (-l "$lonidsdir/$linkedfile.id") {
 3193:                                         unlink("$lonidsdir/$linkedfile.id");
 3194:                                     }
 3195:                                 }
 3196:                             }
 3197:                         } else {
 3198:                             $result = unlink("$lonidsdir/$filename");
 3199:                         }
 3200:                         last;
 3201:                     }
 3202:                 }
 3203:             }
 3204:         }
 3205:         if ($result == 1) {
 3206:             &Reply($client, "$result\n", "$cmd:$tail");
 3207:         } else {
 3208:             &Reply($client, "not_found\n", "$cmd:$tail");
 3209:         }
 3210:     } else {
 3211:         &Failure($client, "invalid_user\n", "$cmd:$tail");
 3212:     }
 3213:     return 1;
 3214: }
 3215: 
 3216: &register_handler("delusersession", \&del_usersession_handler, 0,1,0);
 3217: 
 3218: #
 3219: #  Authenticate access to a user file by checking that the token the user's 
 3220: #  passed also exists in their session file
 3221: #
 3222: # Parameters:
 3223: #   cmd      - The request keyword that dispatched to tus.
 3224: #   tail     - The tail of the request (colon separated parameters).
 3225: #   client   - Filehandle open on the client.
 3226: # Return:
 3227: #    1.
 3228: sub token_auth_user_file_handler {
 3229:     my ($cmd, $tail, $client) = @_;
 3230: 
 3231:     my ($fname, $session) = split(/:/, $tail);
 3232:     
 3233:     chomp($session);
 3234:     my $reply="non_auth";
 3235:     my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
 3236:     if (open(ENVIN,"$file")) {
 3237: 	flock(ENVIN,LOCK_SH);
 3238: 	tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
 3239: 	if (exists($disk_env{"userfile.$fname"})) {
 3240: 	    $reply="ok";
 3241: 	} else {
 3242: 	    foreach my $envname (keys(%disk_env)) {
 3243: 		if ($envname=~ m|^userfile\.\Q$fname\E|) {
 3244: 		    $reply="ok";
 3245: 		    last;
 3246: 		}
 3247: 	    }
 3248: 	}
 3249: 	untie(%disk_env);
 3250: 	close(ENVIN);
 3251: 	&Reply($client, \$reply, "$cmd:$tail");
 3252:     } else {
 3253: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
 3254:     }
 3255:     return 1;
 3256: 
 3257: }
 3258: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
 3259: 
 3260: #
 3261: #   Unsubscribe from a resource.
 3262: #
 3263: # Parameters:
 3264: #    $cmd      - The command that got us here.
 3265: #    $tail     - Tail of the command (remaining parameters).
 3266: #    $client   - File descriptor connected to client.
 3267: # Returns
 3268: #     0        - Requested to exit, caller should shut down.
 3269: #     1        - Continue processing.
 3270: #
 3271: sub unsubscribe_handler {
 3272:     my ($cmd, $tail, $client) = @_;
 3273: 
 3274:     my $userinput= "$cmd:$tail";
 3275:     
 3276:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
 3277: 
 3278:     &Debug("Unsubscribing $fname");
 3279:     if (-e $fname) {
 3280: 	&Debug("Exists");
 3281: 	&Reply($client, &unsub($fname,$clientip), $userinput);
 3282:     } else {
 3283: 	&Failure($client, "not_found\n", $userinput);
 3284:     }
 3285:     return 1;
 3286: }
 3287: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
 3288: 
 3289: #   Subscribe to a resource
 3290: #
 3291: # Parameters:
 3292: #    $cmd      - The command that got us here.
 3293: #    $tail     - Tail of the command (remaining parameters).
 3294: #    $client   - File descriptor connected to client.
 3295: # Returns
 3296: #     0        - Requested to exit, caller should shut down.
 3297: #     1        - Continue processing.
 3298: #
 3299: sub subscribe_handler {
 3300:     my ($cmd, $tail, $client)= @_;
 3301: 
 3302:     my $userinput  = "$cmd:$tail";
 3303: 
 3304:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
 3305: 
 3306:     return 1;
 3307: }
 3308: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
 3309: 
 3310: #
 3311: #   Determine the latest version of a resource (it looks for the highest
 3312: #   past version and then returns that +1)
 3313: #
 3314: # Parameters:
 3315: #    $cmd      - The command that got us here.
 3316: #    $tail     - Tail of the command (remaining parameters).
 3317: #                 (Should consist of an absolute path to a file)
 3318: #    $client   - File descriptor connected to client.
 3319: # Returns
 3320: #     0        - Requested to exit, caller should shut down.
 3321: #     1        - Continue processing.
 3322: #
 3323: sub current_version_handler {
 3324:     my ($cmd, $tail, $client) = @_;
 3325: 
 3326:     my $userinput= "$cmd:$tail";
 3327:    
 3328:     my $fname   = $tail;
 3329:     &Reply( $client, &currentversion($fname)."\n", $userinput);
 3330:     return 1;
 3331: 
 3332: }
 3333: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
 3334: 
 3335: #  Make an entry in a user's activity log.
 3336: #
 3337: # Parameters:
 3338: #    $cmd      - The command that got us here.
 3339: #    $tail     - Tail of the command (remaining parameters).
 3340: #    $client   - File descriptor connected to client.
 3341: # Returns
 3342: #     0        - Requested to exit, caller should shut down.
 3343: #     1        - Continue processing.
 3344: #
 3345: sub activity_log_handler {
 3346:     my ($cmd, $tail, $client) = @_;
 3347: 
 3348: 
 3349:     my $userinput= "$cmd:$tail";
 3350: 
 3351:     my ($udom,$uname,$what)=split(/:/,$tail);
 3352:     chomp($what);
 3353:     my $proname=&propath($udom,$uname);
 3354:     my $now=time;
 3355:     my $hfh;
 3356:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
 3357: 	print $hfh "$now:$clientname:$what\n";
 3358: 	&Reply( $client, "ok\n", $userinput); 
 3359:     } else {
 3360: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
 3361: 		 ."while attempting log\n", 
 3362: 		 $userinput);
 3363:     }
 3364: 
 3365:     return 1;
 3366: }
 3367: &register_handler("log", \&activity_log_handler, 0, 1, 0);
 3368: 
 3369: #
 3370: #   Put a namespace entry in a user profile hash.
 3371: #   My druthers would be for this to be an encrypted interaction too.
 3372: #   anything that might be an inadvertent covert channel about either
 3373: #   user authentication or user personal information....
 3374: #
 3375: # Parameters:
 3376: #    $cmd      - The command that got us here.
 3377: #    $tail     - Tail of the command (remaining parameters).
 3378: #    $client   - File descriptor connected to client.
 3379: # Returns
 3380: #     0        - Requested to exit, caller should shut down.
 3381: #     1        - Continue processing.
 3382: #
 3383: sub put_user_profile_entry {
 3384:     my ($cmd, $tail, $client)  = @_;
 3385: 
 3386:     my $userinput = "$cmd:$tail";
 3387:     
 3388:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
 3389:     if ($namespace ne 'roles') {
 3390: 	chomp($what);
 3391: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3392: 				  &GDBM_WRCREAT(),"P",$what);
 3393: 	if($hashref) {
 3394: 	    my @pairs=split(/\&/,$what);
 3395: 	    foreach my $pair (@pairs) {
 3396: 		my ($key,$value)=split(/=/,$pair);
 3397: 		$hashref->{$key}=$value;
 3398: 	    }
 3399: 	    if (&untie_user_hash($hashref)) {
 3400: 		&Reply( $client, "ok\n", $userinput);
 3401: 	    } else {
 3402: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 3403: 			"while attempting put\n", 
 3404: 			$userinput);
 3405: 	    }
 3406: 	} else {
 3407: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3408: 		     "while attempting put\n", $userinput);
 3409: 	}
 3410:     } else {
 3411:         &Failure( $client, "refused\n", $userinput);
 3412:     }
 3413:     
 3414:     return 1;
 3415: }
 3416: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
 3417: 
 3418: #   Put a piece of new data in hash, returns error if entry already exists
 3419: # Parameters:
 3420: #    $cmd      - The command that got us here.
 3421: #    $tail     - Tail of the command (remaining parameters).
 3422: #    $client   - File descriptor connected to client.
 3423: # Returns
 3424: #     0        - Requested to exit, caller should shut down.
 3425: #     1        - Continue processing.
 3426: #
 3427: sub newput_user_profile_entry {
 3428:     my ($cmd, $tail, $client)  = @_;
 3429: 
 3430:     my $userinput = "$cmd:$tail";
 3431: 
 3432:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
 3433:     if ($namespace eq 'roles') {
 3434:         &Failure( $client, "refused\n", $userinput);
 3435: 	return 1;
 3436:     }
 3437: 
 3438:     chomp($what);
 3439: 
 3440:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3441: 				 &GDBM_WRCREAT(),"N",$what);
 3442:     if(!$hashref) {
 3443: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3444: 		  "while attempting put\n", $userinput);
 3445: 	return 1;
 3446:     }
 3447: 
 3448:     my @pairs=split(/\&/,$what);
 3449:     foreach my $pair (@pairs) {
 3450: 	my ($key,$value)=split(/=/,$pair);
 3451: 	if (exists($hashref->{$key})) {
 3452:             if (!&untie_user_hash($hashref)) {
 3453:                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
 3454:                          "while attempting newput - early out as key exists");
 3455:             }
 3456:             &Failure($client, "key_exists: ".$key."\n",$userinput);
 3457:             return 1;
 3458: 	}
 3459:     }
 3460: 
 3461:     foreach my $pair (@pairs) {
 3462: 	my ($key,$value)=split(/=/,$pair);
 3463: 	$hashref->{$key}=$value;
 3464:     }
 3465: 
 3466:     if (&untie_user_hash($hashref)) {
 3467: 	&Reply( $client, "ok\n", $userinput);
 3468:     } else {
 3469: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 3470: 		 "while attempting put\n", 
 3471: 		 $userinput);
 3472:     }
 3473:     return 1;
 3474: }
 3475: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
 3476: 
 3477: # 
 3478: #   Increment a profile entry in the user history file.
 3479: #   The history contains keyword value pairs.  In this case,
 3480: #   The value itself is a pair of numbers.  The first, the current value
 3481: #   the second an increment that this function applies to the current
 3482: #   value.
 3483: #
 3484: # Parameters:
 3485: #    $cmd      - The command that got us here.
 3486: #    $tail     - Tail of the command (remaining parameters).
 3487: #    $client   - File descriptor connected to client.
 3488: # Returns
 3489: #     0        - Requested to exit, caller should shut down.
 3490: #     1        - Continue processing.
 3491: #
 3492: sub increment_user_value_handler {
 3493:     my ($cmd, $tail, $client) = @_;
 3494:     
 3495:     my $userinput   = "$cmd:$tail";
 3496:     
 3497:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
 3498:     if ($namespace ne 'roles') {
 3499:         chomp($what);
 3500: 	my $hashref = &tie_user_hash($udom, $uname,
 3501: 				     $namespace, &GDBM_WRCREAT(),
 3502: 				     "P",$what);
 3503: 	if ($hashref) {
 3504: 	    my @pairs=split(/\&/,$what);
 3505: 	    foreach my $pair (@pairs) {
 3506: 		my ($key,$value)=split(/=/,$pair);
 3507:                 $value = &unescape($value);
 3508: 		# We could check that we have a number...
 3509: 		if (! defined($value) || $value eq '') {
 3510: 		    $value = 1;
 3511: 		}
 3512: 		$hashref->{$key}+=$value;
 3513:                 if ($namespace eq 'nohist_resourcetracker') {
 3514:                     if ($hashref->{$key} < 0) {
 3515:                         $hashref->{$key} = 0;
 3516:                     }
 3517:                 }
 3518: 	    }
 3519: 	    if (&untie_user_hash($hashref)) {
 3520: 		&Reply( $client, "ok\n", $userinput);
 3521: 	    } else {
 3522: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 3523: 			 "while attempting inc\n", $userinput);
 3524: 	    }
 3525: 	} else {
 3526: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3527: 		     "while attempting inc\n", $userinput);
 3528: 	}
 3529:     } else {
 3530: 	&Failure($client, "refused\n", $userinput);
 3531:     }
 3532:     
 3533:     return 1;
 3534: }
 3535: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
 3536: 
 3537: #
 3538: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
 3539: #   Each 'role' a user has implies a set of permissions.  Adding a new role
 3540: #   for a person grants the permissions packaged with that role
 3541: #   to that user when the role is selected.
 3542: #
 3543: # Parameters:
 3544: #    $cmd       - The command string (rolesput).
 3545: #    $tail      - The remainder of the request line.  For rolesput this
 3546: #                 consists of a colon separated list that contains:
 3547: #                 The domain and user that is granting the role (logged).
 3548: #                 The domain and user that is getting the role.
 3549: #                 The roles being granted as a set of & separated pairs.
 3550: #                 each pair a key value pair.
 3551: #    $client    - File descriptor connected to the client.
 3552: # Returns:
 3553: #     0         - If the daemon should exit
 3554: #     1         - To continue processing.
 3555: #
 3556: #
 3557: sub roles_put_handler {
 3558:     my ($cmd, $tail, $client) = @_;
 3559: 
 3560:     my $userinput  = "$cmd:$tail";
 3561: 
 3562:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
 3563:     
 3564: 
 3565:     my $namespace='roles';
 3566:     chomp($what);
 3567:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3568: 				 &GDBM_WRCREAT(), "P",
 3569: 				 "$exedom:$exeuser:$what");
 3570:     #
 3571:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
 3572:     #  handle is open for the minimal amount of time.  Since the flush
 3573:     #  is done on close this improves the chances the log will be an un-
 3574:     #  corrupted ordered thing.
 3575:     if ($hashref) {
 3576: 	my $pass_entry = &get_auth_type($udom, $uname);
 3577: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
 3578: 	$auth_type = $auth_type.":";
 3579: 	my @pairs=split(/\&/,$what);
 3580: 	foreach my $pair (@pairs) {
 3581: 	    my ($key,$value)=split(/=/,$pair);
 3582: 	    &manage_permissions($key, $udom, $uname,
 3583: 			       $auth_type);
 3584: 	    $hashref->{$key}=$value;
 3585: 	}
 3586: 	if (&untie_user_hash($hashref)) {
 3587: 	    &Reply($client, "ok\n", $userinput);
 3588: 	} else {
 3589: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 3590: 		     "while attempting rolesput\n", $userinput);
 3591: 	}
 3592:     } else {
 3593: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3594: 		 "while attempting rolesput\n", $userinput);
 3595:     }
 3596:     return 1;
 3597: }
 3598: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
 3599: 
 3600: #
 3601: #   Deletes (removes) a role for a user.   This is equivalent to removing
 3602: #  a permissions package associated with the role from the user's profile.
 3603: #
 3604: # Parameters:
 3605: #     $cmd                 - The command (rolesdel)
 3606: #     $tail                - The remainder of the request line. This consists
 3607: #                             of:
 3608: #                             The domain and user requesting the change (logged)
 3609: #                             The domain and user being changed.
 3610: #                             The roles being revoked.  These are shipped to us
 3611: #                             as a bunch of & separated role name keywords.
 3612: #     $client              - The file handle open on the client.
 3613: # Returns:
 3614: #     1                    - Continue processing
 3615: #     0                    - Exit.
 3616: #
 3617: sub roles_delete_handler {
 3618:     my ($cmd, $tail, $client)  = @_;
 3619: 
 3620:     my $userinput    = "$cmd:$tail";
 3621:    
 3622:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
 3623:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
 3624: 	   "what = ".$what);
 3625:     my $namespace='roles';
 3626:     chomp($what);
 3627:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3628: 				 &GDBM_WRCREAT(), "D",
 3629: 				 "$exedom:$exeuser:$what");
 3630:     
 3631:     if ($hashref) {
 3632: 	my @rolekeys=split(/\&/,$what);
 3633: 	
 3634: 	foreach my $key (@rolekeys) {
 3635: 	    delete $hashref->{$key};
 3636: 	}
 3637: 	if (&untie_user_hash($hashref)) {
 3638: 	    &Reply($client, "ok\n", $userinput);
 3639: 	} else {
 3640: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 3641: 		     "while attempting rolesdel\n", $userinput);
 3642: 	}
 3643:     } else {
 3644:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3645: 		 "while attempting rolesdel\n", $userinput);
 3646:     }
 3647:     
 3648:     return 1;
 3649: }
 3650: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
 3651: 
 3652: # Unencrypted get from a user's profile database.  See 
 3653: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
 3654: # This function retrieves a keyed item from a specific named database in the
 3655: # user's directory.
 3656: #
 3657: # Parameters:
 3658: #   $cmd             - Command request keyword (get).
 3659: #   $tail            - Tail of the command.  This is a colon separated list
 3660: #                      consisting of the domain and username that uniquely
 3661: #                      identifies the profile,
 3662: #                      The 'namespace' which selects the gdbm file to 
 3663: #                      do the lookup in, 
 3664: #                      & separated list of keys to lookup.  Note that
 3665: #                      the values are returned as an & separated list too.
 3666: #   $client          - File descriptor open on the client.
 3667: # Returns:
 3668: #   1       - Continue processing.
 3669: #   0       - Exit.
 3670: #
 3671: sub get_profile_entry {
 3672:     my ($cmd, $tail, $client) = @_;
 3673: 
 3674:     my $userinput= "$cmd:$tail";
 3675:    
 3676:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 3677:     chomp($what);
 3678: 
 3679: 
 3680:     my $replystring = read_profile($udom, $uname, $namespace, $what);
 3681:     my ($first) = split(/:/,$replystring);
 3682:     if($first ne "error") {
 3683: 	&Reply($client, \$replystring, $userinput);
 3684:     } else {
 3685: 	&Failure($client, $replystring." while attempting get\n", $userinput);
 3686:     }
 3687:     return 1;
 3688: 
 3689: 
 3690: }
 3691: &register_handler("get", \&get_profile_entry, 0,1,0);
 3692: 
 3693: #
 3694: #  Process the encrypted get request.  Note that the request is sent
 3695: #  in clear, but the reply is encrypted.  This is a small covert channel:
 3696: #  information about the sensitive keys is given to the snooper.  Just not
 3697: #  information about the values of the sensitive key.  Hmm if I wanted to
 3698: #  know these I'd snoop for the egets. Get the profile item names from them
 3699: #  and then issue a get for them since there's no enforcement of the
 3700: #  requirement of an encrypted get for particular profile items.  If I
 3701: #  were re-doing this, I'd force the request to be encrypted as well as the
 3702: #  reply.  I'd also just enforce encrypted transactions for all gets since
 3703: #  that would prevent any covert channel snooping.
 3704: #
 3705: #  Parameters:
 3706: #     $cmd               - Command keyword of request (eget).
 3707: #     $tail              - Tail of the command.  See GetProfileEntry
 3708: #                          for more information about this.
 3709: #     $client            - File open on the client.
 3710: #  Returns:
 3711: #     1      - Continue processing
 3712: #     0      - server should exit.
 3713: sub get_profile_entry_encrypted {
 3714:     my ($cmd, $tail, $client) = @_;
 3715: 
 3716:     my $userinput = "$cmd:$tail";
 3717:    
 3718:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 3719:     chomp($what);
 3720:     my $qresult = read_profile($udom, $uname, $namespace, $what);
 3721:     my ($first) = split(/:/, $qresult);
 3722:     if($first ne "error") {
 3723: 	
 3724: 	if ($cipher) {
 3725: 	    my $cmdlength=length($qresult);
 3726: 	    $qresult.="         ";
 3727: 	    my $encqresult='';
 3728: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 3729: 		$encqresult.= unpack("H16", 
 3730: 				     $cipher->encrypt(substr($qresult,
 3731: 							     $encidx,
 3732: 							     8)));
 3733: 	    }
 3734: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
 3735: 	} else {
 3736: 		&Failure( $client, "error:no_key\n", $userinput);
 3737: 	    }
 3738:     } else {
 3739: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
 3740: 
 3741:     }
 3742:     
 3743:     return 1;
 3744: }
 3745: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
 3746: 
 3747: #
 3748: #   Deletes a key in a user profile database.
 3749: #   
 3750: #   Parameters:
 3751: #       $cmd                  - Command keyword (del).
 3752: #       $tail                 - Command tail.  IN this case a colon
 3753: #                               separated list containing:
 3754: #                               The domain and user that identifies uniquely
 3755: #                               the identity of the user.
 3756: #                               The profile namespace (name of the profile
 3757: #                               database file).
 3758: #                               & separated list of keywords to delete.
 3759: #       $client              - File open on client socket.
 3760: # Returns:
 3761: #     1   - Continue processing
 3762: #     0   - Exit server.
 3763: #
 3764: #
 3765: sub delete_profile_entry {
 3766:     my ($cmd, $tail, $client) = @_;
 3767: 
 3768:     my $userinput = "cmd:$tail";
 3769: 
 3770:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 3771:     chomp($what);
 3772:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3773: 				 &GDBM_WRCREAT(),
 3774: 				 "D",$what);
 3775:     if ($hashref) {
 3776:         my @keys=split(/\&/,$what);
 3777: 	foreach my $key (@keys) {
 3778: 	    delete($hashref->{$key});
 3779: 	}
 3780: 	if (&untie_user_hash($hashref)) {
 3781: 	    &Reply($client, "ok\n", $userinput);
 3782: 	} else {
 3783: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3784: 		    "while attempting del\n", $userinput);
 3785: 	}
 3786:     } else {
 3787: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3788: 		 "while attempting del\n", $userinput);
 3789:     }
 3790:     return 1;
 3791: }
 3792: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
 3793: 
 3794: #
 3795: #  List the set of keys that are defined in a profile database file.
 3796: #  A successful reply from this will contain an & separated list of
 3797: #  the keys. 
 3798: # Parameters:
 3799: #     $cmd              - Command request (keys).
 3800: #     $tail             - Remainder of the request, a colon separated
 3801: #                         list containing domain/user that identifies the
 3802: #                         user being queried, and the database namespace
 3803: #                         (database filename essentially).
 3804: #     $client           - File open on the client.
 3805: #  Returns:
 3806: #    1    - Continue processing.
 3807: #    0    - Exit the server.
 3808: #
 3809: sub get_profile_keys {
 3810:     my ($cmd, $tail, $client) = @_;
 3811: 
 3812:     my $userinput = "$cmd:$tail";
 3813: 
 3814:     my ($udom,$uname,$namespace)=split(/:/,$tail);
 3815:     my $qresult='';
 3816:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3817: 				  &GDBM_READER());
 3818:     if ($hashref) {
 3819: 	foreach my $key (keys %$hashref) {
 3820: 	    $qresult.="$key&";
 3821: 	}
 3822: 	if (&untie_user_hash($hashref)) {
 3823: 	    $qresult=~s/\&$//;
 3824: 	    &Reply($client, \$qresult, $userinput);
 3825: 	} else {
 3826: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3827: 		    "while attempting keys\n", $userinput);
 3828: 	}
 3829:     } else {
 3830: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3831: 		 "while attempting keys\n", $userinput);
 3832:     }
 3833:    
 3834:     return 1;
 3835: }
 3836: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
 3837: 
 3838: #
 3839: #   Dump the contents of a user profile database.
 3840: #   Note that this constitutes a very large covert channel too since
 3841: #   the dump will return sensitive information that is not encrypted.
 3842: #   The naive security assumption is that the session negotiation ensures
 3843: #   our client is trusted and I don't believe that's assured at present.
 3844: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
 3845: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
 3846: # 
 3847: #  Parameters:
 3848: #     $cmd           - The command request keyword (currentdump).
 3849: #     $tail          - Remainder of the request, consisting of a colon
 3850: #                      separated list that has the domain/username and
 3851: #                      the namespace to dump (database file).
 3852: #     $client        - file open on the remote client.
 3853: # Returns:
 3854: #     1    - Continue processing.
 3855: #     0    - Exit the server.
 3856: #
 3857: sub dump_profile_database {
 3858:     my ($cmd, $tail, $client) = @_;
 3859: 
 3860:     my $res = LONCAPA::Lond::dump_profile_database($tail);
 3861: 
 3862:     if ($res =~ /^error:/) {
 3863:         Failure($client, \$res, "$cmd:$tail");
 3864:     } else {
 3865:         Reply($client, \$res, "$cmd:$tail");
 3866:     }
 3867: 
 3868:     return 1;  
 3869: 
 3870:     #TODO remove 
 3871:     my $userinput = "$cmd:$tail";
 3872:    
 3873:     my ($udom,$uname,$namespace) = split(/:/,$tail);
 3874:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 3875: 				 &GDBM_READER());
 3876:     if ($hashref) {
 3877: 	# Structure of %data:
 3878: 	# $data{$symb}->{$parameter}=$value;
 3879: 	# $data{$symb}->{'v.'.$parameter}=$version;
 3880: 	# since $parameter will be unescaped, we do not
 3881:  	# have to worry about silly parameter names...
 3882: 	
 3883:         my $qresult='';
 3884: 	my %data = ();                     # A hash of anonymous hashes..
 3885: 	while (my ($key,$value) = each(%$hashref)) {
 3886: 	    my ($v,$symb,$param) = split(/:/,$key);
 3887: 	    next if ($v eq 'version' || $symb eq 'keys');
 3888: 	    next if (exists($data{$symb}) && 
 3889: 		     exists($data{$symb}->{$param}) &&
 3890: 		     $data{$symb}->{'v.'.$param} > $v);
 3891: 	    $data{$symb}->{$param}=$value;
 3892: 	    $data{$symb}->{'v.'.$param}=$v;
 3893: 	}
 3894: 	if (&untie_user_hash($hashref)) {
 3895: 	    while (my ($symb,$param_hash) = each(%data)) {
 3896: 		while(my ($param,$value) = each (%$param_hash)){
 3897: 		    next if ($param =~ /^v\./);       # Ignore versions...
 3898: 		    #
 3899: 		    #   Just dump the symb=value pairs separated by &
 3900: 		    #
 3901: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
 3902: 		}
 3903: 	    }
 3904: 	    chop($qresult);
 3905: 	    &Reply($client , \$qresult, $userinput);
 3906: 	} else {
 3907: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 3908: 		     "while attempting currentdump\n", $userinput);
 3909: 	}
 3910:     } else {
 3911: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3912: 		"while attempting currentdump\n", $userinput);
 3913:     }
 3914: 
 3915:     return 1;
 3916: }
 3917: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
 3918: 
 3919: #
 3920: #   Dump a profile database with an optional regular expression
 3921: #   to match against the keys.  In this dump, no effort is made
 3922: #   to separate symb from version information. Presumably the
 3923: #   databases that are dumped by this command are of a different
 3924: #   structure.  Need to look at this and improve the documentation of
 3925: #   both this and the currentdump handler.
 3926: # Parameters:
 3927: #    $cmd                     - The command keyword.
 3928: #    $tail                    - All of the characters after the $cmd:
 3929: #                               These are expected to be a colon
 3930: #                               separated list containing:
 3931: #                               domain/user - identifying the user.
 3932: #                               namespace   - identifying the database.
 3933: #                               regexp      - optional regular expression
 3934: #                                             that is matched against
 3935: #                                             database keywords to do
 3936: #                                             selective dumps.
 3937: #                               range       - optional range of entries
 3938: #                                             e.g., 10-20 would return the
 3939: #                                             10th to 19th items, etc.  
 3940: #   $client                   - Channel open on the client.
 3941: # Returns:
 3942: #    1    - Continue processing.
 3943: # Side effects:
 3944: #    response is written to $client.
 3945: #
 3946: sub dump_with_regexp {
 3947:     my ($cmd, $tail, $client) = @_;
 3948: 
 3949:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
 3950:     
 3951:     if ($res =~ /^error:/) {
 3952:         Failure($client, \$res, "$cmd:$tail");
 3953:     } else {
 3954:         Reply($client, \$res, "$cmd:$tail");
 3955:     }
 3956: 
 3957:     return 1;
 3958: }
 3959: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
 3960: 
 3961: #
 3962: #  Process the encrypted dump request. Original call should
 3963: #  be from lonnet::dump() with seventh arg ($encrypt) set to
 3964: #  1, to ensure that both request and response are encrypted.
 3965: #
 3966: #  Parameters:
 3967: #     $cmd               - Command keyword of request (edump).
 3968: #     $tail              - Tail of the command.
 3969: #                          See &dump_with_regexp for more
 3970: #                          information about this.
 3971: #     $client            - File open on the client.
 3972: #  Returns:
 3973: #     1      - Continue processing
 3974: #     0      - server should exit.
 3975: #
 3976: 
 3977: sub encrypted_dump_with_regexp {
 3978:     my ($cmd, $tail, $client) = @_;
 3979:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
 3980: 
 3981:     if ($res =~ /^error:/) {
 3982:         Failure($client, \$res, "$cmd:$tail");
 3983:     } else {
 3984:         if ($cipher) {
 3985:             my $cmdlength=length($res);
 3986:             $res.="         ";
 3987:             my $encres='';
 3988:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 3989:                 $encres.= unpack("H16",
 3990:                                  $cipher->encrypt(substr($res,
 3991:                                                          $encidx,
 3992:                                                          8)));
 3993:             }
 3994:             &Reply( $client,"enc:$cmdlength:$encres\n","$cmd:$tail");
 3995:         } else {
 3996:             &Failure( $client, "error:no_key\n","$cmd:$tail");
 3997:         }
 3998:     }
 3999: }
 4000: &register_handler("edump", \&encrypted_dump_with_regexp, 0, 1, 0);
 4001: 
 4002: #  Store a set of key=value pairs associated with a versioned name.
 4003: #
 4004: #  Parameters:
 4005: #    $cmd                - Request command keyword.
 4006: #    $tail               - Tail of the request.  This is a colon
 4007: #                          separated list containing:
 4008: #                          domain/user - User and authentication domain.
 4009: #                          namespace   - Name of the database being modified
 4010: #                          rid         - Resource keyword to modify.
 4011: #                          what        - new value associated with rid.
 4012: #                          laststore   - (optional) version=timestamp
 4013: #                                        for most recent transaction for rid
 4014: #                                        in namespace, when cstore was called
 4015: #
 4016: #    $client             - Socket open on the client.
 4017: #
 4018: #
 4019: #  Returns:
 4020: #      1 (keep on processing).
 4021: #  Side-Effects:
 4022: #    Writes to the client
 4023: #    Successful storage will cause either 'ok', or, if $laststore was included
 4024: #    in the tail of the request, and the version number for the last transaction
 4025: #    is larger than the version in $laststore, delay:$numtrans , where $numtrans
 4026: #    is the number of store evevnts recorded for rid in namespace since
 4027: #    lonnet::store() was called by the client.
 4028: #
 4029: sub store_handler {
 4030:     my ($cmd, $tail, $client) = @_;
 4031:  
 4032:     my $userinput = "$cmd:$tail";
 4033:     chomp($tail);
 4034:     my ($udom,$uname,$namespace,$rid,$what,$laststore) =split(/:/,$tail);
 4035:     if ($namespace ne 'roles') {
 4036: 
 4037: 	my @pairs=split(/\&/,$what);
 4038: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
 4039: 				       &GDBM_WRCREAT(), "S",
 4040: 				       "$rid:$what");
 4041: 	if ($hashref) {
 4042: 	    my $now = time;
 4043:             my $numtrans;
 4044:             if ($laststore) {
 4045:                 my ($previousversion,$previoustime) = split(/\=/,$laststore);
 4046:                 my ($lastversion,$lasttime) = (0,0);
 4047:                 $lastversion = $hashref->{"version:$rid"};
 4048:                 if ($lastversion) {
 4049:                     $lasttime = $hashref->{"$lastversion:$rid:timestamp"};
 4050:                 }
 4051:                 if (($previousversion) && ($previousversion !~ /\D/)) {
 4052:                     if (($lastversion > $previousversion) && ($lasttime >= $previoustime)) {
 4053:                         $numtrans = $lastversion - $previousversion;
 4054:                     }
 4055:                 } elsif ($lastversion) {
 4056:                     $numtrans = $lastversion;
 4057:                 }
 4058:                 if ($numtrans) {
 4059:                     $numtrans =~ s/D//g;
 4060:                 }
 4061:             }
 4062: 	    $hashref->{"version:$rid"}++;
 4063: 	    my $version=$hashref->{"version:$rid"};
 4064: 	    my $allkeys=''; 
 4065: 	    foreach my $pair (@pairs) {
 4066: 		my ($key,$value)=split(/=/,$pair);
 4067: 		$allkeys.=$key.':';
 4068: 		$hashref->{"$version:$rid:$key"}=$value;
 4069: 	    }
 4070: 	    $hashref->{"$version:$rid:timestamp"}=$now;
 4071: 	    $allkeys.='timestamp';
 4072: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
 4073: 	    if (&untie_user_hash($hashref)) {
 4074:                 my $msg = 'ok';
 4075:                 if ($numtrans) {
 4076:                     $msg = 'delay:'.$numtrans;
 4077:                 }
 4078: 		&Reply($client, "$msg\n", $userinput);
 4079: 	    } else {
 4080: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4081: 			"while attempting store\n", $userinput);
 4082: 	    }
 4083: 	} else {
 4084: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 4085: 		     "while attempting store\n", $userinput);
 4086: 	}
 4087:     } else {
 4088: 	&Failure($client, "refused\n", $userinput);
 4089:     }
 4090: 
 4091:     return 1;
 4092: }
 4093: &register_handler("store", \&store_handler, 0, 1, 0);
 4094: 
 4095: #  Modify a set of key=value pairs associated with a versioned name.
 4096: #
 4097: #  Parameters:
 4098: #    $cmd                - Request command keyword.
 4099: #    $tail               - Tail of the request.  This is a colon
 4100: #                          separated list containing:
 4101: #                          domain/user - User and authentication domain.
 4102: #                          namespace   - Name of the database being modified
 4103: #                          rid         - Resource keyword to modify.
 4104: #                          v           - Version item to modify
 4105: #                          what        - new value associated with rid.
 4106: #
 4107: #    $client             - Socket open on the client.
 4108: #
 4109: #
 4110: #  Returns:
 4111: #      1 (keep on processing).
 4112: #  Side-Effects:
 4113: #    Writes to the client
 4114: sub putstore_handler {
 4115:     my ($cmd, $tail, $client) = @_;
 4116:  
 4117:     my $userinput = "$cmd:$tail";
 4118: 
 4119:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
 4120:     if ($namespace ne 'roles') {
 4121: 
 4122: 	chomp($what);
 4123: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
 4124: 				       &GDBM_WRCREAT(), "M",
 4125: 				       "$rid:$v:$what");
 4126: 	if ($hashref) {
 4127: 	    my $now = time;
 4128: 	    my %data = &hash_extract($what);
 4129: 	    my @allkeys;
 4130: 	    while (my($key,$value) = each(%data)) {
 4131: 		push(@allkeys,$key);
 4132: 		$hashref->{"$v:$rid:$key"} = $value;
 4133: 	    }
 4134: 	    my $allkeys = join(':',@allkeys);
 4135: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
 4136: 
 4137: 	    if (&untie_user_hash($hashref)) {
 4138: 		&Reply($client, "ok\n", $userinput);
 4139: 	    } else {
 4140: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4141: 			"while attempting store\n", $userinput);
 4142: 	    }
 4143: 	} else {
 4144: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 4145: 		     "while attempting store\n", $userinput);
 4146: 	}
 4147:     } else {
 4148: 	&Failure($client, "refused\n", $userinput);
 4149:     }
 4150: 
 4151:     return 1;
 4152: }
 4153: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
 4154: 
 4155: sub hash_extract {
 4156:     my ($str)=@_;
 4157:     my %hash;
 4158:     foreach my $pair (split(/\&/,$str)) {
 4159: 	my ($key,$value)=split(/=/,$pair);
 4160: 	$hash{$key}=$value;
 4161:     }
 4162:     return (%hash);
 4163: }
 4164: sub hash_to_str {
 4165:     my ($hash_ref)=@_;
 4166:     my $str;
 4167:     foreach my $key (keys(%$hash_ref)) {
 4168: 	$str.=$key.'='.$hash_ref->{$key}.'&';
 4169:     }
 4170:     $str=~s/\&$//;
 4171:     return $str;
 4172: }
 4173: 
 4174: #
 4175: #  Dump out all versions of a resource that has key=value pairs associated
 4176: # with it for each version.  These resources are built up via the store
 4177: # command.
 4178: #
 4179: #  Parameters:
 4180: #     $cmd               - Command keyword.
 4181: #     $tail              - Remainder of the request which consists of:
 4182: #                          domain/user   - User and auth. domain.
 4183: #                          namespace     - name of resource database.
 4184: #                          rid           - Resource id.
 4185: #    $client             - socket open on the client.
 4186: #
 4187: # Returns:
 4188: #      1  indicating the caller should not yet exit.
 4189: # Side-effects:
 4190: #   Writes a reply to the client.
 4191: #   The reply is a string of the following shape:
 4192: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
 4193: #    Where the 1 above represents version 1.
 4194: #    this continues for all pairs of keys in all versions.
 4195: #
 4196: #
 4197: #    
 4198: #
 4199: sub restore_handler {
 4200:     my ($cmd, $tail, $client) = @_;
 4201: 
 4202:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
 4203:     my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
 4204:     $namespace=~s/\//\_/g;
 4205:     $namespace = &LONCAPA::clean_username($namespace);
 4206: 
 4207:     chomp($rid);
 4208:     my $qresult='';
 4209:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
 4210:     if ($hashref) {
 4211: 	my $version=$hashref->{"version:$rid"};
 4212: 	$qresult.="version=$version&";
 4213: 	my $scope;
 4214: 	for ($scope=1;$scope<=$version;$scope++) {
 4215: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
 4216: 	    my @keys=split(/:/,$vkeys);
 4217: 	    my $key;
 4218: 	    $qresult.="$scope:keys=$vkeys&";
 4219: 	    foreach $key (@keys) {
 4220: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
 4221: 	    }                                  
 4222: 	}
 4223: 	if (&untie_user_hash($hashref)) {
 4224: 	    $qresult=~s/\&$//;
 4225: 	    &Reply( $client, \$qresult, $userinput);
 4226: 	} else {
 4227: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4228: 		    "while attempting restore\n", $userinput);
 4229: 	}
 4230:     } else {
 4231: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 4232: 		"while attempting restore\n", $userinput);
 4233:     }
 4234:   
 4235:     return 1;
 4236: 
 4237: 
 4238: }
 4239: &register_handler("restore", \&restore_handler, 0,1,0);
 4240: 
 4241: #
 4242: #   Add a chat message to a synchronous discussion board.
 4243: #
 4244: # Parameters:
 4245: #    $cmd                - Request keyword.
 4246: #    $tail               - Tail of the command. A colon separated list
 4247: #                          containing:
 4248: #                          cdom    - Domain on which the chat board lives
 4249: #                          cnum    - Course containing the chat board.
 4250: #                          newpost - Body of the posting.
 4251: #                          group   - Optional group, if chat board is only 
 4252: #                                    accessible in a group within the course 
 4253: #   $client              - Socket open on the client.
 4254: # Returns:
 4255: #   1    - Indicating caller should keep on processing.
 4256: #
 4257: # Side-effects:
 4258: #   writes a reply to the client.
 4259: #
 4260: #
 4261: sub send_chat_handler {
 4262:     my ($cmd, $tail, $client) = @_;
 4263: 
 4264:     
 4265:     my $userinput = "$cmd:$tail";
 4266: 
 4267:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
 4268:     &chat_add($cdom,$cnum,$newpost,$group);
 4269:     &Reply($client, "ok\n", $userinput);
 4270: 
 4271:     return 1;
 4272: }
 4273: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
 4274: 
 4275: #
 4276: #   Retrieve the set of chat messages from a discussion board.
 4277: #
 4278: #  Parameters:
 4279: #    $cmd             - Command keyword that initiated the request.
 4280: #    $tail            - Remainder of the request after the command
 4281: #                       keyword.  In this case a colon separated list of
 4282: #                       chat domain    - Which discussion board.
 4283: #                       chat id        - Discussion thread(?)
 4284: #                       domain/user    - Authentication domain and username
 4285: #                                        of the requesting person.
 4286: #                       group          - Optional course group containing
 4287: #                                        the board.      
 4288: #   $client           - Socket open on the client program.
 4289: # Returns:
 4290: #    1     - continue processing
 4291: # Side effects:
 4292: #    Response is written to the client.
 4293: #
 4294: sub retrieve_chat_handler {
 4295:     my ($cmd, $tail, $client) = @_;
 4296: 
 4297: 
 4298:     my $userinput = "$cmd:$tail";
 4299: 
 4300:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
 4301:     my $reply='';
 4302:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
 4303: 	$reply.=&escape($_).':';
 4304:     }
 4305:     $reply=~s/\:$//;
 4306:     &Reply($client, \$reply, $userinput);
 4307: 
 4308: 
 4309:     return 1;
 4310: }
 4311: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
 4312: 
 4313: #
 4314: #  Initiate a query of an sql database.  SQL query repsonses get put in
 4315: #  a file for later retrieval.  This prevents sql query results from
 4316: #  bottlenecking the system.  Note that with loncnew, perhaps this is
 4317: #  less of an issue since multiple outstanding requests can be concurrently
 4318: #  serviced.
 4319: #
 4320: #  Parameters:
 4321: #     $cmd       - Command keyword that initiated the request.
 4322: #     $tail      - Remainder of the command after the keyword.
 4323: #                  For this function, this consists of a query and
 4324: #                  3 arguments that are self-documentingly labelled
 4325: #                  in the original arg1, arg2, arg3.
 4326: #     $client    - Socket open on the client.
 4327: # Return:
 4328: #    1   - Indicating processing should continue.
 4329: # Side-effects:
 4330: #    a reply is written to $client.
 4331: #
 4332: sub send_query_handler {
 4333:     my ($cmd, $tail, $client) = @_;
 4334: 
 4335:     my $userinput = "$cmd:$tail";
 4336: 
 4337:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
 4338:     $query=~s/\n*$//g;
 4339:     if (($query eq 'usersearch') || ($query eq 'instdirsearch')) {
 4340:         my $usersearchconf = &get_usersearch_config($currentdomainid,'directorysrch');
 4341:         my $earlyout;
 4342:         if (ref($usersearchconf) eq 'HASH') {
 4343:             if ($currentdomainid eq $clienthomedom) {
 4344:                 if ($query eq 'usersearch') {
 4345:                     if ($usersearchconf->{'lcavailable'} eq '0') {
 4346:                         $earlyout = 1;
 4347:                     }
 4348:                 } else {
 4349:                     if ($usersearchconf->{'available'} eq '0') {
 4350:                         $earlyout = 1;
 4351:                     }
 4352:                 }
 4353:             } else {
 4354:                 if ($query eq 'usersearch') {
 4355:                     if ($usersearchconf->{'lclocalonly'}) {
 4356:                         $earlyout = 1;
 4357:                     }
 4358:                 } else {
 4359:                     if ($usersearchconf->{'localonly'}) {
 4360:                         $earlyout = 1;
 4361:                     }
 4362:                 }
 4363:             }
 4364:         }
 4365:         if ($earlyout) {
 4366:             &Reply($client, "query_not_authorized\n");
 4367:             return 1;
 4368:         }
 4369:     }
 4370:     &Reply($client, "". &sql_reply("$clientname\&$query".
 4371: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
 4372: 	  $userinput);
 4373:     
 4374:     return 1;
 4375: }
 4376: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
 4377: 
 4378: #
 4379: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
 4380: #   The query is submitted via a "querysend" transaction.
 4381: #   There it is passed on to the lonsql daemon, queued and issued to
 4382: #   mysql.
 4383: #     This transaction is invoked when the sql transaction is complete
 4384: #   it stores the query results in flie and indicates query completion.
 4385: #   presumably local software then fetches this response... I'm guessing
 4386: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
 4387: #   lonsql on completion of the query interacts with the lond of our
 4388: #   client to do a query reply storing two files:
 4389: #    - id     - The results of the query.
 4390: #    - id.end - Indicating the transaction completed. 
 4391: #    NOTE: id is a unique id assigned to the query and querysend time.
 4392: # Parameters:
 4393: #    $cmd        - Command keyword that initiated this request.
 4394: #    $tail       - Remainder of the tail.  In this case that's a colon
 4395: #                  separated list containing the query Id and the 
 4396: #                  results of the query.
 4397: #    $client     - Socket open on the client.
 4398: # Return:
 4399: #    1           - Indicating that we should continue processing.
 4400: # Side effects:
 4401: #    ok written to the client.
 4402: #
 4403: sub reply_query_handler {
 4404:     my ($cmd, $tail, $client) = @_;
 4405: 
 4406: 
 4407:     my $userinput = "$cmd:$tail";
 4408: 
 4409:     my ($id,$reply)=split(/:/,$tail); 
 4410:     my $store;
 4411:     my $execdir=$perlvar{'lonDaemons'};
 4412:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
 4413: 	$reply=~s/\&/\n/g;
 4414: 	print $store $reply;
 4415: 	close $store;
 4416: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
 4417: 	print $store2 "done\n";
 4418: 	close $store2;
 4419: 	&Reply($client, "ok\n", $userinput);
 4420:     } else {
 4421: 	&Failure($client, "error: ".($!+0)
 4422: 		." IO::File->new Failed ".
 4423: 		"while attempting queryreply\n", $userinput);
 4424:     }
 4425:  
 4426: 
 4427:     return 1;
 4428: }
 4429: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
 4430: 
 4431: #
 4432: #  Process the courseidput request.  Not quite sure what this means
 4433: #  at the system level sense.  It appears a gdbm file in the 
 4434: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
 4435: #  a set of entries made in that database.
 4436: #
 4437: # Parameters:
 4438: #   $cmd      - The command keyword that initiated this request.
 4439: #   $tail     - Tail of the command.  In this case consists of a colon
 4440: #               separated list contaning the domain to apply this to and
 4441: #               an ampersand separated list of keyword=value pairs.
 4442: #               Each value is a colon separated list that includes:  
 4443: #               description, institutional code and course owner.
 4444: #               For backward compatibility with versions included
 4445: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
 4446: #               code and/or course owner are preserved from the existing 
 4447: #               record when writing a new record in response to 1.1 or 
 4448: #               1.2 implementations of lonnet::flushcourselogs().   
 4449: #                      
 4450: #   $client   - Socket open on the client.
 4451: # Returns:
 4452: #   1    - indicating that processing should continue
 4453: #
 4454: # Side effects:
 4455: #   reply is written to the client.
 4456: #
 4457: sub put_course_id_handler {
 4458:     my ($cmd, $tail, $client) = @_;
 4459: 
 4460: 
 4461:     my $userinput = "$cmd:$tail";
 4462: 
 4463:     my ($udom, $what) = split(/:/, $tail,2);
 4464:     chomp($what);
 4465:     my $now=time;
 4466:     my @pairs=split(/\&/,$what);
 4467: 
 4468:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 4469:     if ($hashref) {
 4470: 	foreach my $pair (@pairs) {
 4471:             my ($key,$courseinfo) = split(/=/,$pair,2);
 4472:             $courseinfo =~ s/=/:/g;
 4473:             if (defined($hashref->{$key})) {
 4474:                 my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
 4475:                 if (ref($value) eq 'HASH') {
 4476:                     my @items = ('description','inst_code','owner','type');
 4477:                     my @new_items = split(/:/,$courseinfo,-1);
 4478:                     my %storehash; 
 4479:                     for (my $i=0; $i<@new_items; $i++) {
 4480:                         $storehash{$items[$i]} = &unescape($new_items[$i]);
 4481:                     }
 4482:                     $hashref->{$key} = 
 4483:                         &Apache::lonnet::freeze_escape(\%storehash);
 4484:                     my $unesc_key = &unescape($key);
 4485:                     $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
 4486:                     next;
 4487:                 }
 4488:             }
 4489:             my @current_items = split(/:/,$hashref->{$key},-1);
 4490:             shift(@current_items); # remove description
 4491:             pop(@current_items);   # remove last access
 4492:             my $numcurrent = scalar(@current_items);
 4493:             if ($numcurrent > 3) {
 4494:                 $numcurrent = 3;
 4495:             }
 4496:             my @new_items = split(/:/,$courseinfo,-1);
 4497:             my $numnew = scalar(@new_items);
 4498:             if ($numcurrent > 0) {
 4499:                 if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2 
 4500:                     for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
 4501:                         $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
 4502:                     }
 4503:                 }
 4504:             }
 4505:             $hashref->{$key}=$courseinfo.':'.$now;
 4506: 	}
 4507: 	if (&untie_domain_hash($hashref)) {
 4508: 	    &Reply( $client, "ok\n", $userinput);
 4509: 	} else {
 4510: 	    &Failure($client, "error: ".($!+0)
 4511: 		     ." untie(GDBM) Failed ".
 4512: 		     "while attempting courseidput\n", $userinput);
 4513: 	}
 4514:     } else {
 4515: 	&Failure($client, "error: ".($!+0)
 4516: 		 ." tie(GDBM) Failed ".
 4517: 		 "while attempting courseidput\n", $userinput);
 4518:     }
 4519: 
 4520:     return 1;
 4521: }
 4522: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
 4523: 
 4524: sub put_course_id_hash_handler {
 4525:     my ($cmd, $tail, $client) = @_;
 4526:     my $userinput = "$cmd:$tail";
 4527:     my ($udom,$mode,$what) = split(/:/, $tail,3);
 4528:     chomp($what);
 4529:     my $now=time;
 4530:     my @pairs=split(/\&/,$what);
 4531:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 4532:     if ($hashref) {
 4533:         foreach my $pair (@pairs) {
 4534:             my ($key,$value)=split(/=/,$pair);
 4535:             my $unesc_key = &unescape($key);
 4536:             if ($mode ne 'timeonly') {
 4537:                 if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
 4538:                     my $curritems = &Apache::lonnet::thaw_unescape($key); 
 4539:                     if (ref($curritems) ne 'HASH') {
 4540:                         my @current_items = split(/:/,$hashref->{$key},-1);
 4541:                         my $lasttime = pop(@current_items);
 4542:                         $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
 4543:                     } else {
 4544:                         $hashref->{&escape('lasttime:'.$unesc_key)} = '';
 4545:                     }
 4546:                 } 
 4547:                 $hashref->{$key} = $value;
 4548:             }
 4549:             if ($mode ne 'notime') {
 4550:                 $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
 4551:             }
 4552:         }
 4553:         if (&untie_domain_hash($hashref)) {
 4554:             &Reply($client, "ok\n", $userinput);
 4555:         } else {
 4556:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4557:                      "while attempting courseidputhash\n", $userinput);
 4558:         }
 4559:     } else {
 4560:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 4561:                   "while attempting courseidputhash\n", $userinput);
 4562:     }
 4563:     return 1;
 4564: }
 4565: &register_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
 4566: 
 4567: #  Retrieves the value of a course id resource keyword pattern
 4568: #  defined since a starting date.  Both the starting date and the
 4569: #  keyword pattern are optional.  If the starting date is not supplied it
 4570: #  is treated as the beginning of time.  If the pattern is not found,
 4571: #  it is treatred as "." matching everything.
 4572: #
 4573: #  Parameters:
 4574: #     $cmd     - Command keyword that resulted in us being dispatched.
 4575: #     $tail    - The remainder of the command that, in this case, consists
 4576: #                of a colon separated list of:
 4577: #                 domain   - The domain in which the course database is 
 4578: #                            defined.
 4579: #                 since    - Optional parameter describing the minimum
 4580: #                            time of definition(?) of the resources that
 4581: #                            will match the dump.
 4582: #                 description - regular expression that is used to filter
 4583: #                            the dump.  Only keywords matching this regexp
 4584: #                            will be used.
 4585: #                 institutional code - optional supplied code to filter 
 4586: #                            the dump. Only courses with an institutional code 
 4587: #                            that match the supplied code will be returned.
 4588: #                 owner    - optional supplied username and domain of owner to
 4589: #                            filter the dump.  Only courses for which the course
 4590: #                            owner matches the supplied username and/or domain
 4591: #                            will be returned. Pre-2.2.0 legacy entries from 
 4592: #                            nohist_courseiddump will only contain usernames.
 4593: #                 type     - optional parameter for selection 
 4594: #                 regexp_ok - if 1 or -1 allow the supplied institutional code
 4595: #                            filter to behave as a regular expression:
 4596: #	                      1 will not exclude the course if the instcode matches the RE 
 4597: #                            -1 will exclude the course if the instcode matches the RE
 4598: #                 rtn_as_hash - whether to return the information available for
 4599: #                            each matched item as a frozen hash of all 
 4600: #                            key, value pairs in the item's hash, or as a 
 4601: #                            colon-separated list of (in order) description,
 4602: #                            institutional code, and course owner.
 4603: #                 selfenrollonly - filter by courses allowing self-enrollment  
 4604: #                                  now or in the future (selfenrollonly = 1).
 4605: #                 catfilter - filter by course category, assigned to a course 
 4606: #                             using manually defined categories (i.e., not
 4607: #                             self-cataloging based on on institutional code).   
 4608: #                 showhidden - include course in results even if course  
 4609: #                              was set to be excluded from course catalog (DC only).
 4610: #                 caller -  if set to 'coursecatalog', courses set to be hidden
 4611: #                           from course catalog will be excluded from results (unless
 4612: #                           overridden by "showhidden".
 4613: #                 cloner - escaped username:domain of course cloner (if picking course to
 4614: #                          clone).
 4615: #                 cc_clone_list - escaped comma separated list of courses for which 
 4616: #                                 course cloner has active CC role (and so can clone
 4617: #                                 automatically).
 4618: #                 cloneonly - filter by courses for which cloner has rights to clone.
 4619: #                 createdbefore - include courses for which creation date preceeded this date.
 4620: #                 createdafter - include courses for which creation date followed this date.
 4621: #                 creationcontext - include courses created in specified context 
 4622: #
 4623: #                 domcloner - flag to indicate if user can create CCs in course's domain.
 4624: #                             If so, ability to clone course is automatic.
 4625: #                 hasuniquecode - filter by courses for which a six character unique code has 
 4626: #                                 been set.
 4627: #
 4628: #     $client  - The socket open on the client.
 4629: # Returns:
 4630: #    1     - Continue processing.
 4631: # Side Effects:
 4632: #   a reply is written to $client.
 4633: sub dump_course_id_handler {
 4634:     my ($cmd, $tail, $client) = @_;
 4635: 
 4636:     my $res = LONCAPA::Lond::dump_course_id_handler($tail);
 4637:     if ($res =~ /^error:/) {
 4638:         Failure($client, \$res, "$cmd:$tail");
 4639:     } else {
 4640:         Reply($client, \$res, "$cmd:$tail");
 4641:     }
 4642: 
 4643:     return 1;  
 4644: 
 4645:     #TODO remove
 4646:     my $userinput = "$cmd:$tail";
 4647: 
 4648:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
 4649:         $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
 4650:         $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
 4651:         $creationcontext,$domcloner,$hasuniquecode) =split(/:/,$tail);
 4652:     my $now = time;
 4653:     my ($cloneruname,$clonerudom,%cc_clone);
 4654:     if (defined($description)) {
 4655: 	$description=&unescape($description);
 4656:     } else {
 4657: 	$description='.';
 4658:     }
 4659:     if (defined($instcodefilter)) {
 4660:         $instcodefilter=&unescape($instcodefilter);
 4661:     } else {
 4662:         $instcodefilter='.';
 4663:     }
 4664:     my ($ownerunamefilter,$ownerdomfilter);
 4665:     if (defined($ownerfilter)) {
 4666:         $ownerfilter=&unescape($ownerfilter);
 4667:         if ($ownerfilter ne '.' && defined($ownerfilter)) {
 4668:             if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
 4669:                  $ownerunamefilter = $1;
 4670:                  $ownerdomfilter = $2;
 4671:             } else {
 4672:                 $ownerunamefilter = $ownerfilter;
 4673:                 $ownerdomfilter = '';
 4674:             }
 4675:         }
 4676:     } else {
 4677:         $ownerfilter='.';
 4678:     }
 4679: 
 4680:     if (defined($coursefilter)) {
 4681:         $coursefilter=&unescape($coursefilter);
 4682:     } else {
 4683:         $coursefilter='.';
 4684:     }
 4685:     if (defined($typefilter)) {
 4686:         $typefilter=&unescape($typefilter);
 4687:     } else {
 4688:         $typefilter='.';
 4689:     }
 4690:     if (defined($regexp_ok)) {
 4691:         $regexp_ok=&unescape($regexp_ok);
 4692:     }
 4693:     if (defined($catfilter)) {
 4694:         $catfilter=&unescape($catfilter);
 4695:     }
 4696:     if (defined($cloner)) {
 4697:         $cloner = &unescape($cloner);
 4698:         ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/); 
 4699:     }
 4700:     if (defined($cc_clone_list)) {
 4701:         $cc_clone_list = &unescape($cc_clone_list);
 4702:         my @cc_cloners = split('&',$cc_clone_list);
 4703:         foreach my $cid (@cc_cloners) {
 4704:             my ($clonedom,$clonenum) = split(':',$cid);
 4705:             next if ($clonedom ne $udom); 
 4706:             $cc_clone{$clonedom.'_'.$clonenum} = 1;
 4707:         } 
 4708:     }
 4709:     if ($createdbefore ne '') {
 4710:         $createdbefore = &unescape($createdbefore);
 4711:     } else {
 4712:        $createdbefore = 0;
 4713:     }
 4714:     if ($createdafter ne '') {
 4715:         $createdafter = &unescape($createdafter);
 4716:     } else {
 4717:         $createdafter = 0;
 4718:     }
 4719:     if ($creationcontext ne '') {
 4720:         $creationcontext = &unescape($creationcontext);
 4721:     } else {
 4722:         $creationcontext = '.';
 4723:     }
 4724:     unless ($hasuniquecode) {
 4725:         $hasuniquecode = '.';
 4726:     }
 4727:     my $unpack = 1;
 4728:     if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' && 
 4729:         $typefilter eq '.') {
 4730:         $unpack = 0;
 4731:     }
 4732:     if (!defined($since)) { $since=0; }
 4733:     my $qresult='';
 4734:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 4735:     if ($hashref) {
 4736: 	while (my ($key,$value) = each(%$hashref)) {
 4737:             my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
 4738:                 %unesc_val,$selfenroll_end,$selfenroll_types,$created,
 4739:                 $context);
 4740:             $unesc_key = &unescape($key);
 4741:             if ($unesc_key =~ /^lasttime:/) {
 4742:                 next;
 4743:             } else {
 4744:                 $lasttime_key = &escape('lasttime:'.$unesc_key);
 4745:             }
 4746:             if ($hashref->{$lasttime_key} ne '') {
 4747:                 $lasttime = $hashref->{$lasttime_key};
 4748:                 next if ($lasttime<$since);
 4749:             }
 4750:             my ($canclone,$valchange);
 4751:             my $items = &Apache::lonnet::thaw_unescape($value);
 4752:             if (ref($items) eq 'HASH') {
 4753:                 if ($hashref->{$lasttime_key} eq '') {
 4754:                     next if ($since > 1);
 4755:                 }
 4756:                 $is_hash =  1;
 4757:                 if ($domcloner) {
 4758:                     $canclone = 1;
 4759:                 } elsif (defined($clonerudom)) {
 4760:                     if ($items->{'cloners'}) {
 4761:                         my @cloneable = split(',',$items->{'cloners'});
 4762:                         if (@cloneable) {
 4763:                             if (grep(/^\*$/,@cloneable))  {
 4764:                                 $canclone = 1;
 4765:                             } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
 4766:                                 $canclone = 1;
 4767:                             } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
 4768:                                 $canclone = 1;
 4769:                             }
 4770:                         }
 4771:                         unless ($canclone) {
 4772:                             if ($cloneruname ne '' && $clonerudom ne '') {
 4773:                                 if ($cc_clone{$unesc_key}) {
 4774:                                     $canclone = 1;
 4775:                                     $items->{'cloners'} .= ','.$cloneruname.':'.
 4776:                                                            $clonerudom;
 4777:                                     $valchange = 1;
 4778:                                 }
 4779:                             }
 4780:                         }
 4781:                     } elsif (defined($cloneruname)) {
 4782:                         if ($cc_clone{$unesc_key}) {
 4783:                             $canclone = 1;
 4784:                             $items->{'cloners'} = $cloneruname.':'.$clonerudom;
 4785:                             $valchange = 1;
 4786:                         }
 4787:                         unless ($canclone) {
 4788:                             if ($items->{'owner'} =~ /:/) {
 4789:                                 if ($items->{'owner'} eq $cloner) {
 4790:                                     $canclone = 1;
 4791:                                 }
 4792:                             } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
 4793:                                 $canclone = 1;
 4794:                             }
 4795:                             if ($canclone) {
 4796:                                 $items->{'cloners'} = $cloneruname.':'.$clonerudom;
 4797:                                 $valchange = 1;
 4798:                             }
 4799:                         }
 4800:                     }
 4801:                 }
 4802:                 if ($unpack || !$rtn_as_hash) {
 4803:                     $unesc_val{'descr'} = $items->{'description'};
 4804:                     $unesc_val{'inst_code'} = $items->{'inst_code'};
 4805:                     $unesc_val{'owner'} = $items->{'owner'};
 4806:                     $unesc_val{'type'} = $items->{'type'};
 4807:                     $unesc_val{'cloners'} = $items->{'cloners'};
 4808:                     $unesc_val{'created'} = $items->{'created'};
 4809:                     $unesc_val{'context'} = $items->{'context'};
 4810:                 }
 4811:                 $selfenroll_types = $items->{'selfenroll_types'};
 4812:                 $selfenroll_end = $items->{'selfenroll_end_date'};
 4813:                 $created = $items->{'created'};
 4814:                 $context = $items->{'context'};
 4815:                 if ($hasuniquecode ne '.') {
 4816:                     next unless ($items->{'uniquecode'});
 4817:                 }
 4818:                 if ($selfenrollonly) {
 4819:                     next if (!$selfenroll_types);
 4820:                     if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
 4821:                         next;
 4822:                     }
 4823:                 }
 4824:                 if ($creationcontext ne '.') {
 4825:                     next if (($context ne '') && ($context ne $creationcontext));  
 4826:                 }
 4827:                 if ($createdbefore > 0) {
 4828:                     next if (($created eq '') || ($created > $createdbefore));   
 4829:                 }
 4830:                 if ($createdafter > 0) {
 4831:                     next if (($created eq '') || ($created <= $createdafter)); 
 4832:                 }
 4833:                 if ($catfilter ne '') {
 4834:                     next if ($items->{'categories'} eq '');
 4835:                     my @categories = split('&',$items->{'categories'}); 
 4836:                     next if (@categories == 0);
 4837:                     my @subcats = split('&',$catfilter);
 4838:                     my $matchcat = 0;
 4839:                     foreach my $cat (@categories) {
 4840:                         if (grep(/^\Q$cat\E$/,@subcats)) {
 4841:                             $matchcat = 1;
 4842:                             last;
 4843:                         }
 4844:                     }
 4845:                     next if (!$matchcat);
 4846:                 }
 4847:                 if ($caller eq 'coursecatalog') {
 4848:                     if ($items->{'hidefromcat'} eq 'yes') {
 4849:                         next if !$showhidden;
 4850:                     }
 4851:                 }
 4852:             } else {
 4853:                 next if ($catfilter ne '');
 4854:                 next if ($selfenrollonly);
 4855:                 next if ($createdbefore || $createdafter);
 4856:                 next if ($creationcontext ne '.');
 4857:                 if ((defined($clonerudom)) && (defined($cloneruname)))  {
 4858:                     if ($cc_clone{$unesc_key}) {
 4859:                         $canclone = 1;
 4860:                         $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
 4861:                     }
 4862:                 }
 4863:                 $is_hash =  0;
 4864:                 my @courseitems = split(/:/,$value);
 4865:                 $lasttime = pop(@courseitems);
 4866:                 if ($hashref->{$lasttime_key} eq '') {
 4867:                     next if ($lasttime<$since);
 4868:                 }
 4869: 	        ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
 4870:             }
 4871:             if ($cloneonly) {
 4872:                next unless ($canclone);
 4873:             }
 4874:             my $match = 1;
 4875: 	    if ($description ne '.') {
 4876:                 if (!$is_hash) {
 4877:                     $unesc_val{'descr'} = &unescape($val{'descr'});
 4878:                 }
 4879:                 if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
 4880:                     $match = 0;
 4881:                 }
 4882:             }
 4883:             if ($instcodefilter ne '.') {
 4884:                 if (!$is_hash) {
 4885:                     $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
 4886:                 }
 4887:                 if ($regexp_ok == 1) {
 4888:                     if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
 4889:                         $match = 0;
 4890:                     }
 4891:                 } elsif ($regexp_ok == -1) {
 4892:                     if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
 4893:                         $match = 0;
 4894:                     }
 4895:                 } else {
 4896:                     if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
 4897:                         $match = 0;
 4898:                     }
 4899:                 }
 4900: 	    }
 4901:             if ($ownerfilter ne '.') {
 4902:                 if (!$is_hash) {
 4903:                     $unesc_val{'owner'} = &unescape($val{'owner'});
 4904:                 }
 4905:                 if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
 4906:                     if ($unesc_val{'owner'} =~ /:/) {
 4907:                         if (eval{$unesc_val{'owner'} !~ 
 4908:                              /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
 4909:                             $match = 0;
 4910:                         } 
 4911:                     } else {
 4912:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
 4913:                             $match = 0;
 4914:                         }
 4915:                     }
 4916:                 } elsif ($ownerunamefilter ne '') {
 4917:                     if ($unesc_val{'owner'} =~ /:/) {
 4918:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
 4919:                              $match = 0;
 4920:                         }
 4921:                     } else {
 4922:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
 4923:                             $match = 0;
 4924:                         }
 4925:                     }
 4926:                 } elsif ($ownerdomfilter ne '') {
 4927:                     if ($unesc_val{'owner'} =~ /:/) {
 4928:                         if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
 4929:                              $match = 0;
 4930:                         }
 4931:                     } else {
 4932:                         if ($ownerdomfilter ne $udom) {
 4933:                             $match = 0;
 4934:                         }
 4935:                     }
 4936:                 }
 4937:             }
 4938:             if ($coursefilter ne '.') {
 4939:                 if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
 4940:                     $match = 0;
 4941:                 }
 4942:             }
 4943:             if ($typefilter ne '.') {
 4944:                 if (!$is_hash) {
 4945:                     $unesc_val{'type'} = &unescape($val{'type'});
 4946:                 }
 4947:                 if ($unesc_val{'type'} eq '') {
 4948:                     if ($typefilter ne 'Course') {
 4949:                         $match = 0;
 4950:                     }
 4951:                 } else {
 4952:                     if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
 4953:                         $match = 0;
 4954:                     }
 4955:                 }
 4956:             }
 4957:             if ($match == 1) {
 4958:                 if ($rtn_as_hash) {
 4959:                     if ($is_hash) {
 4960:                         if ($valchange) {
 4961:                             my $newvalue = &Apache::lonnet::freeze_escape($items);
 4962:                             $qresult.=$key.'='.$newvalue.'&';
 4963:                         } else {
 4964:                             $qresult.=$key.'='.$value.'&';
 4965:                         }
 4966:                     } else {
 4967:                         my %rtnhash = ( 'description' => &unescape($val{'descr'}),
 4968:                                         'inst_code' => &unescape($val{'inst_code'}),
 4969:                                         'owner'     => &unescape($val{'owner'}),
 4970:                                         'type'      => &unescape($val{'type'}),
 4971:                                         'cloners'   => &unescape($val{'cloners'}),
 4972:                                       );
 4973:                         my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
 4974:                         $qresult.=$key.'='.$items.'&';
 4975:                     }
 4976:                 } else {
 4977:                     if ($is_hash) {
 4978:                         $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
 4979:                                     &escape($unesc_val{'inst_code'}).':'.
 4980:                                     &escape($unesc_val{'owner'}).'&';
 4981:                     } else {
 4982:                         $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
 4983:                                     ':'.$val{'owner'}.'&';
 4984:                     }
 4985:                 }
 4986:             }
 4987: 	}
 4988: 	if (&untie_domain_hash($hashref)) {
 4989: 	    chop($qresult);
 4990: 	    &Reply($client, \$qresult, $userinput);
 4991: 	} else {
 4992: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 4993: 		    "while attempting courseiddump\n", $userinput);
 4994: 	}
 4995:     } else {
 4996: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 4997: 		"while attempting courseiddump\n", $userinput);
 4998:     }
 4999:     return 1;
 5000: }
 5001: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
 5002: 
 5003: sub course_lastaccess_handler {
 5004:     my ($cmd, $tail, $client) = @_;
 5005:     my $userinput = "$cmd:$tail";
 5006:     my ($cdom,$cnum) = split(':',$tail); 
 5007:     my (%lastaccess,$qresult);
 5008:     my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
 5009:     if ($hashref) {
 5010:         while (my ($key,$value) = each(%$hashref)) {
 5011:             my ($unesc_key,$lasttime);
 5012:             $unesc_key = &unescape($key);
 5013:             if ($cnum) {
 5014:                 next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
 5015:             }
 5016:             if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
 5017:                 $lastaccess{$1} = $value;
 5018:             } else {
 5019:                 my $items = &Apache::lonnet::thaw_unescape($value);
 5020:                 if (ref($items) eq 'HASH') {
 5021:                     unless ($lastaccess{$unesc_key}) {
 5022:                         $lastaccess{$unesc_key} = '';
 5023:                     }
 5024:                 } else {
 5025:                     my @courseitems = split(':',$value);
 5026:                     $lastaccess{$unesc_key} = pop(@courseitems);
 5027:                 }
 5028:             }
 5029:         }
 5030:         foreach my $cid (sort(keys(%lastaccess))) {
 5031:             $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&'; 
 5032:         }
 5033:         if (&untie_domain_hash($hashref)) {
 5034:             if ($qresult) {
 5035:                 chop($qresult);
 5036:             }
 5037:             &Reply($client, \$qresult, $userinput);
 5038:         } else {
 5039:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5040:                     "while attempting lastacourseaccess\n", $userinput);
 5041:         }
 5042:     } else {
 5043:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 5044:                 "while attempting lastcourseaccess\n", $userinput);
 5045:     }
 5046:     return 1;
 5047: }
 5048: &register_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
 5049: 
 5050: sub course_sessions_handler {
 5051:     my ($cmd, $tail, $client) = @_;
 5052:     my $userinput = "$cmd:$tail";
 5053:     my ($cdom,$cnum,$lastactivity) = split(':',$tail);
 5054:     my $dbsuffix = '_'.$cdom.'_'.$cnum.'.db';
 5055:     my (%sessions,$qresult);
 5056:     my $now=time;
 5057:     if (opendir(DIR,$perlvar{'lonIDsDir'})) {
 5058:         my $filename;
 5059:         while ($filename=readdir(DIR)) {
 5060:             next if ($filename=~/^\./);
 5061:             next if ($filename=~/^publicuser_/);
 5062:             next if ($filename=~/^[a-f0-9]+_(linked|lti_\d+)\.id$/);
 5063:             if ($filename =~ /^($LONCAPA::match_username)_\d+_($LONCAPA::match_domain)_/) {
 5064:                 my ($uname,$udom) = ($1,$2);
 5065:                 next unless (-e "$perlvar{'lonDaemons'}/tmp/$uname$dbsuffix");
 5066:                 my $mtime = (stat("$perlvar{'lonIDsDir'}/$filename"))[9];
 5067:                 if ($lastactivity < 0) {
 5068:                     next if ($mtime-$now > $lastactivity);
 5069:                 } else {
 5070:                     next if ($now-$mtime > $lastactivity);
 5071:                 }
 5072:                 $sessions{$uname.':'.$udom} = $mtime;
 5073:             }
 5074:         }
 5075:         closedir(DIR); 
 5076:     }
 5077:     foreach my $user (keys(%sessions)) {
 5078:         $qresult.=&escape($user).'='.$sessions{$user}.'&';
 5079:     }
 5080:     if ($qresult) {
 5081:         chop($qresult);
 5082:     }
 5083:     &Reply($client, \$qresult, $userinput);
 5084:     return 1;
 5085: }
 5086: &register_handler("coursesessions",\&course_sessions_handler, 0, 1, 0);
 5087: 
 5088: #
 5089: # Puts an unencrypted entry in a namespace db file at the domain level 
 5090: #
 5091: # Parameters:
 5092: #    $cmd      - The command that got us here.
 5093: #    $tail     - Tail of the command (remaining parameters).
 5094: #    $client   - File descriptor connected to client.
 5095: # Returns
 5096: #     0        - Requested to exit, caller should shut down.
 5097: #     1        - Continue processing.
 5098: #  Side effects:
 5099: #     reply is written to $client.
 5100: #
 5101: sub put_domain_handler {
 5102:     my ($cmd,$tail,$client) = @_;
 5103: 
 5104:     my $userinput = "$cmd:$tail";
 5105: 
 5106:     my ($udom,$namespace,$what) =split(/:/,$tail,3);
 5107:     chomp($what);
 5108:     my @pairs=split(/\&/,$what);
 5109:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
 5110:                                    "P", $what);
 5111:     if ($hashref) {
 5112:         foreach my $pair (@pairs) {
 5113:             my ($key,$value)=split(/=/,$pair);
 5114:             $hashref->{$key}=$value;
 5115:         }
 5116:         if (&untie_domain_hash($hashref)) {
 5117:             &Reply($client, "ok\n", $userinput);
 5118:         } else {
 5119:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5120:                      "while attempting putdom\n", $userinput);
 5121:         }
 5122:     } else {
 5123:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 5124:                   "while attempting putdom\n", $userinput);
 5125:     }
 5126: 
 5127:     return 1;
 5128: }
 5129: &register_handler("putdom", \&put_domain_handler, 0, 1, 0);
 5130: 
 5131: # Updates one or more entries in clickers.db file at the domain level
 5132: #
 5133: # Parameters:
 5134: #    $cmd      - The command that got us here.
 5135: #    $tail     - Tail of the command (remaining parameters).
 5136: #                In this case a colon separated list containing:
 5137: #                (a) the domain for which we are updating the entries,
 5138: #                (b) the action required -- add or del -- and
 5139: #                (c) a &-separated list of entries to add or delete.
 5140: #    $client   - File descriptor connected to client.
 5141: # Returns
 5142: #     1        - Continue processing.
 5143: #     0        - Requested to exit, caller should shut down.
 5144: #  Side effects:
 5145: #     reply is written to $client.
 5146: #
 5147: 
 5148: 
 5149: sub update_clickers {
 5150:     my ($cmd, $tail, $client)  = @_;
 5151: 
 5152:     my $userinput = "$cmd:$tail";
 5153:     my ($udom,$action,$what) =split(/:/,$tail,3);
 5154:     chomp($what);
 5155: 
 5156:     my $hashref = &tie_domain_hash($udom, "clickers", &GDBM_WRCREAT(),
 5157:                                  "U","$action:$what");
 5158: 
 5159:     if (!$hashref) {
 5160:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 5161:                   "while attempting updateclickers\n", $userinput);
 5162:         return 1;
 5163:     }
 5164: 
 5165:     my @pairs=split(/\&/,$what);
 5166:     foreach my $pair (@pairs) {
 5167:         my ($key,$value)=split(/=/,$pair);
 5168:         if ($action eq 'add') {
 5169:             if (exists($hashref->{$key})) {
 5170:                 my @newvals = split(/,/,&unescape($value));
 5171:                 my @currvals = split(/,/,&unescape($hashref->{$key}));
 5172:                 my @merged = sort(keys(%{{map { $_ => 1 } (@newvals,@currvals)}}));
 5173:                 $hashref->{$key}=&escape(join(',',@merged));
 5174:             } else {
 5175:                 $hashref->{$key}=$value;
 5176:             }
 5177:         } elsif ($action eq 'del') {
 5178:             if (exists($hashref->{$key})) {
 5179:                 my %current;
 5180:                 map { $current{$_} = 1; } split(/,/,&unescape($hashref->{$key}));
 5181:                 map { delete($current{$_}); } split(/,/,&unescape($value));
 5182:                 if (keys(%current)) {
 5183:                     $hashref->{$key}=&escape(join(',',sort(keys(%current))));
 5184:                 } else {
 5185:                     delete($hashref->{$key});
 5186:                 }
 5187:             }
 5188:         }
 5189:     }
 5190:     if (&untie_user_hash($hashref)) {
 5191:         &Reply( $client, "ok\n", $userinput);
 5192:     } else {
 5193:         &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 5194:                  "while attempting put\n",
 5195:                  $userinput);
 5196:     }
 5197:     return 1;
 5198: }
 5199: &register_handler("updateclickers", \&update_clickers, 0, 1, 0);
 5200: 
 5201: 
 5202: # Deletes one or more entries in a namespace db file at the domain level
 5203: #
 5204: # Parameters:
 5205: #    $cmd      - The command that got us here.
 5206: #    $tail     - Tail of the command (remaining parameters).
 5207: #                In this case a colon separated list containing:
 5208: #                (a) the domain for which we are deleting the entries,
 5209: #                (b) &-separated list of keys to delete.  
 5210: #    $client   - File descriptor connected to client.
 5211: # Returns
 5212: #     1        - Continue processing.
 5213: #     0        - Requested to exit, caller should shut down.
 5214: #  Side effects:
 5215: #     reply is written to $client.
 5216: #
 5217: 
 5218: sub del_domain_handler {
 5219:     my ($cmd,$tail,$client) = @_;
 5220: 
 5221:     my $userinput = "$cmd:$tail";
 5222: 
 5223:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
 5224:     chomp($what);
 5225:     my $hashref = &tie_domain_hash($udom,$namespace,&GDBM_WRCREAT(),
 5226:                                    "D", $what);
 5227:     if ($hashref) {
 5228:         my @keys=split(/\&/,$what);
 5229:         foreach my $key (@keys) {
 5230:             delete($hashref->{$key});
 5231:         }
 5232:         if (&untie_user_hash($hashref)) {
 5233:             &Reply($client, "ok\n", $userinput);
 5234:         } else {
 5235:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5236:                     "while attempting deldom\n", $userinput);
 5237:         }
 5238:     } else {
 5239:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 5240:                  "while attempting deldom\n", $userinput);
 5241:     }
 5242:     return 1;
 5243: }
 5244: &register_handler("deldom", \&del_domain_handler, 0, 1, 0);
 5245: 
 5246: 
 5247: # Unencrypted get from the namespace database file at the domain level.
 5248: # This function retrieves a keyed item from a specific named database in the
 5249: # domain directory.
 5250: #
 5251: # Parameters:
 5252: #   $cmd             - Command request keyword (getdom).
 5253: #   $tail            - Tail of the command.  This is a colon separated list
 5254: #                      consisting of the domain and the 'namespace' 
 5255: #                      which selects the gdbm file to do the lookup in,
 5256: #                      & separated list of keys to lookup.  Note that
 5257: #                      the values are returned as an & separated list too.
 5258: #   $client          - File descriptor open on the client.
 5259: # Returns:
 5260: #   1       - Continue processing.
 5261: #   0       - Exit.
 5262: #  Side effects:
 5263: #     reply is written to $client.
 5264: #
 5265: 
 5266: sub get_domain_handler {
 5267:     my ($cmd, $tail, $client) = @_;
 5268: 
 5269:     my $userinput = "$cmd:$tail";
 5270: 
 5271:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
 5272:     if (($namespace =~ /^enc/) || ($namespace eq 'private')) {
 5273:         &Failure( $client, "refused\n", $userinput);
 5274:     } else {
 5275:         my $res = LONCAPA::Lond::get_dom($userinput);
 5276:         if ($res =~ /^error:/) {
 5277:             &Failure($client, \$res, $userinput);
 5278:         } else {
 5279:             &Reply($client, \$res, $userinput);
 5280:         }
 5281:     }
 5282: 
 5283:     return 1;
 5284: }
 5285: &register_handler("getdom", \&get_domain_handler, 0, 1, 0);
 5286: 
 5287: #
 5288: # Encrypted get from the namespace database file at the domain level.
 5289: # This function retrieves a keyed item from a specific named database in the
 5290: # domain directory.
 5291: #
 5292: # Parameters:
 5293: #   $cmd             - Command request keyword (egetdom).
 5294: #   $tail            - Tail of the command.  This is a colon separated list
 5295: #                      consisting of the domain and the 'namespace'
 5296: #                      which selects the gdbm file to do the lookup in,
 5297: #                      & separated list of keys to lookup.  Note that
 5298: #                      the values are returned as an & separated list too.
 5299: #   $client          - File descriptor open on the client.
 5300: # Returns:
 5301: #   1       - Continue processing.
 5302: #   0       - Exit.
 5303: #  Side effects:
 5304: #     reply is encrypted before being written to $client.
 5305: #
 5306: sub encrypted_get_domain_handler {
 5307:     my ($cmd, $tail, $client) = @_;
 5308: 
 5309:     my $userinput = "$cmd:$tail";
 5310: 
 5311:     my ($udom,$namespace,$what) = split(/:/,$tail,3);
 5312:     if ($namespace eq 'private') {
 5313:         &Failure( $client, "refused\n", $userinput);
 5314:     } else {
 5315:         my $res = LONCAPA::Lond::get_dom($userinput);
 5316:         if ($res =~ /^error:/) {
 5317:             &Failure($client, \$res, $userinput);
 5318:         } else {
 5319:             if ($cipher) {
 5320:                 my $cmdlength=length($res);
 5321:                 $res.="         ";
 5322:                 my $encres='';
 5323:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 5324:                     $encres.= unpack("H16",
 5325:                                      $cipher->encrypt(substr($res,
 5326:                                                              $encidx,
 5327:                                                              8)));
 5328:                 }
 5329:                 &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
 5330:             } else {
 5331:                 &Failure( $client, "error:no_key\n",$userinput);
 5332:             }
 5333:         }
 5334:     }
 5335:     return 1;
 5336: }
 5337: &register_handler("egetdom", \&encrypted_get_domain_handler, 1, 1, 0);
 5338: 
 5339: #
 5340: # Encrypted get from the namespace database file at the domain level.
 5341: # This function retrieves a keyed item from a specific named database in the
 5342: # domain directory.
 5343: #
 5344: # Parameters:
 5345: #   $cmd             - Command request keyword (lti).
 5346: #   $tail            - Tail of the command.  This is a colon-separated list
 5347: #                      consisting of the domain, coursenum, if for LTI-
 5348: #                      enabled deep-linking to course content using
 5349: #                      link protection configured within a course,
 5350: #                      context (=deeplink) if for LTI-enabled deep-linking
 5351: #                      to course content using LTI Provider settings
 5352: #                      configured within a course's domain, the (escaped)
 5353: #                      launch URL, the (escaped) method (typically POST),
 5354: #                      and a frozen hash of the LTI launch parameters
 5355: #                      from the LTI payload.
 5356: #   $client          - File descriptor open on the client.
 5357: # Returns:
 5358: #   1       - Continue processing.
 5359: #   0       - Exit.
 5360: #  Side effects:
 5361: #     The reply will contain an LTI itemID, if the signed LTI payload
 5362: #     could be verified using the consumer key and the shared secret
 5363: #     available for that key (for the itemID) for either the course or domain,
 5364: #     depending on values for cnum and context. The reply is encrypted before
 5365: #     being written to $client.
 5366: #
 5367: sub lti_handler {
 5368:     my ($cmd, $tail, $client) = @_;
 5369: 
 5370:     my $userinput = "$cmd:$tail";
 5371: 
 5372:     my ($cdom,$cnum,$context,$escurl,$escmethod,$items) = split(/:/,$tail);
 5373:     my $url = &unescape($escurl);
 5374:     my $method = &unescape($escmethod);
 5375:     my $params = &Apache::lonnet::thaw_unescape($items);
 5376:     my $res;
 5377:     if ($cnum ne '') {
 5378:         $res = &LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
 5379:     } else {
 5380:         $res = &LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
 5381:     }
 5382:     if ($res =~ /^error:/) {
 5383:         &Failure($client, \$res, $userinput);
 5384:     } else {
 5385:         if ($cipher) {
 5386:             my $cmdlength=length($res);
 5387:             $res.="         ";
 5388:             my $encres='';
 5389:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 5390:                 $encres.= unpack("H16",
 5391:                                  $cipher->encrypt(substr($res,
 5392:                                                          $encidx,
 5393:                                                          8)));
 5394:             }
 5395:             &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
 5396:         } else {
 5397:             &Failure( $client, "error:no_key\n",$userinput);
 5398:         }
 5399:     }
 5400:     return 1;
 5401: }
 5402: &register_handler("lti", \&lti_handler, 1, 1, 0);
 5403: 
 5404: #
 5405: # Data for LTI payload (received encrypted) are unencrypted and
 5406: # then signed with the appropriate key and secret, before re-encrypting
 5407: # the signed payload which is sent to the client for unencryption by
 5408: # the caller: lonnet::sign_lti()) before dispatch either to a web browser
 5409: # (launch) or to a remote web service (roster, logout, or grade).  
 5410: #
 5411: # Parameters:
 5412: #   $cmd             - Command request keyword (signlti).
 5413: #   $tail            - Tail of the command.  This is a colon-separated list
 5414: #                      consisting of the domain, coursenum (if for an External
 5415: #                      Tool defined in a course), crsdef (true if defined in
 5416: #                      a course), type (linkprot or lti)
 5417: #                      context (launch, roster, logout, or grade),
 5418: #                      escaped launch URL, numeric ID of external tool,
 5419: #                      version number for encryption key (if tool's LTI secret was
 5420: #                      encrypted before storing), a frozen hash of LTI launch 
 5421: #                      parameters, and a frozen hash of LTI information,
 5422: #                      (e.g., method => 'HMAC-SHA1',
 5423: #                             respfmt => 'to_authorization_header').
 5424: #   $client          - File descriptor open on the client.
 5425: # Returns:
 5426: #   1       - Continue processing.
 5427: #   0       - Exit.
 5428: #  Side effects:
 5429: #     The reply will contain the LTI payload, as & separated key=value pairs,
 5430: #     where value is itself a frozen hash, if the required key and secret
 5431: #     for the specific tool ID are available. The payload data are retrieved from
 5432: #     a call to Lond::sign_lti_payload(), and the reply is encrypted before being
 5433: #     written to $client.
 5434: #
 5435: sub sign_lti_handler {
 5436:     my ($cmd, $tail, $client) = @_;
 5437: 
 5438:     my $userinput = "$cmd:$tail";
 5439: 
 5440:     my ($cdom,$cnum,$crsdef,$type,$context,$escurl,
 5441:         $ltinum,$keynum,$paramsref,$inforef) = split(/:/,$tail);
 5442:     my $url = &unescape($escurl);
 5443:     my $params = &Apache::lonnet::thaw_unescape($paramsref);
 5444:     my $info = &Apache::lonnet::thaw_unescape($inforef);
 5445:     my $res =
 5446:         &LONCAPA::Lond::sign_lti_payload($cdom,$cnum,$crsdef,$type,$context,$url,$ltinum,
 5447:                                          $keynum,$perlvar{'lonVersion'},$params,$info);
 5448:     my $result;
 5449:     if (ref($res) eq 'HASH') {
 5450:         foreach my $key (keys(%{$res})) {
 5451:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($res->{$key}).'&';
 5452:         }
 5453:         $result =~ s/\&$//;
 5454:     } else {
 5455:         $result = $res;
 5456:     }
 5457:     if ($result =~ /^error:/) {
 5458:         &Failure($client, \$result, $userinput);
 5459:     } else {
 5460:         if ($cipher) {
 5461:             my $cmdlength=length($result);
 5462:             $result.="         ";
 5463:             my $encres='';
 5464:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 5465:                 $encres.= unpack("H16",
 5466:                                  $cipher->encrypt(substr($result,
 5467:                                                          $encidx,
 5468:                                                          8)));
 5469:             }
 5470:             &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
 5471:         } else {
 5472:             &Failure( $client, "error:no_key\n",$userinput);
 5473:         }
 5474:     }
 5475:     return 1;
 5476: }
 5477: &register_handler("signlti", \&sign_lti_handler, 1, 1, 0);
 5478: 
 5479: #
 5480: #  Puts an id to a domains id database. 
 5481: #
 5482: #  Parameters:
 5483: #   $cmd     - The command that triggered us.
 5484: #   $tail    - Remainder of the request other than the command. This is a 
 5485: #              colon separated list containing:
 5486: #              $domain  - The domain for which we are writing the id.
 5487: #              $pairs  - The id info to write... this is and & separated list
 5488: #                        of keyword=value.
 5489: #   $client  - Socket open on the client.
 5490: #  Returns:
 5491: #    1   - Continue processing.
 5492: #  Side effects:
 5493: #     reply is written to $client.
 5494: #
 5495: sub put_id_handler {
 5496:     my ($cmd,$tail,$client) = @_;
 5497: 
 5498: 
 5499:     my $userinput = "$cmd:$tail";
 5500: 
 5501:     my ($udom,$what)=split(/:/,$tail);
 5502:     chomp($what);
 5503:     my @pairs=split(/\&/,$what);
 5504:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
 5505: 				   "P", $what);
 5506:     if ($hashref) {
 5507: 	foreach my $pair (@pairs) {
 5508: 	    my ($key,$value)=split(/=/,$pair);
 5509: 	    $hashref->{$key}=$value;
 5510: 	}
 5511: 	if (&untie_domain_hash($hashref)) {
 5512: 	    &Reply($client, "ok\n", $userinput);
 5513: 	} else {
 5514: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5515: 		     "while attempting idput\n", $userinput);
 5516: 	}
 5517:     } else {
 5518: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 5519: 		  "while attempting idput\n", $userinput);
 5520:     }
 5521: 
 5522:     return 1;
 5523: }
 5524: &register_handler("idput", \&put_id_handler, 0, 1, 0);
 5525: 
 5526: #
 5527: #  Retrieves a set of id values from the id database.
 5528: #  Returns an & separated list of results, one for each requested id to the
 5529: #  client.
 5530: #
 5531: # Parameters:
 5532: #   $cmd       - Command keyword that caused us to be dispatched.
 5533: #   $tail      - Tail of the command.  Consists of a colon separated:
 5534: #               domain - the domain whose id table we dump
 5535: #               ids      Consists of an & separated list of
 5536: #                        id keywords whose values will be fetched.
 5537: #                        nonexisting keywords will have an empty value.
 5538: #   $client    - Socket open on the client.
 5539: #
 5540: # Returns:
 5541: #    1 - indicating processing should continue.
 5542: # Side effects:
 5543: #   An & separated list of results is written to $client.
 5544: #
 5545: sub get_id_handler {
 5546:     my ($cmd, $tail, $client) = @_;
 5547: 
 5548:     
 5549:     my $userinput = "$client:$tail";
 5550:     
 5551:     my ($udom,$what)=split(/:/,$tail);
 5552:     chomp($what);
 5553:     my @queries=split(/\&/,$what);
 5554:     my $qresult='';
 5555:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
 5556:     if ($hashref) {
 5557: 	for (my $i=0;$i<=$#queries;$i++) {
 5558: 	    $qresult.="$hashref->{$queries[$i]}&";
 5559: 	}
 5560: 	if (&untie_domain_hash($hashref)) {
 5561: 	    $qresult=~s/\&$//;
 5562: 	    &Reply($client, \$qresult, $userinput);
 5563: 	} else {
 5564: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 5565: 		      "while attempting idget\n",$userinput);
 5566: 	}
 5567:     } else {
 5568: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 5569: 		 "while attempting idget\n",$userinput);
 5570:     }
 5571:     
 5572:     return 1;
 5573: }
 5574: &register_handler("idget", \&get_id_handler, 0, 1, 0);
 5575: 
 5576: #   Deletes one or more ids in a domain's id database.
 5577: #
 5578: #   Parameters:
 5579: #       $cmd                  - Command keyword (iddel).
 5580: #       $tail                 - Command tail.  In this case a colon
 5581: #                               separated list containing:
 5582: #                               The domain for which we are deleting the id(s).
 5583: #                               &-separated list of id(s) to delete.
 5584: #       $client               - File open on client socket.
 5585: # Returns:
 5586: #     1   - Continue processing
 5587: #     0   - Exit server.
 5588: #     
 5589: #
 5590: 
 5591: sub del_id_handler {
 5592:     my ($cmd,$tail,$client) = @_;
 5593: 
 5594:     my $userinput = "$cmd:$tail";
 5595: 
 5596:     my ($udom,$what)=split(/:/,$tail);
 5597:     chomp($what);
 5598:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
 5599:                                    "D", $what);
 5600:     if ($hashref) {
 5601:         my @keys=split(/\&/,$what);
 5602:         foreach my $key (@keys) {
 5603:             delete($hashref->{$key});
 5604:         }
 5605:         if (&untie_user_hash($hashref)) {
 5606:             &Reply($client, "ok\n", $userinput);
 5607:         } else {
 5608:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5609:                     "while attempting iddel\n", $userinput);
 5610:         }
 5611:     } else {
 5612:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 5613:                  "while attempting iddel\n", $userinput);
 5614:     }
 5615:     return 1;
 5616: }
 5617: &register_handler("iddel", \&del_id_handler, 0, 1, 0);
 5618: 
 5619: #
 5620: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
 5621: #
 5622: # Parameters
 5623: #   $cmd       - Command keyword that caused us to be dispatched.
 5624: #   $tail      - Tail of the command.  Consists of a colon separated:
 5625: #               domain - the domain whose dcmail we are recording
 5626: #               email    Consists of key=value pair 
 5627: #                        where key is unique msgid
 5628: #                        and value is message (in XML)
 5629: #   $client    - Socket open on the client.
 5630: #
 5631: # Returns:
 5632: #    1 - indicating processing should continue.
 5633: # Side effects
 5634: #     reply is written to $client.
 5635: #
 5636: sub put_dcmail_handler {
 5637:     my ($cmd,$tail,$client) = @_;
 5638:     my $userinput = "$cmd:$tail";
 5639: 
 5640: 
 5641:     my ($udom,$what)=split(/:/,$tail);
 5642:     chomp($what);
 5643:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
 5644:     if ($hashref) {
 5645:         my ($key,$value)=split(/=/,$what);
 5646:         $hashref->{$key}=$value;
 5647:     }
 5648:     if (&untie_domain_hash($hashref)) {
 5649:         &Reply($client, "ok\n", $userinput);
 5650:     } else {
 5651:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5652:                  "while attempting dcmailput\n", $userinput);
 5653:     }
 5654:     return 1;
 5655: }
 5656: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
 5657: 
 5658: #
 5659: # Retrieves broadcast e-mail from nohist_dcmail database
 5660: # Returns to client an & separated list of key=value pairs,
 5661: # where key is msgid and value is message information.
 5662: #
 5663: # Parameters
 5664: #   $cmd       - Command keyword that caused us to be dispatched.
 5665: #   $tail      - Tail of the command.  Consists of a colon separated:
 5666: #               domain - the domain whose dcmail table we dump
 5667: #               startfilter - beginning of time window 
 5668: #               endfilter - end of time window
 5669: #               sendersfilter - & separated list of username:domain 
 5670: #                 for senders to search for.
 5671: #   $client    - Socket open on the client.
 5672: #
 5673: # Returns:
 5674: #    1 - indicating processing should continue.
 5675: # Side effects
 5676: #     reply (& separated list of msgid=messageinfo pairs) is 
 5677: #     written to $client.
 5678: #
 5679: sub dump_dcmail_handler {
 5680:     my ($cmd, $tail, $client) = @_;
 5681:                                                                                 
 5682:     my $userinput = "$cmd:$tail";
 5683:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
 5684:     chomp($sendersfilter);
 5685:     my @senders = ();
 5686:     if (defined($startfilter)) {
 5687:         $startfilter=&unescape($startfilter);
 5688:     } else {
 5689:         $startfilter='.';
 5690:     }
 5691:     if (defined($endfilter)) {
 5692:         $endfilter=&unescape($endfilter);
 5693:     } else {
 5694:         $endfilter='.';
 5695:     }
 5696:     if (defined($sendersfilter)) {
 5697:         $sendersfilter=&unescape($sendersfilter);
 5698: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
 5699:     }
 5700: 
 5701:     my $qresult='';
 5702:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
 5703:     if ($hashref) {
 5704:         while (my ($key,$value) = each(%$hashref)) {
 5705:             my $match = 1;
 5706:             my ($timestamp,$subj,$uname,$udom) = 
 5707: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
 5708:             $subj = &unescape($subj);
 5709:             unless ($startfilter eq '.' || !defined($startfilter)) {
 5710:                 if ($timestamp < $startfilter) {
 5711:                     $match = 0;
 5712:                 }
 5713:             }
 5714:             unless ($endfilter eq '.' || !defined($endfilter)) {
 5715:                 if ($timestamp > $endfilter) {
 5716:                     $match = 0;
 5717:                 }
 5718:             }
 5719:             unless (@senders < 1) {
 5720:                 unless (grep/^$uname:$udom$/,@senders) {
 5721:                     $match = 0;
 5722:                 }
 5723:             }
 5724:             if ($match == 1) {
 5725:                 $qresult.=$key.'='.$value.'&';
 5726:             }
 5727:         }
 5728:         if (&untie_domain_hash($hashref)) {
 5729:             chop($qresult);
 5730:             &Reply($client, \$qresult, $userinput);
 5731:         } else {
 5732:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5733:                     "while attempting dcmaildump\n", $userinput);
 5734:         }
 5735:     } else {
 5736:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 5737:                 "while attempting dcmaildump\n", $userinput);
 5738:     }
 5739:     return 1;
 5740: }
 5741: 
 5742: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
 5743: 
 5744: #
 5745: # Puts domain roles in nohist_domainroles database
 5746: #
 5747: # Parameters
 5748: #   $cmd       - Command keyword that caused us to be dispatched.
 5749: #   $tail      - Tail of the command.  Consists of a colon separated:
 5750: #               domain - the domain whose roles we are recording  
 5751: #               role -   Consists of key=value pair
 5752: #                        where key is unique role
 5753: #                        and value is start/end date information
 5754: #   $client    - Socket open on the client.
 5755: #
 5756: # Returns:
 5757: #    1 - indicating processing should continue.
 5758: # Side effects
 5759: #     reply is written to $client.
 5760: #
 5761: 
 5762: sub put_domainroles_handler {
 5763:     my ($cmd,$tail,$client) = @_;
 5764: 
 5765:     my $userinput = "$cmd:$tail";
 5766:     my ($udom,$what)=split(/:/,$tail);
 5767:     chomp($what);
 5768:     my @pairs=split(/\&/,$what);
 5769:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
 5770:     if ($hashref) {
 5771:         foreach my $pair (@pairs) {
 5772:             my ($key,$value)=split(/=/,$pair);
 5773:             $hashref->{$key}=$value;
 5774:         }
 5775:         if (&untie_domain_hash($hashref)) {
 5776:             &Reply($client, "ok\n", $userinput);
 5777:         } else {
 5778:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5779:                      "while attempting domroleput\n", $userinput);
 5780:         }
 5781:     } else {
 5782:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 5783:                   "while attempting domroleput\n", $userinput);
 5784:     }
 5785:                                                                                   
 5786:     return 1;
 5787: }
 5788: 
 5789: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
 5790: 
 5791: #
 5792: # Retrieves domain roles from nohist_domainroles database
 5793: # Returns to client an & separated list of key=value pairs,
 5794: # where key is role and value is start and end date information.
 5795: #
 5796: # Parameters
 5797: #   $cmd       - Command keyword that caused us to be dispatched.
 5798: #   $tail      - Tail of the command.  Consists of a colon separated:
 5799: #               domain - the domain whose domain roles table we dump
 5800: #   $client    - Socket open on the client.
 5801: #
 5802: # Returns:
 5803: #    1 - indicating processing should continue.
 5804: # Side effects
 5805: #     reply (& separated list of role=start/end info pairs) is
 5806: #     written to $client.
 5807: #
 5808: sub dump_domainroles_handler {
 5809:     my ($cmd, $tail, $client) = @_;
 5810:                                                                                            
 5811:     my $userinput = "$cmd:$tail";
 5812:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
 5813:     chomp($rolesfilter);
 5814:     my @roles = ();
 5815:     if (defined($startfilter)) {
 5816:         $startfilter=&unescape($startfilter);
 5817:     } else {
 5818:         $startfilter='.';
 5819:     }
 5820:     if (defined($endfilter)) {
 5821:         $endfilter=&unescape($endfilter);
 5822:     } else {
 5823:         $endfilter='.';
 5824:     }
 5825:     if (defined($rolesfilter)) {
 5826:         $rolesfilter=&unescape($rolesfilter);
 5827: 	@roles = split(/\&/,$rolesfilter);
 5828:     }
 5829: 
 5830:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
 5831:     if ($hashref) {
 5832:         my $qresult = '';
 5833:         while (my ($key,$value) = each(%$hashref)) {
 5834:             my $match = 1;
 5835:             my ($end,$start) = split(/:/,&unescape($value));
 5836:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
 5837:             unless (@roles < 1) {
 5838:                 unless (grep/^\Q$trole\E$/,@roles) {
 5839:                     $match = 0;
 5840:                     next;
 5841:                 }
 5842:             }
 5843:             unless ($startfilter eq '.' || !defined($startfilter)) {
 5844:                 if ((defined($start)) && ($start >= $startfilter)) {
 5845:                     $match = 0;
 5846:                     next;
 5847:                 }
 5848:             }
 5849:             unless ($endfilter eq '.' || !defined($endfilter)) {
 5850:                 if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
 5851:                     $match = 0;
 5852:                     next;
 5853:                 }
 5854:             }
 5855:             if ($match == 1) {
 5856:                 $qresult.=$key.'='.$value.'&';
 5857:             }
 5858:         }
 5859:         if (&untie_domain_hash($hashref)) {
 5860:             chop($qresult);
 5861:             &Reply($client, \$qresult, $userinput);
 5862:         } else {
 5863:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 5864:                     "while attempting domrolesdump\n", $userinput);
 5865:         }
 5866:     } else {
 5867:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 5868:                 "while attempting domrolesdump\n", $userinput);
 5869:     }
 5870:     return 1;
 5871: }
 5872: 
 5873: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
 5874: 
 5875: 
 5876: #  Process the tmpput command I'm not sure what this does.. Seems to
 5877: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
 5878: # where Id is the client's ip concatenated with a sequence number.
 5879: # The file will contain some value that is passed in.  Is this e.g.
 5880: # a login token?
 5881: #
 5882: # Parameters:
 5883: #    $cmd     - The command that got us dispatched.
 5884: #    $tail    - The remainder of the request following $cmd:
 5885: #               In this case this will be the contents of the file.
 5886: #    $client  - Socket connected to the client.
 5887: # Returns:
 5888: #    1 indicating processing can continue.
 5889: # Side effects:
 5890: #   A file is created in the local filesystem.
 5891: #   A reply is sent to the client.
 5892: sub tmp_put_handler {
 5893:     my ($cmd, $what, $client) = @_;
 5894: 
 5895:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
 5896: 
 5897:     my ($record,$context) = split(/:/,$what);
 5898:     if ($context ne '') {
 5899:         chomp($context);
 5900:         $context = &unescape($context);
 5901:     }
 5902:     my ($id,$store);
 5903:     $tmpsnum++;
 5904:     my $numtries = 0;
 5905:     my $execdir=$perlvar{'lonDaemons'};
 5906:     if (($context eq 'resetpw') || ($context eq 'createaccount') ||
 5907:         ($context eq 'sso') || ($context eq 'link') || ($context eq 'retry')) {
 5908:         $id = &md5_hex(&md5_hex(time.{}.rand().$$.$tmpsnum));
 5909:         while ((-e "$execdir/tmp/$id.tmp") && ($numtries <10)) {
 5910:             undef($id);
 5911:             $id = &md5_hex(&md5_hex(time.{}.rand().$$.$tmpsnum));
 5912:             $numtries ++;
 5913:         }
 5914:     } else {
 5915:         $id = $$.'_'.$clientip.'_'.$tmpsnum;
 5916:     }
 5917:     $id=~s/\W/\_/g;
 5918:     $record=~s/\n//g;
 5919:     if (($id ne '') &&
 5920:         ($store=IO::File->new(">$execdir/tmp/$id.tmp"))) {
 5921: 	print $store $record;
 5922: 	close $store;
 5923: 	&Reply($client, \$id, $userinput);
 5924:     } else {
 5925: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
 5926: 		  "while attempting tmpput\n", $userinput);
 5927:     }
 5928:     return 1;
 5929:   
 5930: }
 5931: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
 5932: 
 5933: #   Processes the tmpget command.  This command returns the contents
 5934: #  of a temporary resource file(?) created via tmpput.
 5935: #
 5936: # Paramters:
 5937: #    $cmd      - Command that got us dispatched.
 5938: #    $id       - Tail of the command, contain the id of the resource
 5939: #                we want to fetch.
 5940: #    $client   - socket open on the client.
 5941: # Return:
 5942: #    1         - Inidcating processing can continue.
 5943: # Side effects:
 5944: #   A reply is sent to the client.
 5945: #
 5946: sub tmp_get_handler {
 5947:     my ($cmd, $id, $client) = @_;
 5948: 
 5949:     my $userinput = "$cmd:$id"; 
 5950:     
 5951: 
 5952:     $id=~s/\W/\_/g;
 5953:     my $store;
 5954:     my $execdir=$perlvar{'lonDaemons'};
 5955:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
 5956: 	my $reply=<$store>;
 5957: 	&Reply( $client, \$reply, $userinput);
 5958: 	close $store;
 5959:     } else {
 5960: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
 5961: 		  "while attempting tmpget\n", $userinput);
 5962:     }
 5963: 
 5964:     return 1;
 5965: }
 5966: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
 5967: 
 5968: #
 5969: #  Process the tmpdel command.  This command deletes a temp resource
 5970: #  created by the tmpput command.
 5971: #
 5972: # Parameters:
 5973: #   $cmd      - Command that got us here.
 5974: #   $id       - Id of the temporary resource created.
 5975: #   $client   - socket open on the client process.
 5976: #
 5977: # Returns:
 5978: #   1     - Indicating processing should continue.
 5979: # Side Effects:
 5980: #   A file is deleted
 5981: #   A reply is sent to the client.
 5982: sub tmp_del_handler {
 5983:     my ($cmd, $id, $client) = @_;
 5984:     
 5985:     my $userinput= "$cmd:$id";
 5986:     
 5987:     chomp($id);
 5988:     $id=~s/\W/\_/g;
 5989:     my $execdir=$perlvar{'lonDaemons'};
 5990:     if (unlink("$execdir/tmp/$id.tmp")) {
 5991: 	&Reply($client, "ok\n", $userinput);
 5992:     } else {
 5993: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
 5994: 		  "while attempting tmpdel\n", $userinput);
 5995:     }
 5996:     
 5997:     return 1;
 5998: 
 5999: }
 6000: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
 6001: 
 6002: #
 6003: #  Process the updatebalcookie command.  This command updates a
 6004: #  cookie in the lonBalancedir directory on a load balancer node.
 6005: #
 6006: # Parameters:
 6007: #   $cmd      - Command that got us here.
 6008: #   $tail     - Tail of the request (escaped cookie: escaped current entry)
 6009: #
 6010: #   $client   - socket open on the client process.
 6011: #
 6012: # Returns:
 6013: #   1     - Indicating processing should continue.
 6014: # Side Effects:
 6015: #   A cookie file is updated from the lonBalancedir directory
 6016: #   A reply is sent to the client.
 6017: #
 6018: sub update_balcookie_handler {
 6019:     my ($cmd, $tail, $client) = @_;
 6020: 
 6021:     my $userinput= "$cmd:$tail";
 6022:     chomp($tail);
 6023:     my ($cookie,$lastentry) = map { &unescape($_) } (split(/:/,$tail));
 6024: 
 6025:     my $updatedone;
 6026:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
 6027:         my $execdir=$perlvar{'lonBalanceDir'};
 6028:         if (-e "$execdir/$cookie.id") {
 6029:             my $doupdate;
 6030:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
 6031:                 while (my $line = <$fh>) {
 6032:                     chomp($line);
 6033:                     if ($line eq $lastentry) {
 6034:                         $doupdate = 1;
 6035:                         last;
 6036:                     }
 6037:                 }
 6038:                 close($fh);
 6039:             }
 6040:             if ($doupdate) {
 6041:                 if (open(my $fh,'>',"$execdir/$cookie.id")) {
 6042:                     print $fh $clientname;
 6043:                     close($fh);
 6044:                     $updatedone = 1;
 6045:                 }
 6046:             }
 6047:         }
 6048:     }
 6049:     if ($updatedone) {
 6050:         &Reply($client, "ok\n", $userinput);
 6051:     } else {
 6052:         &Failure( $client, "error: ".($!+0)."file update failed ".
 6053:                   "while attempting updatebalcookie\n", $userinput);
 6054:     }
 6055:     return 1;
 6056: }
 6057: &register_handler("updatebalcookie", \&update_balcookie_handler, 0, 1, 0);
 6058: 
 6059: #
 6060: #  Process the delbalcookie command. This command deletes a balancer
 6061: #  cookie in the lonBalancedir directory on a load balancer node.
 6062: #
 6063: # Parameters:
 6064: #   $cmd      - Command that got us here.
 6065: #   $cookie   - Cookie to be deleted.
 6066: #   $client   - socket open on the client process.
 6067: #
 6068: # Returns:
 6069: #   1     - Indicating processing should continue.
 6070: # Side Effects:
 6071: #   A cookie file is deleted from the lonBalancedir directory
 6072: #   A reply is sent to the client.
 6073: sub del_balcookie_handler {
 6074:     my ($cmd, $cookie, $client) = @_;
 6075: 
 6076:     my $userinput= "$cmd:$cookie";
 6077: 
 6078:     chomp($cookie);
 6079:     $cookie = &unescape($cookie);
 6080:     my $deleted = '';
 6081:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
 6082:         my $execdir=$perlvar{'lonBalanceDir'};
 6083:         if (-e "$execdir/$cookie.id") {
 6084:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
 6085:                 my $dodelete;
 6086:                 while (my $line = <$fh>) {
 6087:                     chomp($line);
 6088:                     if ($line eq $clientname) {
 6089:                         $dodelete = 1;
 6090:                         last;
 6091:                     }
 6092:                 }
 6093:                 close($fh);
 6094:                 if ($dodelete) {
 6095:                     if (unlink("$execdir/$cookie.id")) {
 6096:                         $deleted = 1;
 6097:                     }
 6098:                 }
 6099:             }
 6100:         }
 6101:     }
 6102:     if ($deleted) {
 6103:         &Reply($client, "ok\n", $userinput);
 6104:     } else {
 6105:         &Failure( $client, "error: ".($!+0)."Unlinking cookie file Failed ".
 6106:                   "while attempting delbalcookie\n", $userinput);
 6107:     }
 6108:     return 1;
 6109: }
 6110: &register_handler("delbalcookie", \&del_balcookie_handler, 0, 1, 0);
 6111: 
 6112: #
 6113: #   Processes the setannounce command.  This command
 6114: #   creates a file named announce.txt in the top directory of
 6115: #   the documentn root and sets its contents.  The announce.txt file is
 6116: #   printed in its entirety at the LonCAPA login page.  Note:
 6117: #   once the announcement.txt fileis created it cannot be deleted.
 6118: #   However, setting the contents of the file to empty removes the
 6119: #   announcement from the login page of loncapa so who cares.
 6120: #
 6121: # Parameters:
 6122: #    $cmd          - The command that got us dispatched.
 6123: #    $announcement - The text of the announcement.
 6124: #    $client       - Socket open on the client process.
 6125: # Retunrns:
 6126: #   1             - Indicating request processing should continue
 6127: # Side Effects:
 6128: #   The file {DocRoot}/announcement.txt is created.
 6129: #   A reply is sent to $client.
 6130: #
 6131: sub set_announce_handler {
 6132:     my ($cmd, $announcement, $client) = @_;
 6133:   
 6134:     my $userinput    = "$cmd:$announcement";
 6135: 
 6136:     chomp($announcement);
 6137:     $announcement=&unescape($announcement);
 6138:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
 6139: 				'/announcement.txt')) {
 6140: 	print $store $announcement;
 6141: 	close $store;
 6142: 	&Reply($client, "ok\n", $userinput);
 6143:     } else {
 6144: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
 6145:     }
 6146: 
 6147:     return 1;
 6148: }
 6149: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
 6150: 
 6151: #
 6152: #  Return the version of the daemon.  This can be used to determine
 6153: #  the compatibility of cross version installations or, alternatively to
 6154: #  simply know who's out of date and who isn't.  Note that the version
 6155: #  is returned concatenated with the tail.
 6156: # Parameters:
 6157: #   $cmd        - the request that dispatched to us.
 6158: #   $tail       - Tail of the request (client's version?).
 6159: #   $client     - Socket open on the client.
 6160: #Returns:
 6161: #   1 - continue processing requests.
 6162: # Side Effects:
 6163: #   Replies with version to $client.
 6164: sub get_version_handler {
 6165:     my ($cmd, $tail, $client) = @_;
 6166: 
 6167:     my $userinput  = $cmd.$tail;
 6168:     
 6169:     &Reply($client, &version($userinput)."\n", $userinput);
 6170: 
 6171: 
 6172:     return 1;
 6173: }
 6174: &register_handler("version", \&get_version_handler, 0, 1, 0);
 6175: 
 6176: #  Set the current host and domain.  This is used to support
 6177: #  multihomed systems.  Each IP of the system, or even separate daemons
 6178: #  on the same IP can be treated as handling a separate lonCAPA virtual
 6179: #  machine.  This command selects the virtual lonCAPA.  The client always
 6180: #  knows the right one since it is lonc and it is selecting the domain/system
 6181: #  from the hosts.tab file.
 6182: # Parameters:
 6183: #    $cmd      - Command that dispatched us.
 6184: #    $tail     - Tail of the command (domain/host requested).
 6185: #    $socket   - Socket open on the client.
 6186: #
 6187: # Returns:
 6188: #     1   - Indicates the program should continue to process requests.
 6189: # Side-effects:
 6190: #     The default domain/system context is modified for this daemon.
 6191: #     a reply is sent to the client.
 6192: #
 6193: sub set_virtual_host_handler {
 6194:     my ($cmd, $tail, $socket) = @_;
 6195:   
 6196:     my $userinput  ="$cmd:$tail";
 6197: 
 6198:     &Reply($client, &sethost($userinput)."\n", $userinput);
 6199: 
 6200: 
 6201:     return 1;
 6202: }
 6203: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
 6204: 
 6205: #  Process a request to exit:
 6206: #   - "bye" is sent to the client.
 6207: #   - The client socket is shutdown and closed.
 6208: #   - We indicate to the caller that we should exit.
 6209: # Formal Parameters:
 6210: #   $cmd                - The command that got us here.
 6211: #   $tail               - Tail of the command (empty).
 6212: #   $client             - Socket open on the tail.
 6213: # Returns:
 6214: #   0      - Indicating the program should exit!!
 6215: #
 6216: sub exit_handler {
 6217:     my ($cmd, $tail, $client) = @_;
 6218: 
 6219:     my $userinput = "$cmd:$tail";
 6220: 
 6221:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
 6222:     &Reply($client, "bye\n", $userinput);
 6223:     $client->shutdown(2);        # shutdown the socket forcibly.
 6224:     $client->close();
 6225: 
 6226:     return 0;
 6227: }
 6228: &register_handler("exit", \&exit_handler, 0,1,1);
 6229: &register_handler("init", \&exit_handler, 0,1,1);
 6230: &register_handler("quit", \&exit_handler, 0,1,1);
 6231: 
 6232: #  Determine if auto-enrollment is enabled.
 6233: #  Note that the original had what I believe to be a defect.
 6234: #  The original returned 0 if the requestor was not a registerd client.
 6235: #  It should return "refused".
 6236: # Formal Parameters:
 6237: #   $cmd       - The command that invoked us.
 6238: #   $tail      - The tail of the command (Extra command parameters.
 6239: #   $client    - The socket open on the client that issued the request.
 6240: # Returns:
 6241: #    1         - Indicating processing should continue.
 6242: #
 6243: sub enrollment_enabled_handler {
 6244:     my ($cmd, $tail, $client) = @_;
 6245:     my $userinput = $cmd.":".$tail; # For logging purposes.
 6246: 
 6247:     my ($cdom) = split(/:/, $tail, 2);   # Domain we're asking about.
 6248:     my $outcome;
 6249:     eval {
 6250:         local($SIG{__DIE__})='DEFAULT';
 6251:         $outcome = &localenroll::run($cdom);
 6252:     };
 6253:     &Reply($client, \$outcome, $userinput);
 6254:     return 1;
 6255: }
 6256: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
 6257: 
 6258: #
 6259: #   Validate an institutional code used for a LON-CAPA course.          
 6260: #
 6261: # Formal Parameters:
 6262: #   $cmd          - The command request that got us dispatched.
 6263: #   $tail         - The tail of the command.  In this case,
 6264: #                   this is a colon separated set of words that will be split
 6265: #                   into:
 6266: #                        $dom      - The domain for which the check of 
 6267: #                                    institutional course code will occur.
 6268: #
 6269: #                        $instcode - The institutional code for the course
 6270: #                                    being requested, or validated for rights
 6271: #                                    to request.
 6272: #
 6273: #                        $owner    - The course requestor (who will be the
 6274: #                                    course owner, in the form username:domain
 6275: #
 6276: #   $client       - Socket open on the client.
 6277: # Returns:
 6278: #    1           - Indicating processing should continue.
 6279: #
 6280: sub validate_instcode_handler {
 6281:     my ($cmd, $tail, $client) = @_;
 6282:     my $userinput = "$cmd:$tail";
 6283:     my ($dom,$instcode,$owner) = split(/:/, $tail);
 6284:     $instcode = &unescape($instcode);
 6285:     $owner = &unescape($owner);
 6286:     my ($outcome,$description,$credits);
 6287:     eval {
 6288:         local($SIG{__DIE__})='DEFAULT';
 6289:         ($outcome,$description,$credits) =
 6290:             &localenroll::validate_instcode($dom,$instcode,$owner);
 6291:     };
 6292:     my $result = &escape($outcome).'&'.&escape($description).'&'.
 6293:                  &escape($credits);
 6294:     &Reply($client, \$result, $userinput);
 6295: 
 6296:     return 1;
 6297: }
 6298: &register_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
 6299: 
 6300: #
 6301: #  Validate co-owner for cross-listed institutional code and
 6302: #  institutional course code itself used for a LON-CAPA course.
 6303: #
 6304: # Formal Parameters:
 6305: #   $cmd          - The command request that got us dispatched.
 6306: #   $tail         - The tail of the command.  In this case,
 6307: #                   this is a colon separated string containing:
 6308: #      $dom            - Course's LON-CAPA domain
 6309: #      $instcode       - Institutional course code for the course
 6310: #      $inst_xlist     - Institutional course Id for the crosslisting
 6311: #      $coowner        - Username of co-owner
 6312: #      (values for all but $dom have been escaped). 
 6313: #
 6314: #   $client       - Socket open on the client.
 6315: # Returns:
 6316: #    1           - Indicating processing should continue.
 6317: #
 6318: sub validate_instcrosslist_handler  {
 6319:     my ($cmd, $tail, $client) = @_;
 6320:     my $userinput = "$cmd:$tail";
 6321:     my ($dom,$instcode,$inst_xlist,$coowner) = split(/:/,$tail);
 6322:     $instcode = &unescape($instcode);
 6323:     $inst_xlist = &unescape($inst_xlist);
 6324:     $coowner = &unescape($coowner);
 6325:     my $outcome;
 6326:     eval {
 6327:         local($SIG{__DIE__})='DEFAULT';
 6328:         $outcome = &localenroll::validate_crosslist_access($dom,$instcode,
 6329:                                                            $inst_xlist,$coowner);
 6330:     };
 6331: 
 6332:     &Reply($client, \$outcome, $userinput);
 6333:     return 1;
 6334: }
 6335: &register_handler("autovalidateinstcrosslist", \&validate_instcrosslist_handler, 0, 1, 0);
 6336: 
 6337: #   Get the official sections for which auto-enrollment is possible.
 6338: #   Since the admin people won't know about 'unofficial sections' 
 6339: #   we cannot auto-enroll on them.
 6340: # Formal Parameters:
 6341: #    $cmd     - The command request that got us dispatched here.
 6342: #    $tail    - The remainder of the request.  In our case this
 6343: #               will be split into:
 6344: #               $coursecode   - The course name from the admin point of view.
 6345: #               $cdom         - The course's domain(?).
 6346: #    $client  - Socket open on the client.
 6347: # Returns:
 6348: #    1    - Indiciting processing should continue.
 6349: #
 6350: sub get_sections_handler {
 6351:     my ($cmd, $tail, $client) = @_;
 6352:     my $userinput = "$cmd:$tail";
 6353: 
 6354:     my ($coursecode, $cdom) = split(/:/, $tail);
 6355:     my $seclist;
 6356:     eval {
 6357:         local($SIG{__DIE__})='DEFAULT';
 6358:         my @secs = &localenroll::get_sections($coursecode,$cdom);
 6359:         $seclist = &escape(join(':',@secs));
 6360:     };
 6361:     &Reply($client, \$seclist, $userinput);
 6362:     return 1;
 6363: }
 6364: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
 6365: 
 6366: #   Validate the owner of a new course section.  
 6367: #
 6368: # Formal Parameters:
 6369: #   $cmd      - Command that got us dispatched.
 6370: #   $tail     - the remainder of the command.  For us this consists of a
 6371: #               colon separated string containing:
 6372: #                  $inst    - Course Id from the institutions point of view.
 6373: #                  $owner   - Proposed owner of the course.
 6374: #                  $cdom    - Domain of the course (from the institutions
 6375: #                             point of view?)..
 6376: #   $client   - Socket open on the client.
 6377: #
 6378: # Returns:
 6379: #   1        - Processing should continue.
 6380: #
 6381: 
 6382: sub validate_course_owner_handler {
 6383:     my ($cmd, $tail, $client)  = @_;
 6384:     my $userinput = "$cmd:$tail";
 6385:     my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
 6386:     
 6387:     $owner = &unescape($owner);
 6388:     $coowners = &unescape($coowners);
 6389:     my $outcome;
 6390:     eval {
 6391:         local($SIG{__DIE__})='DEFAULT';
 6392:         $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
 6393:     };
 6394:     &Reply($client, \$outcome, $userinput);
 6395:     return 1;
 6396: }
 6397: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
 6398: 
 6399: #
 6400: #   Validate a course section in the official schedule of classes
 6401: #   from the institutions point of view (part of autoenrollment).
 6402: #
 6403: # Formal Parameters:
 6404: #   $cmd          - The command request that got us dispatched.
 6405: #   $tail         - The tail of the command.  In this case,
 6406: #                   this is a colon separated set of words that will be split
 6407: #                   into:
 6408: #                        $inst_course_id - The course/section id from the
 6409: #                                          institutions point of view.
 6410: #                        $cdom           - The domain from the institutions
 6411: #                                          point of view.
 6412: #   $client       - Socket open on the client.
 6413: # Returns:
 6414: #    1           - Indicating processing should continue.
 6415: #
 6416: sub validate_course_section_handler {
 6417:     my ($cmd, $tail, $client) = @_;
 6418:     my $userinput = "$cmd:$tail";
 6419:     my ($inst_course_id, $cdom) = split(/:/, $tail);
 6420:     my $outcome;
 6421:     eval {
 6422:         local($SIG{__DIE__})='DEFAULT';
 6423:         $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
 6424:     };
 6425:     &Reply($client, \$outcome, $userinput);
 6426:     return 1;
 6427: }
 6428: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
 6429: 
 6430: #
 6431: #   Validate course owner's access to enrollment data for specific class section. 
 6432: #   
 6433: #
 6434: # Formal Parameters:
 6435: #    $cmd     - The command request that got us dispatched.
 6436: #    $tail    - The tail of the command.   In this case this is a colon separated
 6437: #               set of values that will be split into:
 6438: #               $inst_class  - Institutional code for the specific class section   
 6439: #               $ownerlist   - An escaped comma-separated list of username:domain 
 6440: #                              of the course owner, and co-owner(s).
 6441: #               $cdom        - The domain of the course from the institution's
 6442: #                              point of view.
 6443: #    $client  - The socket open on the client.
 6444: # Returns:
 6445: #    1 - continue processing.
 6446: #
 6447: 
 6448: sub validate_class_access_handler {
 6449:     my ($cmd, $tail, $client) = @_;
 6450:     my $userinput = "$cmd:$tail";
 6451:     my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
 6452:     my $owners = &unescape($ownerlist);
 6453:     my $outcome;
 6454:     eval {
 6455: 	local($SIG{__DIE__})='DEFAULT';
 6456: 	$outcome=&localenroll::check_section($inst_class,$owners,$cdom);
 6457:     };
 6458:     &Reply($client,\$outcome, $userinput);
 6459:     return 1;
 6460: }
 6461: &register_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
 6462: 
 6463: #
 6464: #    Modify institutional sections (using customized &instsec_reformat()
 6465: #    routine in localenroll.pm), to either clutter or declutter, for  
 6466: #    purposes of ensuring an institutional course section (string) can
 6467: #    be unambiguously separated into institutional course and section.
 6468: #
 6469: # Formal Parameters:
 6470: #    $cmd     - The command request that got us dispatched.
 6471: #    $tail    - The tail of the command.   In this case this is a colon separated
 6472: #               set of values that will be split into:
 6473: #               $cdom        - The LON-CAPA domain of the course.
 6474: #               $action      - Either: clutter or declutter
 6475: #                              clutter adds character(s) to eliminate ambiguity
 6476: #                              declutter removes the added characters (e.g., for
 6477: #                              display of the institutional course section string.
 6478: #               $info        - A frozen hash in which keys are: 
 6479: #                              LON-CAPA course number:Institutional course code
 6480: #                              and values are a reference to an array of the
 6481: #                              items to modify -- either institutional sections,
 6482: #                              or institutional course sections (for crosslistings). 
 6483: #    $client  - The socket open on the client.
 6484: # Returns:
 6485: #    1 - continue processing.
 6486: #   
 6487: 
 6488: sub instsec_reformat_handler {
 6489:     my ($cmd, $tail, $client) = @_;
 6490:     my $userinput = "$cmd:$tail";
 6491:     my ($cdom,$action,$info) = split(/:/,$tail);
 6492:     my $instsecref = &Apache::lonnet::thaw_unescape($info);
 6493:     my ($outcome,$result);
 6494:     eval {
 6495:         local($SIG{__DIE__})='DEFAULT';
 6496:         $outcome=&localenroll::instsec_reformat($cdom,$action,$instsecref);
 6497:         if ($outcome eq 'ok') {
 6498:             if (ref($instsecref) eq 'HASH') {
 6499:                 foreach my $key (keys(%{$instsecref})) {
 6500:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($instsecref->{$key}).'&';
 6501:                 }
 6502:                 $result =~ s/\&$//;
 6503:             }
 6504:         }
 6505:     };
 6506:     if (!$@) {
 6507:         if ($outcome eq 'ok') {
 6508:             &Reply( $client, \$result, $userinput);
 6509:         } else {
 6510:             &Reply($client,\$outcome, $userinput);
 6511:         }
 6512:     } else {
 6513:         &Failure($client,"unknown_cmd\n",$userinput);
 6514:     }
 6515:     return 1;
 6516: }
 6517: &register_handler("autoinstsecreformat",\&instsec_reformat_handler, 0, 1, 0);
 6518: 
 6519: #
 6520: #   Validate course owner or co-owners(s) access to enrollment data for all sections
 6521: #   and crosslistings for a particular course.
 6522: #
 6523: #
 6524: # Formal Parameters:
 6525: #    $cmd     - The command request that got us dispatched.
 6526: #    $tail    - The tail of the command.   In this case this is a colon separated
 6527: #               set of values that will be split into:
 6528: #               $ownerlist   - An escaped comma-separated list of username:domain
 6529: #                              of the course owner, and co-owner(s).
 6530: #               $cdom        - The domain of the course from the institution's
 6531: #                              point of view.
 6532: #               $classes     - Frozen hash of institutional course sections and
 6533: #                              crosslistings.
 6534: #    $client  - The socket open on the client.
 6535: # Returns:
 6536: #    1 - continue processing.
 6537: #
 6538: 
 6539: sub validate_classes_handler {
 6540:     my ($cmd, $tail, $client) = @_;
 6541:     my $userinput = "$cmd:$tail";
 6542:     my ($ownerlist,$cdom,$classes) = split(/:/, $tail);
 6543:     my $classesref = &Apache::lonnet::thaw_unescape($classes);
 6544:     my $owners = &unescape($ownerlist);
 6545:     my $result;
 6546:     eval {
 6547:         local($SIG{__DIE__})='DEFAULT';
 6548:         my %validations;
 6549:         my $response = &localenroll::check_instclasses($owners,$cdom,$classesref,
 6550:                                                        \%validations);
 6551:         if ($response eq 'ok') {
 6552:             foreach my $key (keys(%validations)) {
 6553:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
 6554:             }
 6555:             $result =~ s/\&$//;
 6556:         } else {
 6557:             $result = 'error';
 6558:         }
 6559:     };
 6560:     if (!$@) {
 6561:         &Reply($client, \$result, $userinput);
 6562:     } else {
 6563:         &Failure($client,"unknown_cmd\n",$userinput);
 6564:     }
 6565:     return 1;
 6566: }
 6567: &register_handler("autovalidateinstclasses", \&validate_classes_handler, 0, 1, 0);
 6568: 
 6569: #
 6570: #   Create a password for a new LON-CAPA user added by auto-enrollment.
 6571: #   Only used for case where authentication method for new user is localauth
 6572: #
 6573: # Formal Parameters:
 6574: #    $cmd     - The command request that got us dispatched.
 6575: #    $tail    - The tail of the command.   In this case this is a colon separated
 6576: #               set of words that will be split into:
 6577: #               $authparam - An authentication parameter (localauth parameter).
 6578: #               $cdom      - The domain of the course from the institution's
 6579: #                            point of view.
 6580: #    $client  - The socket open on the client.
 6581: # Returns:
 6582: #    1 - continue processing.
 6583: #
 6584: sub create_auto_enroll_password_handler {
 6585:     my ($cmd, $tail, $client) = @_;
 6586:     my $userinput = "$cmd:$tail";
 6587: 
 6588:     my ($authparam, $cdom) = split(/:/, $userinput);
 6589: 
 6590:     my ($create_passwd,$authchk);
 6591:     eval {
 6592:         local($SIG{__DIE__})='DEFAULT';
 6593:         ($authparam,$create_passwd,$create_passwd,$authchk) = 
 6594:             &localenroll::create_password($authparam,$cdom);
 6595:     };
 6596:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
 6597: 	   $userinput);
 6598: 
 6599: 
 6600:     return 1;
 6601: }
 6602: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
 6603: 		  0, 1, 0);
 6604: 
 6605: sub auto_export_grades_handler {
 6606:     my ($cmd, $tail, $client) = @_;
 6607:     my $userinput = "$cmd:$tail";
 6608:     my ($cdom,$cnum,$info,$data) = split(/:/,$tail);
 6609:     my $inforef = &Apache::lonnet::thaw_unescape($info);
 6610:     my $dataref = &Apache::lonnet::thaw_unescape($data);
 6611:     my ($outcome,$result);;
 6612:     eval {
 6613:         local($SIG{__DIE__})='DEFAULT';
 6614:         my %rtnhash;
 6615:         $outcome=&localenroll::export_grades($cdom,$cnum,$inforef,$dataref,\%rtnhash);
 6616:         if ($outcome eq 'ok') {
 6617:             foreach my $key (keys(%rtnhash)) {
 6618:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
 6619:             }
 6620:             $result =~ s/\&$//;
 6621:         }
 6622:     };
 6623:     if (!$@) {
 6624:         if ($outcome eq 'ok') {
 6625:             if ($cipher) {
 6626:                 my $cmdlength=length($result);
 6627:                 $result.="         ";
 6628:                 my $encresult='';
 6629:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 6630:                     $encresult.= unpack("H16",
 6631:                                         $cipher->encrypt(substr($result,
 6632:                                                                 $encidx,
 6633:                                                                 8)));
 6634:                 }
 6635:                 &Reply( $client, "enc:$cmdlength:$encresult\n", $userinput);
 6636:             } else {
 6637:                 &Failure( $client, "error:no_key\n", $userinput);
 6638:             }
 6639:         } else {
 6640:             &Reply($client, "$outcome\n", $userinput);
 6641:         }
 6642:     } else {
 6643:         &Failure($client,"export_error\n",$userinput);
 6644:     }
 6645:     return 1;
 6646: }
 6647: &register_handler("autoexportgrades", \&auto_export_grades_handler,
 6648:                   1, 1, 0);
 6649: 
 6650: #   Retrieve and remove temporary files created by/during autoenrollment.
 6651: #
 6652: # Formal Parameters:
 6653: #    $cmd      - The command that got us dispatched.
 6654: #    $tail     - The tail of the command.  In our case this is a colon 
 6655: #                separated list that will be split into:
 6656: #                $filename - The name of the file to retrieve.
 6657: #                            The filename is given as a path relative to
 6658: #                            the LonCAPA temp file directory.
 6659: #    $client   - Socket open on the client.
 6660: #
 6661: # Returns:
 6662: #   1     - Continue processing.
 6663: sub retrieve_auto_file_handler {
 6664:     my ($cmd, $tail, $client)    = @_;
 6665:     my $userinput                = "cmd:$tail";
 6666: 
 6667:     my ($filename)   = split(/:/, $tail);
 6668: 
 6669:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
 6670: 
 6671:     if ($filename =~m{/\.\./}) {
 6672:         &Failure($client, "refused\n", $userinput);
 6673:     } elsif ($filename !~ /^$LONCAPA::match_domain\_$LONCAPA::match_courseid\_.+_classlist\.xml$/) {
 6674:         &Failure($client, "refused\n", $userinput);
 6675:     } elsif ( (-e $source) && ($filename ne '') ) {
 6676: 	my $reply = '';
 6677: 	if (open(my $fh,$source)) {
 6678: 	    while (<$fh>) {
 6679: 		chomp($_);
 6680: 		$_ =~ s/^\s+//g;
 6681: 		$_ =~ s/\s+$//g;
 6682: 		$reply .= $_;
 6683: 	    }
 6684: 	    close($fh);
 6685: 	    &Reply($client, &escape($reply)."\n", $userinput);
 6686: 
 6687: #   Does this have to be uncommented??!?  (RF).
 6688: #
 6689: #                                unlink($source);
 6690: 	} else {
 6691: 	    &Failure($client, "error\n", $userinput);
 6692: 	}
 6693:     } else {
 6694: 	&Failure($client, "error\n", $userinput);
 6695:     }
 6696:     
 6697: 
 6698:     return 1;
 6699: }
 6700: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
 6701: 
 6702: sub crsreq_checks_handler {
 6703:     my ($cmd, $tail, $client) = @_;
 6704:     my $userinput = "$cmd:$tail";
 6705:     my $dom = $tail;
 6706:     my $result;
 6707:     my @reqtypes = ('official','unofficial','community','textbook','placement');
 6708:     eval {
 6709:         local($SIG{__DIE__})='DEFAULT';
 6710:         my %validations;
 6711:         my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
 6712:                                                    \%validations);
 6713:         if ($response eq 'ok') { 
 6714:             foreach my $key (keys(%validations)) {
 6715:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
 6716:             }
 6717:             $result =~ s/\&$//;
 6718:         } else {
 6719:             $result = 'error';
 6720:         }
 6721:     };
 6722:     if (!$@) {
 6723:         &Reply($client, \$result, $userinput);
 6724:     } else {
 6725:         &Failure($client,"unknown_cmd\n",$userinput);
 6726:     }
 6727:     return 1;
 6728: }
 6729: &register_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
 6730: 
 6731: sub validate_crsreq_handler {
 6732:     my ($cmd, $tail, $client) = @_;
 6733:     my $userinput = "$cmd:$tail";
 6734:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
 6735:     $instcode = &unescape($instcode);
 6736:     $owner = &unescape($owner);
 6737:     $crstype = &unescape($crstype);
 6738:     $inststatuslist = &unescape($inststatuslist);
 6739:     $instcode = &unescape($instcode);
 6740:     $instseclist = &unescape($instseclist);
 6741:     my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
 6742:     my $outcome;
 6743:     eval {
 6744:         local($SIG{__DIE__})='DEFAULT';
 6745:         $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
 6746:                                                  $inststatuslist,$instcode,
 6747:                                                  $instseclist,$custominfo);
 6748:     };
 6749:     if (!$@) {
 6750:         &Reply($client, \$outcome, $userinput);
 6751:     } else {
 6752:         &Failure($client,"unknown_cmd\n",$userinput);
 6753:     }
 6754:     return 1;
 6755: }
 6756: &register_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
 6757: 
 6758: sub crsreq_update_handler {
 6759:     my ($cmd, $tail, $client) = @_;
 6760:     my $userinput = "$cmd:$tail";
 6761:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
 6762:         $accessstart,$accessend,$infohashref) =
 6763:         split(/:/, $tail);
 6764:     $crstype = &unescape($crstype);
 6765:     $action = &unescape($action);
 6766:     $ownername = &unescape($ownername);
 6767:     $ownerdomain = &unescape($ownerdomain);
 6768:     $fullname = &unescape($fullname);
 6769:     $title = &unescape($title);
 6770:     $code = &unescape($code);
 6771:     $accessstart = &unescape($accessstart);
 6772:     $accessend = &unescape($accessend);
 6773:     my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
 6774:     my ($result,$outcome);
 6775:     eval {
 6776:         local($SIG{__DIE__})='DEFAULT';
 6777:         my %rtnhash;
 6778:         $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
 6779:                                                 $ownername,$ownerdomain,$fullname,
 6780:                                                 $title,$code,$accessstart,$accessend,
 6781:                                                 $incoming,\%rtnhash);
 6782:         if ($outcome eq 'ok') {
 6783:             my @posskeys = qw(createdweb createdmsg createdcustomized createdactions queuedweb queuedmsg formitems reviewweb validationjs onload javascript);
 6784:             foreach my $key (keys(%rtnhash)) {
 6785:                 if (grep(/^\Q$key\E/,@posskeys)) {
 6786:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
 6787:                 }
 6788:             }
 6789:             $result =~ s/\&$//;
 6790:         }
 6791:     };
 6792:     if (!$@) {
 6793:         if ($outcome eq 'ok') {
 6794:             &Reply($client, \$result, $userinput);
 6795:         } else {
 6796:             &Reply($client, "format_error\n", $userinput);
 6797:         }
 6798:     } else {
 6799:         &Failure($client,"unknown_cmd\n",$userinput);
 6800:     }
 6801:     return 1;
 6802: }
 6803: &register_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
 6804: 
 6805: #
 6806: #   Read and retrieve institutional code format (for support form).
 6807: # Formal Parameters:
 6808: #    $cmd        - Command that dispatched us.
 6809: #    $tail       - Tail of the command.  In this case it conatins 
 6810: #                  the course domain and the coursename.
 6811: #    $client     - Socket open on the client.
 6812: # Returns:
 6813: #    1     - Continue processing.
 6814: #
 6815: sub get_institutional_code_format_handler {
 6816:     my ($cmd, $tail, $client)   = @_;
 6817:     my $userinput               = "$cmd:$tail";
 6818: 
 6819:     my $reply;
 6820:     my($cdom,$course) = split(/:/,$tail);
 6821:     my @pairs = split/\&/,$course;
 6822:     my %instcodes = ();
 6823:     my %codes = ();
 6824:     my @codetitles = ();
 6825:     my %cat_titles = ();
 6826:     my %cat_order = ();
 6827:     foreach (@pairs) {
 6828: 	my ($key,$value) = split/=/,$_;
 6829: 	$instcodes{&unescape($key)} = &unescape($value);
 6830:     }
 6831:     my $formatreply; 
 6832:     eval {
 6833:         local($SIG{__DIE__})='DEFAULT';
 6834:         $formatreply = &localenroll::instcode_format($cdom,
 6835: 	   					     \%instcodes,
 6836: 						     \%codes,
 6837: 						     \@codetitles,
 6838: 						     \%cat_titles,
 6839: 						     \%cat_order);
 6840:     };
 6841:     if ($formatreply eq 'ok') {
 6842: 	my $codes_str = &Apache::lonnet::hash2str(%codes);
 6843: 	my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
 6844: 	my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
 6845: 	my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
 6846: 	&Reply($client,
 6847: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
 6848: 	       .$cat_order_str."\n",
 6849: 	       $userinput);
 6850:     } else {
 6851: 	# this else branch added by RF since if not ok, lonc will
 6852: 	# hang waiting on reply until timeout.
 6853: 	#
 6854: 	&Reply($client, "format_error\n", $userinput);
 6855:     }
 6856:     
 6857:     return 1;
 6858: }
 6859: &register_handler("autoinstcodeformat",
 6860: 		  \&get_institutional_code_format_handler,0,1,0);
 6861: 
 6862: sub get_institutional_defaults_handler {
 6863:     my ($cmd, $tail, $client)   = @_;
 6864:     my $userinput               = "$cmd:$tail";
 6865: 
 6866:     my $dom = $tail;
 6867:     my %defaults_hash;
 6868:     my @code_order;
 6869:     my $outcome;
 6870:     eval {
 6871:         local($SIG{__DIE__})='DEFAULT';
 6872:         $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
 6873:                                                    \@code_order);
 6874:     };
 6875:     if (!$@) {
 6876:         if ($outcome eq 'ok') {
 6877:             my $result='';
 6878:             while (my ($key,$value) = each(%defaults_hash)) {
 6879:                 $result.=&escape($key).'='.&escape($value).'&';
 6880:             }
 6881:             $result .= 'code_order='.&escape(join('&',@code_order));
 6882:             &Reply($client,\$result,$userinput);
 6883:         } else {
 6884:             &Reply($client,"error\n", $userinput);
 6885:         }
 6886:     } else {
 6887:         &Failure($client,"unknown_cmd\n",$userinput);
 6888:     }
 6889: }
 6890: &register_handler("autoinstcodedefaults",
 6891:                   \&get_institutional_defaults_handler,0,1,0);
 6892: 
 6893: sub get_possible_instcodes_handler {
 6894:     my ($cmd, $tail, $client)   = @_;
 6895:     my $userinput               = "$cmd:$tail";
 6896: 
 6897:     my $reply;
 6898:     my $cdom = $tail;
 6899:     my (@codetitles,%cat_titles,%cat_order,@code_order);
 6900:     my $formatreply;
 6901:     eval {
 6902:         local($SIG{__DIE__})='DEFAULT';
 6903:         $formatreply = &localenroll::possible_instcodes($cdom,
 6904:                                                         \@codetitles,
 6905:                                                         \%cat_titles,
 6906:                                                         \%cat_order,
 6907:                                                         \@code_order);
 6908:     };
 6909:     if ($formatreply eq 'ok') {
 6910:         my $result = join('&',map {&escape($_);} (@codetitles)).':';
 6911:         $result .= join('&',map {&escape($_);} (@code_order)).':';
 6912:         foreach my $key (keys(%cat_titles)) {
 6913:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
 6914:         }
 6915:         $result =~ s/\&$//;
 6916:         $result .= ':';
 6917:         foreach my $key (keys(%cat_order)) {
 6918:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
 6919:         }
 6920:         $result =~ s/\&$//;
 6921:         &Reply($client,\$result,$userinput);
 6922:     } else {
 6923:         &Reply($client, "format_error\n", $userinput);
 6924:     }
 6925:     return 1;
 6926: }
 6927: &register_handler("autopossibleinstcodes",
 6928:                   \&get_possible_instcodes_handler,0,1,0);
 6929: 
 6930: sub get_institutional_user_rules {
 6931:     my ($cmd, $tail, $client)   = @_;
 6932:     my $userinput               = "$cmd:$tail";
 6933:     my $dom = &unescape($tail);
 6934:     my (%rules_hash,@rules_order);
 6935:     my $outcome;
 6936:     eval {
 6937:         local($SIG{__DIE__})='DEFAULT';
 6938:         $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
 6939:     };
 6940:     if (!$@) {
 6941:         if ($outcome eq 'ok') {
 6942:             my $result;
 6943:             foreach my $key (keys(%rules_hash)) {
 6944:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
 6945:             }
 6946:             $result =~ s/\&$//;
 6947:             $result .= ':';
 6948:             if (@rules_order > 0) {
 6949:                 foreach my $item (@rules_order) {
 6950:                     $result .= &escape($item).'&';
 6951:                 }
 6952:             }
 6953:             $result =~ s/\&$//;
 6954:             &Reply($client,\$result,$userinput);
 6955:         } else {
 6956:             &Reply($client,"error\n", $userinput);
 6957:         }
 6958:     } else {
 6959:         &Failure($client,"unknown_cmd\n",$userinput);
 6960:     }
 6961: }
 6962: &register_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
 6963: 
 6964: sub get_institutional_id_rules {
 6965:     my ($cmd, $tail, $client)   = @_;
 6966:     my $userinput               = "$cmd:$tail";
 6967:     my $dom = &unescape($tail);
 6968:     my (%rules_hash,@rules_order);
 6969:     my $outcome;
 6970:     eval {
 6971:         local($SIG{__DIE__})='DEFAULT';
 6972:         $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
 6973:     };
 6974:     if (!$@) {
 6975:         if ($outcome eq 'ok') {
 6976:             my $result;
 6977:             foreach my $key (keys(%rules_hash)) {
 6978:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
 6979:             }
 6980:             $result =~ s/\&$//;
 6981:             $result .= ':';
 6982:             if (@rules_order > 0) {
 6983:                 foreach my $item (@rules_order) {
 6984:                     $result .= &escape($item).'&';
 6985:                 }
 6986:             }
 6987:             $result =~ s/\&$//;
 6988:             &Reply($client,\$result,$userinput);
 6989:         } else {
 6990:             &Reply($client,"error\n", $userinput);
 6991:         }
 6992:     } else {
 6993:         &Failure($client,"unknown_cmd\n",$userinput);
 6994:     }
 6995: }
 6996: &register_handler("instidrules",\&get_institutional_id_rules,0,1,0);
 6997: 
 6998: sub get_institutional_selfcreate_rules {
 6999:     my ($cmd, $tail, $client)   = @_;
 7000:     my $userinput               = "$cmd:$tail";
 7001:     my $dom = &unescape($tail);
 7002:     my (%rules_hash,@rules_order);
 7003:     my $outcome;
 7004:     eval {
 7005:         local($SIG{__DIE__})='DEFAULT';
 7006:         $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
 7007:     };
 7008:     if (!$@) {
 7009:         if ($outcome eq 'ok') {
 7010:             my $result;
 7011:             foreach my $key (keys(%rules_hash)) {
 7012:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
 7013:             }
 7014:             $result =~ s/\&$//;
 7015:             $result .= ':';
 7016:             if (@rules_order > 0) {
 7017:                 foreach my $item (@rules_order) {
 7018:                     $result .= &escape($item).'&';
 7019:                 }
 7020:             }
 7021:             $result =~ s/\&$//;
 7022:             &Reply($client,\$result,$userinput);
 7023:         } else {
 7024:             &Reply($client,"error\n", $userinput);
 7025:         }
 7026:     } else {
 7027:         &Failure($client,"unknown_cmd\n",$userinput);
 7028:     }
 7029: }
 7030: &register_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
 7031: 
 7032: sub get_unamemap_rules {
 7033:     my ($cmd, $tail, $client)   = @_;
 7034:     my $userinput               = "$cmd:$tail";
 7035:     my $dom = &unescape($tail);
 7036:     my (%rules_hash,@rules_order);
 7037:     my $outcome;
 7038:     eval {
 7039:         local($SIG{__DIE__})='DEFAULT';
 7040:         $outcome = &localenroll::unamemap_rules($dom,\%rules_hash,\@rules_order);
 7041:     };
 7042:     if (!$@) {
 7043:         if ($outcome eq 'ok') {
 7044:             my $result;
 7045:             foreach my $key (keys(%rules_hash)) {
 7046:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
 7047:             }
 7048:             $result =~ s/\&$//;
 7049:             $result .= ':';
 7050:             if (@rules_order > 0) {
 7051:                 foreach my $item (@rules_order) {
 7052:                     $result .= &escape($item).'&';
 7053:                 }
 7054:             }
 7055:             $result =~ s/\&$//;
 7056:             &Reply($client,\$result,$userinput);
 7057:         } else {
 7058:             &Reply($client,"error\n", $userinput);
 7059:         }
 7060:     } else {
 7061:         &Failure($client,"unknown_cmd\n",$userinput);
 7062:     }
 7063: }
 7064: &register_handler("unamemaprules",\&get_unamemap_rules,0,1,0);
 7065: 
 7066: sub institutional_username_check {
 7067:     my ($cmd, $tail, $client)   = @_;
 7068:     my $userinput               = "$cmd:$tail";
 7069:     my %rulecheck;
 7070:     my $outcome;
 7071:     my ($udom,$uname,@rules) = split(/:/,$tail);
 7072:     $udom = &unescape($udom);
 7073:     $uname = &unescape($uname);
 7074:     @rules = map {&unescape($_);} (@rules);
 7075:     eval {
 7076:         local($SIG{__DIE__})='DEFAULT';
 7077:         $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
 7078:     };
 7079:     if (!$@) {
 7080:         if ($outcome eq 'ok') {
 7081:             my $result='';
 7082:             foreach my $key (keys(%rulecheck)) {
 7083:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
 7084:             }
 7085:             &Reply($client,\$result,$userinput);
 7086:         } else {
 7087:             &Reply($client,"error\n", $userinput);
 7088:         }
 7089:     } else {
 7090:         &Failure($client,"unknown_cmd\n",$userinput);
 7091:     }
 7092: }
 7093: &register_handler("instrulecheck",\&institutional_username_check,0,1,0);
 7094: 
 7095: sub institutional_id_check {
 7096:     my ($cmd, $tail, $client)   = @_;
 7097:     my $userinput               = "$cmd:$tail";
 7098:     my %rulecheck;
 7099:     my $outcome;
 7100:     my ($udom,$id,@rules) = split(/:/,$tail);
 7101:     $udom = &unescape($udom);
 7102:     $id = &unescape($id);
 7103:     @rules = map {&unescape($_);} (@rules);
 7104:     eval {
 7105:         local($SIG{__DIE__})='DEFAULT';
 7106:         $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
 7107:     };
 7108:     if (!$@) {
 7109:         if ($outcome eq 'ok') {
 7110:             my $result='';
 7111:             foreach my $key (keys(%rulecheck)) {
 7112:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
 7113:             }
 7114:             &Reply($client,\$result,$userinput);
 7115:         } else {
 7116:             &Reply($client,"error\n", $userinput);
 7117:         }
 7118:     } else {
 7119:         &Failure($client,"unknown_cmd\n",$userinput);
 7120:     }
 7121: }
 7122: &register_handler("instidrulecheck",\&institutional_id_check,0,1,0);
 7123: 
 7124: sub institutional_selfcreate_check {
 7125:     my ($cmd, $tail, $client)   = @_;
 7126:     my $userinput               = "$cmd:$tail";
 7127:     my %rulecheck;
 7128:     my $outcome;
 7129:     my ($udom,$email,@rules) = split(/:/,$tail);
 7130:     $udom = &unescape($udom);
 7131:     $email = &unescape($email);
 7132:     @rules = map {&unescape($_);} (@rules);
 7133:     eval {
 7134:         local($SIG{__DIE__})='DEFAULT';
 7135:         $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
 7136:     };
 7137:     if (!$@) {
 7138:         if ($outcome eq 'ok') {
 7139:             my $result='';
 7140:             foreach my $key (keys(%rulecheck)) {
 7141:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
 7142:             }
 7143:             &Reply($client,\$result,$userinput);
 7144:         } else {
 7145:             &Reply($client,"error\n", $userinput);
 7146:         }
 7147:     } else {
 7148:         &Failure($client,"unknown_cmd\n",$userinput);
 7149:     }
 7150: }
 7151: &register_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
 7152: 
 7153: # Get domain specific conditions for import of student photographs to a course
 7154: #
 7155: # Retrieves information from photo_permission subroutine in localenroll.
 7156: # Returns outcome (ok) if no processing errors, and whether course owner is 
 7157: # required to accept conditions of use (yes/no).
 7158: #
 7159: #    
 7160: sub photo_permission_handler {
 7161:     my ($cmd, $tail, $client)   = @_;
 7162:     my $userinput               = "$cmd:$tail";
 7163:     my $cdom = $tail;
 7164:     my ($perm_reqd,$conditions);
 7165:     my $outcome;
 7166:     eval {
 7167: 	local($SIG{__DIE__})='DEFAULT';
 7168: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
 7169: 						  \$conditions);
 7170:     };
 7171:     if (!$@) {
 7172: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
 7173: 	       $userinput);
 7174:     } else {
 7175: 	&Failure($client,"unknown_cmd\n",$userinput);
 7176:     }
 7177:     return 1;
 7178: }
 7179: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
 7180: 
 7181: #
 7182: # Checks if student photo is available for a user in the domain, in the user's
 7183: # directory (in /userfiles/internal/studentphoto.jpg).
 7184: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
 7185: # the student's photo.   
 7186: 
 7187: sub photo_check_handler {
 7188:     my ($cmd, $tail, $client)   = @_;
 7189:     my $userinput               = "$cmd:$tail";
 7190:     my ($udom,$uname,$pid) = split(/:/,$tail);
 7191:     $udom = &unescape($udom);
 7192:     $uname = &unescape($uname);
 7193:     $pid = &unescape($pid);
 7194:     my $path=&propath($udom,$uname).'/userfiles/internal/';
 7195:     if (!-e $path) {
 7196:         &mkpath($path);
 7197:     }
 7198:     my $response;
 7199:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
 7200:     $result .= ':'.$response;
 7201:     &Reply($client, &escape($result)."\n",$userinput);
 7202:     return 1;
 7203: }
 7204: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
 7205: 
 7206: #
 7207: # Retrieve information from localenroll about whether to provide a button     
 7208: # for users who have enbled import of student photos to initiate an 
 7209: # update of photo files for registered students. Also include 
 7210: # comment to display alongside button.  
 7211: 
 7212: sub photo_choice_handler {
 7213:     my ($cmd, $tail, $client) = @_;
 7214:     my $userinput             = "$cmd:$tail";
 7215:     my $cdom                  = &unescape($tail);
 7216:     my ($update,$comment);
 7217:     eval {
 7218: 	local($SIG{__DIE__})='DEFAULT';
 7219: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
 7220:     };
 7221:     if (!$@) {
 7222: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
 7223:     } else {
 7224: 	&Failure($client,"unknown_cmd\n",$userinput);
 7225:     }
 7226:     return 1;
 7227: }
 7228: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
 7229: 
 7230: #
 7231: # Gets a student's photo to exist (in the correct image type) in the user's 
 7232: # directory.
 7233: # Formal Parameters:
 7234: #    $cmd     - The command request that got us dispatched.
 7235: #    $tail    - A colon separated set of words that will be split into:
 7236: #               $domain - student's domain
 7237: #               $uname  - student username
 7238: #               $type   - image type desired
 7239: #    $client  - The socket open on the client.
 7240: # Returns:
 7241: #    1 - continue processing.
 7242: 
 7243: sub student_photo_handler {
 7244:     my ($cmd, $tail, $client) = @_;
 7245:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
 7246: 
 7247:     my $path=&propath($domain,$uname). '/userfiles/internal/';
 7248:     my $filename = 'studentphoto.'.$ext;
 7249:     if ($type eq 'thumbnail') {
 7250:         $filename = 'studentphoto_tn.'.$ext;
 7251:     }
 7252:     if (-e $path.$filename) {
 7253: 	&Reply($client,"ok\n","$cmd:$tail");
 7254: 	return 1;
 7255:     }
 7256:     &mkpath($path);
 7257:     my $file;
 7258:     if ($type eq 'thumbnail') {
 7259: 	eval {
 7260: 	    local($SIG{__DIE__})='DEFAULT';
 7261: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
 7262: 	};
 7263:     } else {
 7264:         $file=&localstudentphoto::fetch($domain,$uname);
 7265:     }
 7266:     if (!$file) {
 7267: 	&Failure($client,"unavailable\n","$cmd:$tail");
 7268: 	return 1;
 7269:     }
 7270:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
 7271:     if (-e $path.$filename) {
 7272: 	&Reply($client,"ok\n","$cmd:$tail");
 7273: 	return 1;
 7274:     }
 7275:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
 7276:     return 1;
 7277: }
 7278: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
 7279: 
 7280: sub inst_usertypes_handler {
 7281:     my ($cmd, $domain, $client) = @_;
 7282:     my $res;
 7283:     my $userinput = $cmd.":".$domain; # For logging purposes.
 7284:     my (%typeshash,@order,$result);
 7285:     eval {
 7286: 	local($SIG{__DIE__})='DEFAULT';
 7287: 	$result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
 7288:     };
 7289:     if ($result eq 'ok') {
 7290:         if (keys(%typeshash) > 0) {
 7291:             foreach my $key (keys(%typeshash)) {
 7292:                 $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
 7293:             }
 7294:         }
 7295:         $res=~s/\&$//;
 7296:         $res .= ':';
 7297:         if (@order > 0) {
 7298:             foreach my $item (@order) {
 7299:                 $res .= &escape($item).'&';
 7300:             }
 7301:         }
 7302:         $res=~s/\&$//;
 7303:     }
 7304:     &Reply($client, \$res, $userinput);
 7305:     return 1;
 7306: }
 7307: &register_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
 7308: 
 7309: # mkpath makes all directories for a file, expects an absolute path with a
 7310: # file or a trailing / if just a dir is passed
 7311: # returns 1 on success 0 on failure
 7312: sub mkpath {
 7313:     my ($file)=@_;
 7314:     my @parts=split(/\//,$file,-1);
 7315:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
 7316:     for (my $i=3;$i<= ($#parts-1);$i++) {
 7317: 	$now.='/'.$parts[$i]; 
 7318: 	if (!-e $now) {
 7319: 	    if  (!mkdir($now,0770)) { return 0; }
 7320: 	}
 7321:     }
 7322:     return 1;
 7323: }
 7324: 
 7325: #---------------------------------------------------------------
 7326: #
 7327: #   Getting, decoding and dispatching requests:
 7328: #
 7329: #
 7330: #   Get a Request:
 7331: #   Gets a Request message from the client.  The transaction
 7332: #   is defined as a 'line' of text.  We remove the new line
 7333: #   from the text line.  
 7334: #
 7335: sub get_request {
 7336:     my $input = <$client>;
 7337:     chomp($input);
 7338: 
 7339:     &Debug("get_request: Request = $input\n");
 7340: 
 7341:     &status('Processing '.$clientname.':'.$input);
 7342: 
 7343:     return $input;
 7344: }
 7345: #---------------------------------------------------------------
 7346: #
 7347: #  Process a request.  This sub should shrink as each action
 7348: #  gets farmed out into a separat sub that is registered 
 7349: #  with the dispatch hash.  
 7350: #
 7351: # Parameters:
 7352: #    user_input   - The request received from the client (lonc).
 7353: #
 7354: # Returns:
 7355: #    true to keep processing, false if caller should exit.
 7356: #
 7357: sub process_request {
 7358:     my ($userinput) = @_; # Easier for now to break style than to
 7359:                           # fix all the userinput -> user_input.
 7360:     my $wasenc    = 0;		# True if request was encrypted.
 7361: # ------------------------------------------------------------ See if encrypted
 7362:     # for command
 7363:     # sethost:<server>
 7364:     # <command>:<args>
 7365:     #   we just send it to the processor
 7366:     # for
 7367:     # sethost:<server>:<command>:<args>
 7368:     #  we do the implict set host and then do the command
 7369:     if ($userinput =~ /^sethost:/) {
 7370: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
 7371: 	if (defined($userinput)) {
 7372: 	    &sethost("$cmd:$newid");
 7373: 	} else {
 7374: 	    $userinput = "$cmd:$newid";
 7375: 	}
 7376:     }
 7377: 
 7378:     if ($userinput =~ /^enc/) {
 7379: 	$userinput = decipher($userinput);
 7380: 	$wasenc=1;
 7381: 	if(!$userinput) {	# Cipher not defined.
 7382: 	    &Failure($client, "error: Encrypted data without negotated key\n");
 7383: 	    return 0;
 7384: 	}
 7385:     }
 7386:     Debug("process_request: $userinput\n");
 7387:     
 7388:     #  
 7389:     #   The 'correct way' to add a command to lond is now to
 7390:     #   write a sub to execute it and Add it to the command dispatch
 7391:     #   hash via a call to register_handler..  The comments to that
 7392:     #   sub should give you enough to go on to show how to do this
 7393:     #   along with the examples that are building up as this code
 7394:     #   is getting refactored.   Until all branches of the
 7395:     #   if/elseif monster below have been factored out into
 7396:     #   separate procesor subs, if the dispatch hash is missing
 7397:     #   the command keyword, we will fall through to the remainder
 7398:     #   of the if/else chain below in order to keep this thing in 
 7399:     #   working order throughout the transmogrification.
 7400: 
 7401:     my ($command, $tail) = split(/:/, $userinput, 2);
 7402:     chomp($command);
 7403:     chomp($tail);
 7404:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
 7405:     $command =~ s/(\r)//;	# And this too for parameterless commands.
 7406:     if(!$tail) {
 7407: 	$tail ="";		# defined but blank.
 7408:     }
 7409: 
 7410:     &Debug("Command received: $command, encoded = $wasenc");
 7411: 
 7412:     if(defined $Dispatcher{$command}) {
 7413: 
 7414: 	my $dispatch_info = $Dispatcher{$command};
 7415: 	my $handler       = $$dispatch_info[0];
 7416: 	my $need_encode   = $$dispatch_info[1];
 7417: 	my $client_types  = $$dispatch_info[2];
 7418: 	Debug("Matched dispatch hash: mustencode: $need_encode "
 7419: 	      ."ClientType $client_types");
 7420:       
 7421: 	#  Validate the request:
 7422:       
 7423: 	my $ok = 1;
 7424: 	my $requesterprivs = 0;
 7425: 	if(&isClient()) {
 7426: 	    $requesterprivs |= $CLIENT_OK;
 7427: 	}
 7428: 	if(&isManager()) {
 7429: 	    $requesterprivs |= $MANAGER_OK;
 7430: 	}
 7431: 	if($need_encode && (!$wasenc)) {
 7432: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
 7433: 	    $ok = 0;
 7434: 	}
 7435: 	if(($client_types & $requesterprivs) == 0) {
 7436: 	    Debug("Client not privileged to do this operation");
 7437: 	    $ok = 0;
 7438: 	}
 7439:         if ($ok) {
 7440:             my $realcommand = $command;
 7441:             if ($command eq 'querysend') {
 7442:                 my ($query,$rest)=split(/\:/,$tail,2);
 7443:                 $query=~s/\n*$//g;
 7444:                 my @possqueries = 
 7445:                     qw(userlog courselog fetchenrollment institutionalphotos usersearch instdirsearch getinstuser getmultinstusers);
 7446:                 if (grep(/^\Q$query\E$/,@possqueries)) {
 7447:                     $command .= '_'.$query;
 7448:                 } elsif ($query eq 'prepare activity log') {
 7449:                     $command .= '_activitylog';
 7450:                 }
 7451:             }
 7452:             if (ref($trust{$command}) eq 'HASH') {
 7453:                 my $donechecks;
 7454:                 if ($trust{$command}{'anywhere'}) {
 7455:                    $donechecks = 1;
 7456:                 } elsif ($trust{$command}{'manageronly'}) {
 7457:                     unless (&isManager()) {
 7458:                         $ok = 0;
 7459:                     }
 7460:                     $donechecks = 1;
 7461:                 } elsif ($trust{$command}{'institutiononly'}) {
 7462:                     unless ($clientsameinst) {
 7463:                         $ok = 0;
 7464:                     }
 7465:                     $donechecks = 1;
 7466:                 } elsif ($clientsameinst) {
 7467:                     $donechecks = 1;
 7468:                 }
 7469:                 unless ($donechecks) {
 7470:                     foreach my $rule (keys(%{$trust{$command}})) {
 7471:                         next if ($rule eq 'remote');
 7472:                         if ($trust{$command}{$rule}) {
 7473:                             if ($clientprohibited{$rule}) {
 7474:                                 $ok = 0;
 7475:                             } else {
 7476:                                 $ok = 1;
 7477:                                 $donechecks = 1;
 7478:                                 last;
 7479:                             }
 7480:                         }
 7481:                     }
 7482:                 }
 7483:                 unless ($donechecks) {
 7484:                     if ($trust{$command}{'remote'}) {
 7485:                         if ($clientremoteok) {
 7486:                             $ok = 1;
 7487:                         } else {
 7488:                             $ok = 0;
 7489:                         } 
 7490:                     }
 7491:                 }
 7492:             }
 7493:             $command = $realcommand;
 7494:         }
 7495: 
 7496: 	if($ok) {
 7497: 	    Debug("Dispatching to handler $command $tail");
 7498: 	    my $keep_going = &$handler($command, $tail, $client);
 7499: 	    return $keep_going;
 7500: 	} else {
 7501: 	    Debug("Refusing to dispatch because client did not match requirements");
 7502: 	    Failure($client, "refused\n", $userinput);
 7503: 	    return 1;
 7504: 	}
 7505:     }
 7506: 
 7507:     print $client "unknown_cmd\n";
 7508: # -------------------------------------------------------------------- complete
 7509:     Debug("process_request - returning 1");
 7510:     return 1;
 7511: }
 7512: #
 7513: #   Decipher encoded traffic
 7514: #  Parameters:
 7515: #     input      - Encoded data.
 7516: #  Returns:
 7517: #     Decoded data or undef if encryption key was not yet negotiated.
 7518: #  Implicit input:
 7519: #     cipher  - This global holds the negotiated encryption key.
 7520: #
 7521: sub decipher {
 7522:     my ($input)  = @_;
 7523:     my $output = '';
 7524:     
 7525:     
 7526:     if($cipher) {
 7527: 	my($enc, $enclength, $encinput) = split(/:/, $input);
 7528: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
 7529: 	    $output .= 
 7530: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
 7531: 	}
 7532: 	return substr($output, 0, $enclength);
 7533:     } else {
 7534: 	return undef;
 7535:     }
 7536: }
 7537: 
 7538: #
 7539: #   Register a command processor.  This function is invoked to register a sub
 7540: #   to process a request.  Once registered, the ProcessRequest sub can automatically
 7541: #   dispatch requests to an appropriate sub, and do the top level validity checking
 7542: #   as well:
 7543: #    - Is the keyword recognized.
 7544: #    - Is the proper client type attempting the request.
 7545: #    - Is the request encrypted if it has to be.
 7546: #   Parameters:
 7547: #    $request_name         - Name of the request being registered.
 7548: #                           This is the command request that will match
 7549: #                           against the hash keywords to lookup the information
 7550: #                           associated with the dispatch information.
 7551: #    $procedure           - Reference to a sub to call to process the request.
 7552: #                           All subs get called as follows:
 7553: #                             Procedure($cmd, $tail, $replyfd, $key)
 7554: #                             $cmd    - the actual keyword that invoked us.
 7555: #                             $tail   - the tail of the request that invoked us.
 7556: #                             $replyfd- File descriptor connected to the client
 7557: #    $must_encode          - True if the request must be encoded to be good.
 7558: #    $client_ok            - True if it's ok for a client to request this.
 7559: #    $manager_ok           - True if it's ok for a manager to request this.
 7560: # Side effects:
 7561: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
 7562: #      - On failure, the program will die as it's a bad internal bug to try to 
 7563: #        register a duplicate command handler.
 7564: #
 7565: sub register_handler {
 7566:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
 7567: 
 7568:     #  Don't allow duplication#
 7569:    
 7570:     if (defined $Dispatcher{$request_name}) {
 7571: 	die "Attempting to define a duplicate request handler for $request_name\n";
 7572:     }
 7573:     #   Build the client type mask:
 7574:     
 7575:     my $client_type_mask = 0;
 7576:     if($client_ok) {
 7577: 	$client_type_mask  |= $CLIENT_OK;
 7578:     }
 7579:     if($manager_ok) {
 7580: 	$client_type_mask  |= $MANAGER_OK;
 7581:     }
 7582:    
 7583:     #  Enter the hash:
 7584:       
 7585:     my @entry = ($procedure, $must_encode, $client_type_mask);
 7586:    
 7587:     $Dispatcher{$request_name} = \@entry;
 7588:    
 7589: }
 7590: 
 7591: 
 7592: #------------------------------------------------------------------
 7593: 
 7594: 
 7595: 
 7596: 
 7597: #
 7598: #  Convert an error return code from lcpasswd to a string value.
 7599: #
 7600: sub lcpasswdstrerror {
 7601:     my $ErrorCode = shift;
 7602:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
 7603: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
 7604:     } else {
 7605: 	return $passwderrors[$ErrorCode];
 7606:     }
 7607: }
 7608: 
 7609: # grabs exception and records it to log before exiting
 7610: sub catchexception {
 7611:     my ($error)=@_;
 7612:     $SIG{'QUIT'}='DEFAULT';
 7613:     $SIG{__DIE__}='DEFAULT';
 7614:     &status("Catching exception");
 7615:     &logthis("<font color='red'>CRITICAL: "
 7616:      ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
 7617:      ."a crash with this error msg->[$error]</font>");
 7618:     &logthis('Famous last words: '.$status.' - '.$lastlog);
 7619:     if ($client) { print $client "error: $error\n"; }
 7620:     $server->close();
 7621:     die($error);
 7622: }
 7623: sub timeout {
 7624:     &status("Handling Timeout");
 7625:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
 7626:     &catchexception('Timeout');
 7627: }
 7628: # -------------------------------- Set signal handlers to record abnormal exits
 7629: 
 7630: 
 7631: $SIG{'QUIT'}=\&catchexception;
 7632: $SIG{__DIE__}=\&catchexception;
 7633: 
 7634: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
 7635: &status("Read loncapa.conf and loncapa_apache.conf");
 7636: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
 7637: %perlvar=%{$perlvarref};
 7638: undef $perlvarref;
 7639: 
 7640: # ----------------------------- Make sure this process is running from user=www
 7641: my $wwwid=getpwnam('www');
 7642: if ($wwwid!=$<) {
 7643:    my $emailto="$perlvar{'lonAdmEMail'} $perlvar{'lonSysEMail'}";
 7644:    my $subj="LON: $currenthostid User ID mismatch";
 7645:    system("echo 'User ID mismatch.  lond must be run as user www.' |".
 7646:           " mail -s '$subj' $emailto > /dev/null");
 7647:    exit 1;
 7648: }
 7649: 
 7650: # --------------------------------------------- Check if other instance running
 7651: 
 7652: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
 7653: 
 7654: if (-e $pidfile) {
 7655:    my $lfh=IO::File->new("$pidfile");
 7656:    my $pide=<$lfh>;
 7657:    chomp($pide);
 7658:    if (kill 0 => $pide) { die "already running"; }
 7659: }
 7660: 
 7661: # ------------------------------------------------------------- Read hosts file
 7662: 
 7663: 
 7664: 
 7665: # establish SERVER socket, bind and listen.
 7666: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
 7667:                                 Type      => SOCK_STREAM,
 7668:                                 Proto     => 'tcp',
 7669:                                 ReuseAddr     => 1,
 7670:                                 Listen    => 10 )
 7671:   or die "making socket: $@\n";
 7672: 
 7673: # --------------------------------------------------------- Do global variables
 7674: 
 7675: # global variables
 7676: 
 7677: my %children               = ();       # keys are current child process IDs
 7678: 
 7679: sub REAPER {                        # takes care of dead children
 7680:     $SIG{CHLD} = \&REAPER;
 7681:     &status("Handling child death");
 7682:     my $pid;
 7683:     do {
 7684: 	$pid = waitpid(-1,&WNOHANG());
 7685: 	if (defined($children{$pid})) {
 7686: 	    &logthis("Child $pid died");
 7687: 	    delete($children{$pid});
 7688: 	} elsif ($pid > 0) {
 7689: 	    &logthis("Unknown Child $pid died");
 7690: 	}
 7691:     } while ( $pid > 0 );
 7692:     foreach my $child (keys(%children)) {
 7693: 	$pid = waitpid($child,&WNOHANG());
 7694: 	if ($pid > 0) {
 7695: 	    &logthis("Child $child - $pid looks like we missed it's death");
 7696: 	    delete($children{$pid});
 7697: 	}
 7698:     }
 7699:     &status("Finished Handling child death");
 7700: }
 7701: 
 7702: sub HUNTSMAN {                      # signal handler for SIGINT
 7703:     &status("Killing children (INT)");
 7704:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
 7705:     kill 'INT' => keys %children;
 7706:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
 7707:     my $execdir=$perlvar{'lonDaemons'};
 7708:     unlink("$execdir/logs/lond.pid");
 7709:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
 7710:     &status("Done killing children");
 7711:     exit;                           # clean up with dignity
 7712: }
 7713: 
 7714: sub HUPSMAN {                      # signal handler for SIGHUP
 7715:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
 7716:     &status("Killing children for restart (HUP)");
 7717:     kill 'INT' => keys %children;
 7718:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
 7719:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
 7720:     my $execdir=$perlvar{'lonDaemons'};
 7721:     unlink("$execdir/logs/lond.pid");
 7722:     &status("Restarting self (HUP)");
 7723:     exec("$execdir/lond");         # here we go again
 7724: }
 7725: 
 7726: #
 7727: #  Reload the Apache daemon's state.
 7728: #  This is done by invoking /home/httpd/perl/apachereload
 7729: #  a setuid perl script that can be root for us to do this job.
 7730: #
 7731: sub ReloadApache {
 7732: # --------------------------- Handle case of another apachereload process (locking)
 7733:     if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
 7734:         my $execdir = $perlvar{'lonDaemons'};
 7735:         my $script  = $execdir."/apachereload";
 7736:         system($script);
 7737:         unlink('/tmp/lock_apachereload'); #  Remove the lock file.
 7738:     }
 7739: }
 7740: 
 7741: #
 7742: #   Called in response to a USR2 signal.
 7743: #   - Reread hosts.tab
 7744: #   - All children connected to hosts that were removed from hosts.tab
 7745: #     are killed via SIGINT
 7746: #   - All children connected to previously existing hosts are sent SIGUSR1
 7747: #   - Our internal hosts hash is updated to reflect the new contents of
 7748: #     hosts.tab causing connections from hosts added to hosts.tab to
 7749: #     now be honored.
 7750: #
 7751: sub UpdateHosts {
 7752:     &status("Reload hosts.tab");
 7753:     logthis('<font color="blue"> Updating connections </font>');
 7754:     #
 7755:     #  The %children hash has the set of IP's we currently have children
 7756:     #  on.  These need to be matched against records in the hosts.tab
 7757:     #  Any ip's no longer in the table get killed off they correspond to
 7758:     #  either dropped or changed hosts.  Note that the re-read of the table
 7759:     #  will take care of new and changed hosts as connections come into being.
 7760: 
 7761:     &Apache::lonnet::reset_hosts_info();
 7762:     my %active;
 7763: 
 7764:     foreach my $child (keys(%children)) {
 7765: 	my $childip = $children{$child};
 7766: 	if ($childip ne '127.0.0.1'
 7767: 	    && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
 7768: 	    logthis('<font color="blue"> UpdateHosts killing child '
 7769: 		    ." $child for ip $childip </font>");
 7770: 	    kill('INT', $child);
 7771: 	} else {
 7772:             $active{$child} = $childip;
 7773: 	    logthis('<font color="green"> keeping child for ip '
 7774: 		    ." $childip (pid=$child) </font>");
 7775: 	}
 7776:     }
 7777: 
 7778:     my %oldconf = %secureconf;
 7779:     my %connchange;
 7780:     if (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
 7781:         logthis('<font color="blue"> Reloaded SSL connection rules and cleared CRL checking history </font>');
 7782:     } else {
 7783:         logthis('<font color="yellow"> Failed to reload SSL connection rules and clear CRL checking history </font>');
 7784:     }
 7785:     if ((ref($oldconf{'connfrom'}) eq 'HASH') && (ref($secureconf{'connfrom'}) eq 'HASH')) {
 7786:         foreach my $type ('dom','intdom','other') {
 7787:             if ((($oldconf{'connfrom'}{$type} eq 'no') && ($secureconf{'connfrom'}{$type} eq 'req')) ||
 7788:                 (($oldconf{'connfrom'}{$type} eq 'req') && ($secureconf{'connfrom'}{$type} eq 'no'))) {
 7789:                 $connchange{$type} = 1;
 7790:             }
 7791:         }
 7792:     }
 7793:     if (keys(%connchange)) {
 7794:         foreach my $child (keys(%active)) {
 7795:             my $childip = $active{$child};
 7796:             if ($childip ne '127.0.0.1') {
 7797:                 my $childhostname  = gethostbyaddr(Socket::inet_aton($childip),AF_INET);
 7798:                 if ($childhostname ne '') {
 7799:                     my $childlonhost = &Apache::lonnet::get_server_homeID($childhostname);
 7800:                     my ($samedom,$sameinst) = &set_client_info($childlonhost);
 7801:                     if ($samedom) {
 7802:                         if ($connchange{'dom'}) {
 7803:                             logthis('<font color="blue"> UpdateHosts killing child '
 7804:                                    ." $child for ip $childip </font>");
 7805:                             kill('INT', $child);
 7806:                         }
 7807:                     } elsif ($sameinst) {
 7808:                         if ($connchange{'intdom'}) {
 7809:                             logthis('<font color="blue"> UpdateHosts killing child '
 7810:                                    ." $child for ip $childip </font>");
 7811:                            kill('INT', $child);
 7812:                         }
 7813:                     } else {
 7814:                         if ($connchange{'other'}) {
 7815:                             logthis('<font color="blue"> UpdateHosts killing child '
 7816:                                    ." $child for ip $childip </font>");
 7817:                             kill('INT', $child);
 7818:                         }
 7819:                     }
 7820:                 }
 7821:             }
 7822:         }
 7823:     }
 7824:     ReloadApache;
 7825:     &status("Finished reloading hosts.tab");
 7826: }
 7827: 
 7828: sub checkchildren {
 7829:     &status("Checking on the children (sending signals)");
 7830:     &initnewstatus();
 7831:     &logstatus();
 7832:     &logthis('Going to check on the children');
 7833:     my $docdir=$perlvar{'lonDocRoot'};
 7834:     foreach (sort keys %children) {
 7835: 	#sleep 1;
 7836:         unless (kill 'USR1' => $_) {
 7837: 	    &logthis ('Child '.$_.' is dead');
 7838:             &logstatus($$.' is dead');
 7839: 	    delete($children{$_});
 7840:         } 
 7841:     }
 7842:     sleep 5;
 7843:     $SIG{ALRM} = sub { Debug("timeout"); 
 7844: 		       die "timeout";  };
 7845:     $SIG{__DIE__} = 'DEFAULT';
 7846:     &status("Checking on the children (waiting for reports)");
 7847:     foreach (sort keys %children) {
 7848:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
 7849:           eval {
 7850:             alarm(300);
 7851: 	    &logthis('Child '.$_.' did not respond');
 7852: 	    kill 9 => $_;
 7853: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
 7854: 	    #$subj="LON: $currenthostid killed lond process $_";
 7855: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
 7856: 	    #$execdir=$perlvar{'lonDaemons'};
 7857: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
 7858: 	    delete($children{$_});
 7859: 	    alarm(0);
 7860: 	  }
 7861:         }
 7862:     }
 7863:     $SIG{ALRM} = 'DEFAULT';
 7864:     $SIG{__DIE__} = \&catchexception;
 7865:     &status("Finished checking children");
 7866:     &logthis('Finished Checking children');
 7867: }
 7868: 
 7869: # --------------------------------------------------------------------- Logging
 7870: 
 7871: sub logthis {
 7872:     my $message=shift;
 7873:     my $execdir=$perlvar{'lonDaemons'};
 7874:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
 7875:     my $now=time;
 7876:     my $local=localtime($now);
 7877:     $lastlog=$local.': '.$message;
 7878:     print $fh "$local ($$): $message\n";
 7879: }
 7880: 
 7881: # ------------------------- Conditional log if $DEBUG true.
 7882: sub Debug {
 7883:     my $message = shift;
 7884:     if($DEBUG) {
 7885: 	&logthis($message);
 7886:     }
 7887: }
 7888: 
 7889: #
 7890: #   Sub to do replies to client.. this gives a hook for some
 7891: #   debug tracing too:
 7892: #  Parameters:
 7893: #     fd      - File open on client.
 7894: #     reply   - Text to send to client.
 7895: #     request - Original request from client.
 7896: #
 7897: #NOTE $reply must be terminated by exactly *one* \n. If $reply is a reference
 7898: #this is done automatically ($$reply must not contain any \n in this case). 
 7899: #If $reply is a string the caller has to ensure this.
 7900: sub Reply {
 7901:     my ($fd, $reply, $request) = @_;
 7902:     if (ref($reply)) {
 7903: 	print $fd $$reply;
 7904: 	print $fd "\n";
 7905: 	if ($DEBUG) { Debug("Request was $request  Reply was $$reply"); }
 7906:     } else {
 7907: 	print $fd $reply;
 7908: 	if ($DEBUG) { Debug("Request was $request  Reply was $reply"); }
 7909:     }
 7910:     $Transactions++;
 7911: }
 7912: 
 7913: 
 7914: #
 7915: #    Sub to report a failure.
 7916: #    This function:
 7917: #     -   Increments the failure statistic counters.
 7918: #     -   Invokes Reply to send the error message to the client.
 7919: # Parameters:
 7920: #    fd       - File descriptor open on the client
 7921: #    reply    - Reply text to emit.
 7922: #    request  - The original request message (used by Reply
 7923: #               to debug if that's enabled.
 7924: # Implicit outputs:
 7925: #    $Failures- The number of failures is incremented.
 7926: #    Reply (invoked here) sends a message to the 
 7927: #    client:
 7928: #
 7929: sub Failure {
 7930:     my $fd      = shift;
 7931:     my $reply   = shift;
 7932:     my $request = shift;
 7933:    
 7934:     $Failures++;
 7935:     Reply($fd, $reply, $request);      # That's simple eh?
 7936: }
 7937: # ------------------------------------------------------------------ Log status
 7938: 
 7939: sub logstatus {
 7940:     &status("Doing logging");
 7941:     my $docdir=$perlvar{'lonDocRoot'};
 7942:     {
 7943: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
 7944:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
 7945:         $fh->close();
 7946:     }
 7947:     &status("Finished $$.txt");
 7948:     {
 7949: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
 7950: 	flock(LOG,LOCK_EX);
 7951: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
 7952: 	    .$status."\t".$lastlog."\t $keymode\n";
 7953: 	flock(LOG,LOCK_UN);
 7954: 	close(LOG);
 7955:     }
 7956:     &status("Finished logging");
 7957: }
 7958: 
 7959: sub initnewstatus {
 7960:     my $docdir=$perlvar{'lonDocRoot'};
 7961:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
 7962:     my $now=time();
 7963:     my $local=localtime($now);
 7964:     print $fh "LOND status $local - parent $$\n\n";
 7965:     opendir(DIR,"$docdir/lon-status/londchld");
 7966:     while (my $filename=readdir(DIR)) {
 7967:         unlink("$docdir/lon-status/londchld/$filename");
 7968:     }
 7969:     closedir(DIR);
 7970: }
 7971: 
 7972: # -------------------------------------------------------------- Status setting
 7973: 
 7974: sub status {
 7975:     my $what=shift;
 7976:     my $now=time;
 7977:     my $local=localtime($now);
 7978:     $status=$local.': '.$what;
 7979:     $0='lond: '.$what.' '.$local;
 7980: }
 7981: 
 7982: # -------------------------------------------------------------- Talk to lonsql
 7983: 
 7984: sub sql_reply {
 7985:     my ($cmd)=@_;
 7986:     my $answer=&sub_sql_reply($cmd);
 7987:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
 7988:     return $answer;
 7989: }
 7990: 
 7991: sub sub_sql_reply {
 7992:     my ($cmd)=@_;
 7993:     my $unixsock="mysqlsock";
 7994:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
 7995:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
 7996:                                       Type    => SOCK_STREAM,
 7997:                                       Timeout => 10)
 7998:        or return "con_lost";
 7999:     print $sclient "$cmd:$currentdomainid\n";
 8000:     my $answer=<$sclient>;
 8001:     chomp($answer);
 8002:     if (!$answer) { $answer="con_lost"; }
 8003:     return $answer;
 8004: }
 8005: 
 8006: # --------------------------------------- Is this the home server of an author?
 8007: 
 8008: sub ishome {
 8009:     my $author=shift;
 8010:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 8011:     my ($udom,$uname)=split(/\//,$author);
 8012:     my $proname=propath($udom,$uname);
 8013:     if (-e $proname) {
 8014: 	return 'owner';
 8015:     } else {
 8016:         return 'not_owner';
 8017:     }
 8018: }
 8019: 
 8020: # ======================================================= Continue main program
 8021: # ---------------------------------------------------- Fork once and dissociate
 8022: 
 8023: my $fpid=fork;
 8024: exit if $fpid;
 8025: die "Couldn't fork: $!" unless defined ($fpid);
 8026: 
 8027: POSIX::setsid() or die "Can't start new session: $!";
 8028: 
 8029: # ------------------------------------------------------- Write our PID on disk
 8030: 
 8031: my $execdir=$perlvar{'lonDaemons'};
 8032: open (PIDSAVE,">$execdir/logs/lond.pid");
 8033: print PIDSAVE "$$\n";
 8034: close(PIDSAVE);
 8035: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
 8036: &status('Starting');
 8037: 
 8038: 
 8039: 
 8040: # ----------------------------------------------------- Install signal handlers
 8041: 
 8042: 
 8043: $SIG{CHLD} = \&REAPER;
 8044: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 8045: $SIG{HUP}  = \&HUPSMAN;
 8046: $SIG{USR1} = \&checkchildren;
 8047: $SIG{USR2} = \&UpdateHosts;
 8048: 
 8049: #  Read the host hashes:
 8050: &Apache::lonnet::load_hosts_tab();
 8051: my %iphost = &Apache::lonnet::get_iphost(1);
 8052: 
 8053: $dist=`$perlvar{'lonDaemons'}/distprobe`;
 8054: 
 8055: my $arch = `uname -i`;
 8056: chomp($arch);
 8057: if ($arch eq 'unknown') {
 8058:     $arch = `uname -m`;
 8059:     chomp($arch);
 8060: }
 8061: 
 8062: unless (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
 8063:     &logthis('<font color="blue">No connectionrules table. Will fallback to loncapa.conf</font>');
 8064: }
 8065: 
 8066: # --------------------------------------------------------------
 8067: #   Accept connections.  When a connection comes in, it is validated
 8068: #   and if good, a child process is created to process transactions
 8069: #   along the connection.
 8070: 
 8071: while (1) {
 8072:     &status('Starting accept');
 8073:     $client = $server->accept() or next;
 8074:     &status('Accepted '.$client.' off to spawn');
 8075:     make_new_child($client);
 8076:     &status('Finished spawning');
 8077: }
 8078: 
 8079: sub make_new_child {
 8080:     my $pid;
 8081: #    my $cipher;     # Now global
 8082:     my $sigset;
 8083: 
 8084:     $client = shift;
 8085:     &status('Starting new child '.$client);
 8086:     &logthis('<font color="green"> Attempting to start child ('.$client.
 8087: 	     ")</font>");    
 8088:     # block signal for fork
 8089:     $sigset = POSIX::SigSet->new(SIGINT);
 8090:     sigprocmask(SIG_BLOCK, $sigset)
 8091:         or die "Can't block SIGINT for fork: $!\n";
 8092: 
 8093:     die "fork: $!" unless defined ($pid = fork);
 8094: 
 8095:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
 8096: 	                               # connection liveness.
 8097: 
 8098:     #
 8099:     #  Figure out who we're talking to so we can record the peer in 
 8100:     #  the pid hash.
 8101:     #
 8102:     my $caller = getpeername($client);
 8103:     my ($port,$iaddr);
 8104:     if (defined($caller) && length($caller) > 0) {
 8105: 	($port,$iaddr)=unpack_sockaddr_in($caller);
 8106:     } else {
 8107: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
 8108:     }
 8109:     if (defined($iaddr)) {
 8110: 	$clientip  = inet_ntoa($iaddr);
 8111: 	Debug("Connected with $clientip");
 8112:     } else {
 8113: 	&logthis("Unable to determine clientip");
 8114: 	$clientip='Unavailable';
 8115:     }
 8116:     
 8117:     if ($pid) {
 8118:         # Parent records the child's birth and returns.
 8119:         sigprocmask(SIG_UNBLOCK, $sigset)
 8120:             or die "Can't unblock SIGINT for fork: $!\n";
 8121:         $children{$pid} = $clientip;
 8122:         &status('Started child '.$pid);
 8123: 	close($client);
 8124:         return;
 8125:     } else {
 8126:         # Child can *not* return from this subroutine.
 8127:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
 8128:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
 8129:                                 #don't get intercepted
 8130:         $SIG{USR1}= \&logstatus;
 8131:         $SIG{ALRM}= \&timeout;
 8132: 	#
 8133: 	# Block sigpipe as it gets thrownon socket disconnect and we want to 
 8134: 	# deal with that as a read faiure instead.
 8135: 	#
 8136: 	my $blockset = POSIX::SigSet->new(SIGPIPE);
 8137: 	sigprocmask(SIG_BLOCK, $blockset);
 8138: 
 8139:         $lastlog='Forked ';
 8140:         $status='Forked';
 8141: 
 8142:         # unblock signals
 8143:         sigprocmask(SIG_UNBLOCK, $sigset)
 8144:             or die "Can't unblock SIGINT for fork: $!\n";
 8145: 
 8146: #        my $tmpsnum=0;            # Now global
 8147: #---------------------------------------------------- kerberos 5 initialization
 8148:         &Authen::Krb5::init_context();
 8149: 
 8150:         my $no_ets;
 8151:         if ($dist =~ /^(?:centos|rhes|scientific|oracle|rocky|alma)(\d+)/) {
 8152:             if ($1 >= 7) {
 8153:                 $no_ets = 1;
 8154:             }
 8155:         } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
 8156:             if (($1 eq '9.3') || ($1 >= 12.2)) {
 8157:                 $no_ets = 1; 
 8158:             }
 8159:         } elsif ($dist =~ /^sles(\d+)$/) {
 8160:             if ($1 > 11) {
 8161:                 $no_ets = 1;
 8162:             }
 8163:         } elsif ($dist =~ /^fedora(\d+)$/) {
 8164:             if ($1 < 7) {
 8165:                 $no_ets = 1;
 8166:             }
 8167:         }
 8168:         unless ($no_ets) {
 8169: 	    &Authen::Krb5::init_ets();
 8170: 	}
 8171: 
 8172: 	&status('Accepted connection');
 8173: # =============================================================================
 8174:             # do something with the connection
 8175: # -----------------------------------------------------------------------------
 8176: 	# see if we know client and 'check' for spoof IP by ineffective challenge
 8177: 
 8178: 	my $outsideip=$clientip;
 8179: 	if ($clientip eq '127.0.0.1') {
 8180: 	    $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
 8181: 	}
 8182: 	&ReadManagerTable();
 8183: 	my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
 8184: 	my $ismanager=($managers{$outsideip}    ne undef);
 8185: 	$clientname  = "[unknown]";
 8186: 	if($clientrec) {	# Establish client type.
 8187: 	    $ConnectionType = "client";
 8188: 	    $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
 8189: 	    if($ismanager) {
 8190: 		$ConnectionType = "both";
 8191: 	    }
 8192: 	} else {
 8193: 	    $ConnectionType = "manager";
 8194: 	    $clientname = $managers{$outsideip};
 8195: 	}
 8196: 	my $clientok;
 8197: 
 8198: 	if ($clientrec || $ismanager) {
 8199: 	    &status("Waiting for init from $clientip $clientname");
 8200: 	    &logthis('<font color="yellow">INFO: Connection, '.
 8201: 		     $clientip.
 8202: 		  " ($clientname) connection type = $ConnectionType </font>" );
 8203: 	    &status("Connecting $clientip  ($clientname))"); 
 8204: 	    my $remotereq=<$client>;
 8205: 	    chomp($remotereq);
 8206: 	    Debug("Got init: $remotereq");
 8207: 
 8208: 	    if ($remotereq =~ /^init/) {
 8209: 		&sethost("sethost:$perlvar{'lonHostID'}");
 8210: 		#
 8211: 		#  If the remote is attempting a local init... give that a try:
 8212: 		#
 8213: 		(my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
 8214:         # For LON-CAPA 2.9, the  client session will have sent its LON-CAPA
 8215:         # version when initiating the connection. For LON-CAPA 2.8 and older,
 8216:         # the version is retrieved from the global %loncaparevs in lonnet.pm.            
 8217:         # $clientversion contains path to keyfile if $inittype eq 'local'
 8218:         # it's overridden below in this case
 8219:         $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
 8220: 
 8221: 		# If the connection type is ssl, but I didn't get my
 8222: 		# certificate files yet, then I'll drop  back to 
 8223: 		# insecure (if allowed).
 8224: 
 8225:                 if ($inittype eq "ssl") {
 8226:                     my $context;
 8227:                     if ($clientsamedom) {
 8228:                         $context = 'dom';
 8229:                         if ($secureconf{'connfrom'}{'dom'} eq 'no') {
 8230:                             $inittype = "";
 8231:                         }
 8232:                     } elsif ($clientsameinst) {
 8233:                         $context = 'intdom';
 8234:                         if ($secureconf{'connfrom'}{'intdom'} eq 'no') {
 8235:                             $inittype = "";
 8236:                         }
 8237:                     } else {
 8238:                         $context = 'other';
 8239:                         if ($secureconf{'connfrom'}{'other'} eq 'no') {
 8240:                             $inittype = "";
 8241:                         }
 8242:                     }
 8243:                     if ($inittype eq '') {
 8244:                         &logthis("<font color=\"blue\"> Domain config set "
 8245:                                 ."to no ssl for $clientname (context: $context)"
 8246:                                 ." -- trying insecure auth</font>");
 8247:                     }
 8248:                 }
 8249: 
 8250: 		if($inittype eq "ssl") {
 8251: 		    my ($ca, $cert) = lonssl::CertificateFile;
 8252: 		    my $kfile       = lonssl::KeyFile;
 8253: 		    if((!$ca)   || 
 8254: 		       (!$cert) || 
 8255: 		       (!$kfile)) {
 8256: 			$inittype = ""; # This forces insecure attempt.
 8257: 			&logthis("<font color=\"blue\"> Certificates not "
 8258: 				 ."installed -- trying insecure auth</font>");
 8259: 		    } else {	# SSL certificates are in place so
 8260: 		    }		# Leave the inittype alone.
 8261: 		}
 8262: 
 8263: 		if($inittype eq "local") {
 8264:                     $clientversion = $perlvar{'lonVersion'};
 8265: 		    my $key = LocalConnection($client, $remotereq);
 8266: 		    if($key) {
 8267: 			Debug("Got local key $key");
 8268: 			$clientok     = 1;
 8269: 			my $cipherkey = pack("H32", $key);
 8270: 			$cipher       = new IDEA($cipherkey);
 8271: 			print $client "ok:local\n";
 8272: 			&logthis('<font color="green">'
 8273: 				 . "Successful local authentication </font>");
 8274: 			$keymode = "local"
 8275: 		    } else {
 8276: 			Debug("Failed to get local key");
 8277: 			$clientok = 0;
 8278: 			shutdown($client, 3);
 8279: 			close $client;
 8280: 		    }
 8281: 		} elsif ($inittype eq "ssl") {
 8282: 		    my $key = SSLConnection($client,$clientname);
 8283: 		    if ($key) {
 8284: 			$clientok = 1;
 8285: 			my $cipherkey = pack("H32", $key);
 8286: 			$cipher       = new IDEA($cipherkey);
 8287: 			&logthis('<font color="green">'
 8288: 				 ."Successfull ssl authentication with $clientname </font>");
 8289: 			$keymode = "ssl";
 8290: 	     
 8291: 		    } else {
 8292: 			$clientok = 0;
 8293: 			close $client;
 8294: 		    }
 8295: 	   
 8296: 		} else {
 8297: 		    my $ok = InsecureConnection($client);
 8298: 		    if($ok) {
 8299: 			$clientok = 1;
 8300: 			&logthis('<font color="green">'
 8301: 				 ."Successful insecure authentication with $clientname </font>");
 8302: 			print $client "ok\n";
 8303: 			$keymode = "insecure";
 8304: 		    } else {
 8305: 			&logthis('<font color="yellow">'
 8306: 				  ."Attempted insecure connection disallowed </font>");
 8307: 			close $client;
 8308: 			$clientok = 0;
 8309: 		    }
 8310: 		}
 8311: 	    } else {
 8312: 		&logthis(
 8313: 			 "<font color='blue'>WARNING: "
 8314: 			 ."$clientip failed to initialize: >$remotereq< </font>");
 8315: 		&status('No init '.$clientip);
 8316: 	    }
 8317: 	} else {
 8318: 	    &logthis(
 8319: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
 8320: 	    &status('Hung up on '.$clientip);
 8321: 	}
 8322:  
 8323: 	if ($clientok) {
 8324: # ---------------- New known client connecting, could mean machine online again
 8325: 	    if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip 
 8326: 		&& $clientip ne '127.0.0.1') {
 8327: 		&Apache::lonnet::reconlonc($clientname);
 8328: 	    }
 8329: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
 8330: 	    &status('Will listen to '.$clientname);
 8331: # ------------------------------------------------------------ Process requests
 8332: 	    my $keep_going = 1;
 8333: 	    my $user_input;
 8334: 
 8335: 	    while(($user_input = get_request) && $keep_going) {
 8336: 		alarm(120);
 8337: 		Debug("Main: Got $user_input\n");
 8338: 		$keep_going = &process_request($user_input);
 8339: 		alarm(0);
 8340: 		&status('Listening to '.$clientname." ($keymode)");
 8341: 	    }
 8342: 
 8343: # --------------------------------------------- client unknown or fishy, refuse
 8344: 	}  else {
 8345: 	    print $client "refused\n";
 8346: 	    $client->close();
 8347: 	    &logthis("<font color='blue'>WARNING: "
 8348: 		     ."Rejected client $clientip, closing connection</font>");
 8349: 	}
 8350:     }
 8351:     
 8352: # =============================================================================
 8353:     
 8354:     &logthis("<font color='red'>CRITICAL: "
 8355: 	     ."Disconnect from $clientip ($clientname)</font>");    
 8356: 
 8357: 
 8358:     # this exit is VERY important, otherwise the child will become
 8359:     # a producer of more and more children, forking yourself into
 8360:     # process death.
 8361:     exit;
 8362:     
 8363: }
 8364: 
 8365: #
 8366: #  Used to determine if a particular client is from the same domain
 8367: #  as the current server, or from the same internet domain, and
 8368: #  also if the client can host sessions for the domain's users.
 8369: #  A hash is populated with keys set to commands sent by the client
 8370: #  which may not be executed for this domain.
 8371: #
 8372: #  Optional input -- the client to check for domain and internet domain.
 8373: #  If not specified, defaults to the package variable: $clientname
 8374: #
 8375: #  If called in array context will not set package variables, but will
 8376: #  instead return an array of two values - (a) true if client is in the
 8377: #  same domain as the server, and (b) true if client is in the same 
 8378: #  internet domain.
 8379: #
 8380: #  If called in scalar context, sets package variables for current client:
 8381: #
 8382: #  $clienthomedom    - LonCAPA domain of homeID for client.
 8383: #  $clientsamedom    - LonCAPA domain same for this host and client.
 8384: #  $clientintdom     - LonCAPA "internet domain" for client.
 8385: #  $clientsameinst   - LonCAPA "internet domain" same for this host & client.
 8386: #  $clientremoteok   - If current domain permits hosting on this client: 1
 8387: #  %clientprohibited - Commands prohibited for domain's users for this client.
 8388: #
 8389: #  if the host and client have the same "internet domain", then the value
 8390: #  of $clientremoteok is not used, and no commands are prohibited.
 8391: #
 8392: #  returns 1 to indicate package variables have been set for current client.
 8393: #
 8394: 
 8395: sub set_client_info {
 8396:     my ($lonhost) = @_;
 8397:     $lonhost ||= $clientname;
 8398:     my $clienthost = &Apache::lonnet::hostname($lonhost);
 8399:     my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
 8400:     my $homedom = &Apache::lonnet::host_domain($clientserverhomeID);
 8401:     my $samedom = 0;
 8402:     if ($perlvar{'lonDefDomain'} eq $homedom) {
 8403:         $samedom = 1;
 8404:     }
 8405:     my $intdom = &Apache::lonnet::internet_dom($clientserverhomeID);
 8406:     my $sameinst = 0;
 8407:     if ($intdom ne '') {
 8408:         my $internet_names = &Apache::lonnet::get_internet_names($currenthostid);
 8409:         if (ref($internet_names) eq 'ARRAY') {
 8410:             if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 8411:                 $sameinst = 1;
 8412:             }
 8413:         }
 8414:     }
 8415:     if (wantarray) {
 8416:         return ($samedom,$sameinst);
 8417:     } else {
 8418:         $clienthomedom = $homedom;
 8419:         $clientsamedom = $samedom;
 8420:         $clientintdom = $intdom;
 8421:         $clientsameinst = $sameinst;
 8422:         if ($clientsameinst) {
 8423:             undef($clientremoteok);
 8424:             undef(%clientprohibited);
 8425:         } else {
 8426:             $clientremoteok = &get_remote_hostable($currentdomainid);
 8427:             %clientprohibited = &get_prohibited($currentdomainid);
 8428:         }
 8429:         return 1;
 8430:     }
 8431: }
 8432: 
 8433: #
 8434: #   Determine if a user is an author for the indicated domain.
 8435: #
 8436: # Parameters:
 8437: #    domain          - domain to check in .
 8438: #    user            - Name of user to check.
 8439: #
 8440: # Return:
 8441: #     1             - User is an author for domain.
 8442: #     0             - User is not an author for domain.
 8443: sub is_author {
 8444:     my ($domain, $user) = @_;
 8445: 
 8446:     &Debug("is_author: $user @ $domain");
 8447: 
 8448:     my $hashref = &tie_user_hash($domain, $user, "roles",
 8449: 				 &GDBM_READER());
 8450: 
 8451:     #  Author role should show up as a key /domain/_au
 8452: 
 8453:     my $value;
 8454:     if ($hashref) {
 8455: 
 8456: 	my $key    = "/$domain/_au";
 8457: 	if (defined($hashref)) {
 8458: 	    $value = $hashref->{$key};
 8459: 	    if(!untie_user_hash($hashref)) {
 8460: 		return 'error: ' .  ($!+0)." untie (GDBM) Failed";
 8461: 	    }
 8462: 	}
 8463: 	
 8464: 	if(defined($value)) {
 8465: 	    &Debug("$user @ $domain is an author");
 8466: 	}
 8467:     } else {
 8468: 	return 'error: '.($!+0)." tie (GDBM) Failed";
 8469:     }
 8470: 
 8471:     return defined($value);
 8472: }
 8473: #
 8474: #   Checks to see if the input roleput request was to set
 8475: # an author role.  If so, creates construction space 
 8476: # Parameters:
 8477: #    request   - The request sent to the rolesput subchunk.
 8478: #                We're looking for  /domain/_au
 8479: #    domain    - The domain in which the user is having roles doctored.
 8480: #    user      - Name of the user for which the role is being put.
 8481: #    authtype  - The authentication type associated with the user.
 8482: #
 8483: sub manage_permissions {
 8484:     my ($request, $domain, $user, $authtype) = @_;
 8485:     # See if the request is of the form /$domain/_au
 8486:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
 8487:         my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
 8488:         unless (-e $path) {        
 8489:            mkdir($path);
 8490:         }
 8491:         unless (-e $path.'/'.$user) {
 8492:            mkdir($path.'/'.$user);
 8493:         }
 8494:     }
 8495: }
 8496: 
 8497: 
 8498: #
 8499: #  Return the full path of a user password file, whether it exists or not.
 8500: # Parameters:
 8501: #   domain     - Domain in which the password file lives.
 8502: #   user       - name of the user.
 8503: # Returns:
 8504: #    Full passwd path:
 8505: #
 8506: sub password_path {
 8507:     my ($domain, $user) = @_;
 8508:     return &propath($domain, $user).'/passwd';
 8509: }
 8510: 
 8511: #   Password Filename
 8512: #   Returns the path to a passwd file given domain and user... only if
 8513: #  it exists.
 8514: # Parameters:
 8515: #   domain    - Domain in which to search.
 8516: #   user      - username.
 8517: # Returns:
 8518: #   - If the password file exists returns its path.
 8519: #   - If the password file does not exist, returns undefined.
 8520: #
 8521: sub password_filename {
 8522:     my ($domain, $user) = @_;
 8523: 
 8524:     Debug ("PasswordFilename called: dom = $domain user = $user");
 8525: 
 8526:     my $path  = &password_path($domain, $user);
 8527:     Debug("PasswordFilename got path: $path");
 8528:     if(-e $path) {
 8529: 	return $path;
 8530:     } else {
 8531: 	return undef;
 8532:     }
 8533: }
 8534: 
 8535: #
 8536: #   Rewrite the contents of the user's passwd file.
 8537: #  Parameters:
 8538: #    domain    - domain of the user.
 8539: #    name      - User's name.
 8540: #    contents  - New contents of the file.
 8541: #    saveold   - (optional). If true save old file in a passwd.bak file.
 8542: # Returns:
 8543: #   0    - Failed.
 8544: #   1    - Success.
 8545: #
 8546: sub rewrite_password_file {
 8547:     my ($domain, $user, $contents, $saveold) = @_;
 8548: 
 8549:     my $file = &password_filename($domain, $user);
 8550:     if (defined $file) {
 8551:         if ($saveold) {
 8552:             my $bakfile = $file.'.bak';
 8553:             if (CopyFile($file,$bakfile)) {
 8554:                 chmod(0400,$bakfile);
 8555:                 &logthis("Old password saved in passwd.bak for internally authenticated user: $user:$domain");
 8556:             } else {
 8557:                 &logthis("Failed to save old password in passwd.bak for internally authenticated user: $user:$domain");
 8558:             }
 8559:         }
 8560: 	my $pf = IO::File->new(">$file");
 8561: 	if($pf) {
 8562: 	    print $pf "$contents\n";
 8563: 	    return 1;
 8564: 	} else {
 8565: 	    return 0;
 8566: 	}
 8567:     } else {
 8568: 	return 0;
 8569:     }
 8570: 
 8571: }
 8572: 
 8573: #
 8574: #   get_auth_type - Determines the authorization type of a user in a domain.
 8575: 
 8576: #     Returns the authorization type or nouser if there is no such user.
 8577: #
 8578: sub get_auth_type {
 8579:     my ($domain, $user)  = @_;
 8580: 
 8581:     Debug("get_auth_type( $domain, $user ) \n");
 8582:     my $proname    = &propath($domain, $user); 
 8583:     my $passwdfile = "$proname/passwd";
 8584:     if( -e $passwdfile ) {
 8585: 	my $pf = IO::File->new($passwdfile);
 8586: 	my $realpassword = <$pf>;
 8587: 	chomp($realpassword);
 8588: 	Debug("Password info = $realpassword\n");
 8589: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
 8590: 	Debug("Authtype = $authtype, content = $contentpwd\n");
 8591: 	return "$authtype:$contentpwd";     
 8592:     } else {
 8593: 	Debug("Returning nouser");
 8594: 	return "nouser";
 8595:     }
 8596: }
 8597: 
 8598: #
 8599: #  Validate a user given their domain, name and password.  This utility
 8600: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
 8601: #  to validate the login credentials of a user.
 8602: # Parameters:
 8603: #    $domain    - The domain being logged into (this is required due to
 8604: #                 the capability for multihomed systems.
 8605: #    $user      - The name of the user being validated.
 8606: #    $password  - The user's propoposed password.
 8607: #
 8608: # Returns:
 8609: #     1        - The domain,user,pasword triplet corresponds to a valid
 8610: #                user.
 8611: #     0        - The domain,user,password triplet is not a valid user.
 8612: #
 8613: sub validate_user {
 8614:     my ($domain, $user, $password, $checkdefauth) = @_;
 8615: 
 8616:     # Why negative ~pi you may well ask?  Well this function is about
 8617:     # authentication, and therefore very important to get right.
 8618:     # I've initialized the flag that determines whether or not I've 
 8619:     # validated correctly to a value it's not supposed to get.
 8620:     # At the end of this function. I'll ensure that it's not still that
 8621:     # value so we don't just wind up returning some accidental value
 8622:     # as a result of executing an unforseen code path that
 8623:     # did not set $validated.  At the end of valid execution paths,
 8624:     # validated shoule be 1 for success or 0 for failuer.
 8625: 
 8626:     my $validated = -3.14159;
 8627: 
 8628:     #  How we authenticate is determined by the type of authentication
 8629:     #  the user has been assigned.  If the authentication type is
 8630:     #  "nouser", the user does not exist so we will return 0.
 8631: 
 8632:     my $contents = &get_auth_type($domain, $user);
 8633:     my ($howpwd, $contentpwd) = split(/:/, $contents);
 8634: 
 8635:     my $null = pack("C",0);	# Used by kerberos auth types.
 8636: 
 8637:     if ($howpwd eq 'nouser') {
 8638:         if ($checkdefauth) {
 8639:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 8640:             if ($domdefaults{'auth_def'} eq 'localauth') {
 8641:                 $howpwd = $domdefaults{'auth_def'};
 8642:                 $contentpwd = $domdefaults{'auth_arg_def'};
 8643:             } elsif ((($domdefaults{'auth_def'} eq 'krb4') || 
 8644:                       ($domdefaults{'auth_def'} eq 'krb5')) &&
 8645:                      ($domdefaults{'auth_arg_def'} ne '')) {
 8646:                 #
 8647:                 # Don't attempt authentication for username and password supplied
 8648:                 # for user without an account if uername contains @ to avoid
 8649:                 # call to &Authen::Krb5::parse_name() which will result in con_lost
 8650:                 #
 8651:                 unless ($user =~ /\@/) {
 8652:                     $howpwd = $domdefaults{'auth_def'};
 8653:                     $contentpwd = $domdefaults{'auth_arg_def'};
 8654:                 }
 8655:             }
 8656:         }
 8657:     }
 8658:     if ($howpwd ne 'nouser') {
 8659: 	if($howpwd eq "internal") { # Encrypted is in local password file.
 8660:             if (length($contentpwd) == 13) {
 8661:                 $validated = (crypt($password,$contentpwd) eq $contentpwd);
 8662:                 if ($validated) {
 8663:                     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 8664:                     if ($domdefaults{'intauth_switch'}) {
 8665:                         my $ncpass = &hash_passwd($domain,$password);
 8666:                         my $saveold;
 8667:                         if ($domdefaults{'intauth_switch'} == 2) {
 8668:                             $saveold = 1;
 8669:                         }
 8670:                         if (&rewrite_password_file($domain,$user,"$howpwd:$ncpass",$saveold)) {
 8671:                             &update_passwd_history($user,$domain,$howpwd,'conversion');
 8672:                             &logthis("Validated password hashed with bcrypt for $user:$domain");
 8673:                         }
 8674:                     }
 8675:                 }
 8676:             } else {
 8677:                 $validated = &check_internal_passwd($password,$contentpwd,$domain,$user);
 8678:             }
 8679: 	}
 8680: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
 8681: 	    $contentpwd = (getpwnam($user))[1];
 8682: 	    if($contentpwd) {
 8683: 		if($contentpwd eq 'x') { # Shadow password file...
 8684: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
 8685: 		    open PWAUTH,  "|$pwauth_path" or
 8686: 			die "Cannot invoke authentication";
 8687: 		    print PWAUTH "$user\n$password\n";
 8688: 		    close PWAUTH;
 8689: 		    $validated = ! $?;
 8690: 
 8691: 		} else { 	         # Passwords in /etc/passwd. 
 8692: 		    $validated = (crypt($password,
 8693: 					$contentpwd) eq $contentpwd);
 8694: 		}
 8695: 	    } else {
 8696: 		$validated = 0;
 8697: 	    }
 8698: 	} elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
 8699:             my $checkwithkrb5 = 0;
 8700:             if ($dist =~/^fedora(\d+)$/) {
 8701:                 if ($1 > 11) {
 8702:                     $checkwithkrb5 = 1;
 8703:                 }
 8704:             } elsif ($dist =~ /^suse([\d.]+)$/) {
 8705:                 if ($1 > 11.1) {
 8706:                     $checkwithkrb5 = 1; 
 8707:                 }
 8708:             }
 8709:             if ($checkwithkrb5) {
 8710:                 $validated = &krb5_authen($password,$null,$user,$contentpwd);
 8711:             } else {
 8712:                 $validated = &krb4_authen($password,$null,$user,$contentpwd);
 8713:             }
 8714: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
 8715:             $validated = &krb5_authen($password,$null,$user,$contentpwd);
 8716: 	} elsif ($howpwd eq "localauth") { 
 8717: 	    #  Authenticate via installation specific authentcation method:
 8718: 	    $validated = &localauth::localauth($user, 
 8719: 					       $password, 
 8720: 					       $contentpwd,
 8721: 					       $domain);
 8722: 	    if ($validated < 0) {
 8723: 		&logthis("localauth for $contentpwd $user:$domain returned a $validated");
 8724: 		$validated = 0;
 8725: 	    }
 8726: 	} else {			# Unrecognized auth is also bad.
 8727: 	    $validated = 0;
 8728: 	}
 8729:     } else {
 8730: 	$validated = 0;
 8731:     }
 8732:     #
 8733:     #  $validated has the correct stat of the authentication:
 8734:     #
 8735: 
 8736:     unless ($validated != -3.14159) {
 8737: 	#  I >really really< want to know if this happens.
 8738: 	#  since it indicates that user authentication is badly
 8739: 	#  broken in some code path.
 8740:         #
 8741: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
 8742:     }
 8743:     return $validated;
 8744: }
 8745: 
 8746: sub check_internal_passwd {
 8747:     my ($plainpass,$stored,$domain,$user) = @_;
 8748:     my (undef,$method,@rest) = split(/!/,$stored);
 8749:     if ($method eq 'bcrypt') {
 8750:         my $result = &hash_passwd($domain,$plainpass,@rest);
 8751:         if ($result ne $stored) {
 8752:             return 0;
 8753:         }
 8754:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 8755:         if ($domdefaults{'intauth_check'}) {
 8756:             # Upgrade to a larger number of rounds if necessary
 8757:             my $defaultcost = $domdefaults{'intauth_cost'};
 8758:             if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
 8759:                 $defaultcost = 10;
 8760:             }
 8761:             if (int($rest[0])<int($defaultcost)) {
 8762:                 if ($domdefaults{'intauth_check'} == 1) { 
 8763:                     my $ncpass = &hash_passwd($domain,$plainpass);
 8764:                     if (&rewrite_password_file($domain,$user,"internal:$ncpass")) {
 8765:                         &update_passwd_history($user,$domain,'internal','update cost');
 8766:                         &logthis("Validated password hashed with bcrypt for $user:$domain");
 8767:                     }
 8768:                     return 1;
 8769:                 } elsif ($domdefaults{'intauth_check'} == 2) {
 8770:                     return 0;
 8771:                 }
 8772:             }
 8773:         } else {
 8774:             return 1;
 8775:         }
 8776:     }
 8777:     return 0;
 8778: }
 8779: 
 8780: sub get_last_authchg {
 8781:     my ($domain,$user) = @_;
 8782:     my $lastmod;
 8783:     my $logname = &propath($domain,$user).'/passwd.log';
 8784:     if (-e "$logname") {
 8785:         $lastmod = (stat("$logname"))[9];
 8786:     }
 8787:     return $lastmod;
 8788: }
 8789: 
 8790: sub krb4_authen {
 8791:     my ($password,$null,$user,$contentpwd) = @_;
 8792:     my $validated = 0;
 8793:     if (!($password =~ /$null/) ) {  # Null password not allowed.
 8794:         eval {
 8795:             require Authen::Krb4;
 8796:         };
 8797:         if (!$@) {
 8798:             my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
 8799:                                                        "",
 8800:                                                        $contentpwd,,
 8801:                                                        'krbtgt',
 8802:                                                        $contentpwd,
 8803:                                                        1,
 8804:                                                        $password);
 8805:             if(!$k4error) {
 8806:                 $validated = 1;
 8807:             } else {
 8808:                 $validated = 0;
 8809:                 &logthis('krb4: '.$user.', '.$contentpwd.', '.
 8810:                           &Authen::Krb4::get_err_txt($Authen::Krb4::error));
 8811:             }
 8812:         } else {
 8813:             $validated = krb5_authen($password,$null,$user,$contentpwd);
 8814:         }
 8815:     }
 8816:     return $validated;
 8817: }
 8818: 
 8819: sub krb5_authen {
 8820:     my ($password,$null,$user,$contentpwd) = @_;
 8821:     my $validated = 0;
 8822:     if(!($password =~ /$null/)) { # Null password not allowed.
 8823:         my $krbclient = &Authen::Krb5::parse_name($user.'@'
 8824:                                                   .$contentpwd);
 8825:         my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
 8826:         my $krbserver  = &Authen::Krb5::parse_name($krbservice);
 8827:         my $credentials= &Authen::Krb5::cc_default();
 8828:         $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
 8829:                                                             .$contentpwd));
 8830:         my $krbreturn;
 8831:         if (exists(&Authen::Krb5::get_init_creds_password)) {
 8832:             $krbreturn =
 8833:                 &Authen::Krb5::get_init_creds_password($krbclient,$password,
 8834:                                                           $krbservice);
 8835:             $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
 8836:         } else {
 8837:             $krbreturn  =
 8838:                 &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
 8839:                                                          $password,$credentials);
 8840:             $validated = ($krbreturn == 1);
 8841:         }
 8842:         if (!$validated) {
 8843:             &logthis('krb5: '.$user.', '.$contentpwd.', '.
 8844:                      &Authen::Krb5::error());
 8845:         }
 8846:     }
 8847:     return $validated;
 8848: }
 8849: 
 8850: sub addline {
 8851:     my ($fname,$hostid,$ip,$newline)=@_;
 8852:     my $contents;
 8853:     my $found=0;
 8854:     my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
 8855:     my $sh;
 8856:     if ($sh=IO::File->new("$fname.subscription")) {
 8857: 	while (my $subline=<$sh>) {
 8858: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
 8859: 	}
 8860: 	$sh->close();
 8861:     }
 8862:     $sh=IO::File->new(">$fname.subscription");
 8863:     if ($contents) { print $sh $contents; }
 8864:     if ($newline) { print $sh $newline; }
 8865:     $sh->close();
 8866:     return $found;
 8867: }
 8868: 
 8869: sub get_chat {
 8870:     my ($cdom,$cname,$udom,$uname,$group)=@_;
 8871: 
 8872:     my @entries=();
 8873:     my $namespace = 'nohist_chatroom';
 8874:     my $namespace_inroom = 'nohist_inchatroom';
 8875:     if ($group ne '') {
 8876:         $namespace .= '_'.$group;
 8877:         $namespace_inroom .= '_'.$group;
 8878:     }
 8879:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
 8880: 				 &GDBM_READER());
 8881:     if ($hashref) {
 8882: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
 8883: 	&untie_user_hash($hashref);
 8884:     }
 8885:     my @participants=();
 8886:     my $cutoff=time-60;
 8887:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
 8888: 			      &GDBM_WRCREAT());
 8889:     if ($hashref) {
 8890:         $hashref->{$uname.':'.$udom}=time;
 8891:         foreach my $user (sort(keys(%$hashref))) {
 8892: 	    if ($hashref->{$user}>$cutoff) {
 8893: 		push(@participants, 'active_participant:'.$user);
 8894:             }
 8895:         }
 8896:         &untie_user_hash($hashref);
 8897:     }
 8898:     return (@participants,@entries);
 8899: }
 8900: 
 8901: sub chat_add {
 8902:     my ($cdom,$cname,$newchat,$group)=@_;
 8903:     my @entries=();
 8904:     my $time=time;
 8905:     my $namespace = 'nohist_chatroom';
 8906:     my $logfile = 'chatroom.log';
 8907:     if ($group ne '') {
 8908:         $namespace .= '_'.$group;
 8909:         $logfile = 'chatroom_'.$group.'.log';
 8910:     }
 8911:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
 8912: 				 &GDBM_WRCREAT());
 8913:     if ($hashref) {
 8914: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
 8915: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
 8916: 	my ($thentime,$idnum)=split(/\_/,$lastid);
 8917: 	my $newid=$time.'_000000';
 8918: 	if ($thentime==$time) {
 8919: 	    $idnum=~s/^0+//;
 8920: 	    $idnum++;
 8921: 	    $idnum=substr('000000'.$idnum,-6,6);
 8922: 	    $newid=$time.'_'.$idnum;
 8923: 	}
 8924: 	$hashref->{$newid}=$newchat;
 8925: 	my $expired=$time-3600;
 8926: 	foreach my $comment (keys(%$hashref)) {
 8927: 	    my ($thistime) = ($comment=~/(\d+)\_/);
 8928: 	    if ($thistime<$expired) {
 8929: 		delete $hashref->{$comment};
 8930: 	    }
 8931: 	}
 8932: 	{
 8933: 	    my $proname=&propath($cdom,$cname);
 8934: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
 8935: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
 8936: 	    }
 8937: 	    close(CHATLOG);
 8938: 	}
 8939: 	&untie_user_hash($hashref);
 8940:     }
 8941: }
 8942: 
 8943: sub unsub {
 8944:     my ($fname,$clientip)=@_;
 8945:     my $result;
 8946:     my $unsubs = 0;		# Number of successful unsubscribes:
 8947: 
 8948: 
 8949:     # An old way subscriptions were handled was to have a 
 8950:     # subscription marker file:
 8951: 
 8952:     Debug("Attempting unlink of $fname.$clientname");
 8953:     if (unlink("$fname.$clientname")) {
 8954: 	$unsubs++;		# Successful unsub via marker file.
 8955:     } 
 8956: 
 8957:     # The more modern way to do it is to have a subscription list
 8958:     # file:
 8959: 
 8960:     if (-e "$fname.subscription") {
 8961: 	my $found=&addline($fname,$clientname,$clientip,'');
 8962: 	if ($found) { 
 8963: 	    $unsubs++;
 8964: 	}
 8965:     } 
 8966: 
 8967:     #  If either or both of these mechanisms succeeded in unsubscribing a 
 8968:     #  resource we can return ok:
 8969: 
 8970:     if($unsubs) {
 8971: 	$result = "ok\n";
 8972:     } else {
 8973: 	$result = "not_subscribed\n";
 8974:     }
 8975: 
 8976:     return $result;
 8977: }
 8978: 
 8979: sub currentversion {
 8980:     my $fname=shift;
 8981:     my $version=-1;
 8982:     my $ulsdir='';
 8983:     if ($fname=~/^(.+)\/[^\/]+$/) {
 8984:        $ulsdir=$1;
 8985:     }
 8986:     my ($fnamere1,$fnamere2);
 8987:     # remove version if already specified
 8988:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
 8989:     # get the bits that go before and after the version number
 8990:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
 8991: 	$fnamere1=$1;
 8992: 	$fnamere2='.'.$2;
 8993:     }
 8994:     if (-e $fname) { $version=1; }
 8995:     if (-e $ulsdir) {
 8996: 	if(-d $ulsdir) {
 8997: 	    if (opendir(LSDIR,$ulsdir)) {
 8998:                 if (-e $fname) {
 8999:                     $version=0;
 9000:                 }
 9001: 		my $ulsfn;
 9002: 		while ($ulsfn=readdir(LSDIR)) {
 9003: # see if this is a regular file (ignore links produced earlier)
 9004: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
 9005: 		    unless (-l $thisfile) {
 9006: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
 9007: 			    if ($1>$version) { $version=$1; }
 9008: 			}
 9009: 		    }
 9010: 		}
 9011: 		closedir(LSDIR);
 9012: 		$version++;
 9013: 	    }
 9014: 	}
 9015:     }
 9016:     return $version;
 9017: }
 9018: 
 9019: sub thisversion {
 9020:     my $fname=shift;
 9021:     my $version=-1;
 9022:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
 9023: 	$version=$1;
 9024:     }
 9025:     return $version;
 9026: }
 9027: 
 9028: sub subscribe {
 9029:     my ($userinput,$clientip)=@_;
 9030:     my $result;
 9031:     my ($cmd,$fname)=split(/:/,$userinput,2);
 9032:     my $ownership=&ishome($fname);
 9033:     if ($ownership eq 'owner') {
 9034: # explitly asking for the current version?
 9035:         unless (-e $fname) {
 9036:             my $currentversion=&currentversion($fname);
 9037: 	    if (&thisversion($fname)==$currentversion) {
 9038:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
 9039: 		    my $root=$1;
 9040:                     my $extension=$2;
 9041:                     symlink($root.'.'.$extension,
 9042:                             $root.'.'.$currentversion.'.'.$extension);
 9043:                     unless ($extension=~/\.meta$/) {
 9044:                        symlink($root.'.'.$extension.'.meta',
 9045:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
 9046: 		    }
 9047:                 }
 9048:             }
 9049:         }
 9050: 	if (-e $fname) {
 9051: 	    if (-d $fname) {
 9052: 		$result="directory\n";
 9053: 	    } else {
 9054: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
 9055: 		my $now=time;
 9056: 		my $found=&addline($fname,$clientname,$clientip,
 9057: 				   "$clientname:$clientip:$now\n");
 9058: 		if ($found) { $result="$fname\n"; }
 9059: 		# if they were subscribed to only meta data, delete that
 9060:                 # subscription, when you subscribe to a file you also get
 9061:                 # the metadata
 9062: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
 9063: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
 9064:                 my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
 9065:                 $protocol = 'http' if ($protocol ne 'https');
 9066: 		$fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
 9067: 		$result="$fname\n";
 9068: 	    }
 9069: 	} else {
 9070: 	    $result="not_found\n";
 9071: 	}
 9072:     } else {
 9073: 	$result="rejected\n";
 9074:     }
 9075:     return $result;
 9076: }
 9077: #  Change the passwd of a unix user.  The caller must have
 9078: #  first verified that the user is a loncapa user.
 9079: #
 9080: # Parameters:
 9081: #    user      - Unix user name to change.
 9082: #    pass      - New password for the user.
 9083: # Returns:
 9084: #    ok    - if success
 9085: #    other - Some meaningfule error message string.
 9086: # NOTE:
 9087: #    invokes a setuid script to change the passwd.
 9088: sub change_unix_password {
 9089:     my ($user, $pass) = @_;
 9090: 
 9091:     &Debug("change_unix_password");
 9092:     my $execdir=$perlvar{'lonDaemons'};
 9093:     &Debug("Opening lcpasswd pipeline");
 9094:     my $pf = IO::File->new("|$execdir/lcpasswd > "
 9095: 			   ."$perlvar{'lonDaemons'}"
 9096: 			   ."/logs/lcpasswd.log");
 9097:     print $pf "$user\n$pass\n$pass\n";
 9098:     close $pf;
 9099:     my $err = $?;
 9100:     return ($err < @passwderrors) ? $passwderrors[$err] : 
 9101: 	"pwchange_falure - unknown error";
 9102: 
 9103:     
 9104: }
 9105: 
 9106: 
 9107: sub make_passwd_file {
 9108:     my ($uname,$udom,$umode,$npass,$passfilename,$action)=@_;
 9109:     my $result="ok";
 9110:     if ($umode eq 'krb4' or $umode eq 'krb5') {
 9111: 	{
 9112: 	    my $pf = IO::File->new(">$passfilename");
 9113: 	    if ($pf) {
 9114: 		print $pf "$umode:$npass\n";
 9115:                 &update_passwd_history($uname,$udom,$umode,$action);
 9116: 	    } else {
 9117: 		$result = "pass_file_failed_error";
 9118: 	    }
 9119: 	}
 9120:     } elsif ($umode eq 'internal') {
 9121:         my $ncpass = &hash_passwd($udom,$npass);
 9122: 	{
 9123: 	    &Debug("Creating internal auth");
 9124: 	    my $pf = IO::File->new(">$passfilename");
 9125: 	    if($pf) {
 9126: 		print $pf "internal:$ncpass\n";
 9127:                 &update_passwd_history($uname,$udom,$umode,$action); 
 9128: 	    } else {
 9129: 		$result = "pass_file_failed_error";
 9130: 	    }
 9131: 	}
 9132:     } elsif ($umode eq 'localauth') {
 9133: 	{
 9134: 	    my $pf = IO::File->new(">$passfilename");
 9135: 	    if($pf) {
 9136: 		print $pf "localauth:$npass\n";
 9137:                 &update_passwd_history($uname,$udom,$umode,$action);
 9138: 	    } else {
 9139: 		$result = "pass_file_failed_error";
 9140: 	    }
 9141: 	}
 9142:     } elsif ($umode eq 'unix') {
 9143: 	&logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
 9144: 	$result="no_new_unix_accounts";
 9145:     } elsif ($umode eq 'none') {
 9146: 	{
 9147: 	    my $pf = IO::File->new("> $passfilename");
 9148: 	    if($pf) {
 9149: 		print $pf "none:\n";
 9150: 	    } else {
 9151: 		$result = "pass_file_failed_error";
 9152: 	    }
 9153: 	}
 9154:     } elsif ($umode eq 'lti') {
 9155:         my $pf = IO::File->new(">$passfilename");
 9156:         if($pf) {
 9157:             print $pf "lti:\n";
 9158:             &update_passwd_history($uname,$udom,$umode,$action);
 9159:         } else {
 9160:             $result = "pass_file_failed_error";
 9161:         }
 9162:     } else {
 9163: 	$result="auth_mode_error";
 9164:     }
 9165:     return $result;
 9166: }
 9167: 
 9168: sub convert_photo {
 9169:     my ($start,$dest)=@_;
 9170:     system("convert $start $dest");
 9171: }
 9172: 
 9173: sub sethost {
 9174:     my ($remotereq) = @_;
 9175:     my (undef,$hostid)=split(/:/,$remotereq);
 9176:     # ignore sethost if we are already correct
 9177:     if ($hostid eq $currenthostid) {
 9178: 	return 'ok';
 9179:     }
 9180: 
 9181:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
 9182:     if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'}) 
 9183: 	eq &Apache::lonnet::get_host_ip($hostid)) {
 9184: 	$currenthostid  =$hostid;
 9185: 	$currentdomainid=&Apache::lonnet::host_domain($hostid);
 9186:         &set_client_info();
 9187: #	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
 9188:     } else {
 9189: 	&logthis("Requested host id $hostid not an alias of ".
 9190: 		 $perlvar{'lonHostID'}." refusing connection");
 9191: 	return 'unable_to_set';
 9192:     }
 9193:     return 'ok';
 9194: }
 9195: 
 9196: sub version {
 9197:     my ($userinput)=@_;
 9198:     $remoteVERSION=(split(/:/,$userinput))[1];
 9199:     return "version:$VERSION";
 9200: }
 9201: 
 9202: sub get_usersession_config {
 9203:     my ($dom,$name) = @_;
 9204:     my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
 9205:     if (defined($cached)) {
 9206:         return $usersessionconf;
 9207:     } else {
 9208:         my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
 9209:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
 9210:         return $domconfig{'usersessions'};
 9211:     }
 9212:     return;
 9213: }
 9214: 
 9215: sub get_usersearch_config {
 9216:     my ($dom,$name) = @_;
 9217:     my ($usersearchconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
 9218:     if (defined($cached)) {
 9219:         return $usersearchconf;
 9220:     } else {
 9221:         my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$dom);
 9222:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'directorysrch'},600);
 9223:         return $domconfig{'directorysrch'};
 9224:     }
 9225:     return;
 9226: }
 9227: 
 9228: sub get_prohibited {
 9229:     my ($dom) = @_;
 9230:     my $name = 'trust';
 9231:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
 9232:     unless (defined($cached)) {
 9233:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$dom);
 9234:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'trust'},3600);
 9235:         $trustconfig = $domconfig{'trust'};
 9236:     }
 9237:     my %prohibited;
 9238:     if (ref($trustconfig)) {
 9239:         foreach my $prefix (keys(%{$trustconfig})) {
 9240:             if (ref($trustconfig->{$prefix}) eq 'HASH') {
 9241:                 my $reject;
 9242:                 if (ref($trustconfig->{$prefix}->{'exc'}) eq 'ARRAY') {
 9243:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'exc'}})) {
 9244:                         $reject = 1;
 9245:                     }
 9246:                 }
 9247:                 if (ref($trustconfig->{$prefix}->{'inc'}) eq 'ARRAY') {
 9248:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'inc'}})) {
 9249:                         $reject = 0;
 9250:                     } else {
 9251:                         $reject = 1;
 9252:                     }
 9253:                 }
 9254:                 if ($reject) {
 9255:                     $prohibited{$prefix} = 1;
 9256:                 }
 9257:             }
 9258:         }
 9259:     }
 9260:     return %prohibited;
 9261: }
 9262: 
 9263: sub get_remote_hostable {
 9264:     my ($dom) = @_;
 9265:     my $result;
 9266:     if ($clientintdom) {
 9267:         $result = 1;
 9268:         my $remsessconf = &get_usersession_config($dom,'remotesession');
 9269:         if (ref($remsessconf) eq 'HASH') {
 9270:             if (ref($remsessconf->{'remote'}) eq 'HASH') {
 9271:                 if (ref($remsessconf->{'remote'}->{'excludedomain'}) eq 'ARRAY') {
 9272:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'excludedomain'}})) {
 9273:                         $result = 0;
 9274:                     }
 9275:                 }
 9276:                 if (ref($remsessconf->{'remote'}->{'includedomain'}) eq 'ARRAY') {
 9277:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'includedomain'}})) {
 9278:                         $result = 1;
 9279:                     } else {
 9280:                         $result = 0;
 9281:                     }
 9282:                 }
 9283:             }
 9284:         }
 9285:     }
 9286:     return $result;
 9287: }
 9288: 
 9289: sub distro_and_arch {
 9290:     return $dist.':'.$arch;
 9291: }
 9292: 
 9293: # ----------------------------------- POD (plain old documentation, CPAN style)
 9294: 
 9295: =head1 NAME
 9296: 
 9297: lond - "LON Daemon" Server (port "LOND" 5663)
 9298: 
 9299: =head1 SYNOPSIS
 9300: 
 9301: Usage: B<lond>
 9302: 
 9303: Should only be run as user=www.  This is a command-line script which
 9304: is invoked by B<loncron>.  There is no expectation that a typical user
 9305: will manually start B<lond> from the command-line.  (In other words,
 9306: DO NOT START B<lond> YOURSELF.)
 9307: 
 9308: =head1 DESCRIPTION
 9309: 
 9310: There are two characteristics associated with the running of B<lond>,
 9311: PROCESS MANAGEMENT (starting, stopping, handling child processes)
 9312: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
 9313: subscriptions, etc).  These are described in two large
 9314: sections below.
 9315: 
 9316: B<PROCESS MANAGEMENT>
 9317: 
 9318: Preforker - server who forks first. Runs as a daemon. HUPs.
 9319: Uses IDEA encryption
 9320: 
 9321: B<lond> forks off children processes that correspond to the other servers
 9322: in the network.  Management of these processes can be done at the
 9323: parent process level or the child process level.
 9324: 
 9325: B<logs/lond.log> is the location of log messages.
 9326: 
 9327: The process management is now explained in terms of linux shell commands,
 9328: subroutines internal to this code, and signal assignments:
 9329: 
 9330: =over 4
 9331: 
 9332: =item *
 9333: 
 9334: PID is stored in B<logs/lond.pid>
 9335: 
 9336: This is the process id number of the parent B<lond> process.
 9337: 
 9338: =item *
 9339: 
 9340: SIGTERM and SIGINT
 9341: 
 9342: Parent signal assignment:
 9343:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 9344: 
 9345: Child signal assignment:
 9346:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
 9347: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
 9348:  to restart a new child.)
 9349: 
 9350: Command-line invocations:
 9351:  B<kill> B<-s> SIGTERM I<PID>
 9352:  B<kill> B<-s> SIGINT I<PID>
 9353: 
 9354: Subroutine B<HUNTSMAN>:
 9355:  This is only invoked for the B<lond> parent I<PID>.
 9356: This kills all the children, and then the parent.
 9357: The B<lonc.pid> file is cleared.
 9358: 
 9359: =item *
 9360: 
 9361: SIGHUP
 9362: 
 9363: Current bug:
 9364:  This signal can only be processed the first time
 9365: on the parent process.  Subsequent SIGHUP signals
 9366: have no effect.
 9367: 
 9368: Parent signal assignment:
 9369:  $SIG{HUP}  = \&HUPSMAN;
 9370: 
 9371: Child signal assignment:
 9372:  none (nothing happens)
 9373: 
 9374: Command-line invocations:
 9375:  B<kill> B<-s> SIGHUP I<PID>
 9376: 
 9377: Subroutine B<HUPSMAN>:
 9378:  This is only invoked for the B<lond> parent I<PID>,
 9379: This kills all the children, and then the parent.
 9380: The B<lond.pid> file is cleared.
 9381: 
 9382: =item *
 9383: 
 9384: SIGUSR1
 9385: 
 9386: Parent signal assignment:
 9387:  $SIG{USR1} = \&USRMAN;
 9388: 
 9389: Child signal assignment:
 9390:  $SIG{USR1}= \&logstatus;
 9391: 
 9392: Command-line invocations:
 9393:  B<kill> B<-s> SIGUSR1 I<PID>
 9394: 
 9395: Subroutine B<USRMAN>:
 9396:  When invoked for the B<lond> parent I<PID>,
 9397: SIGUSR1 is sent to all the children, and the status of
 9398: each connection is logged.
 9399: 
 9400: =item *
 9401: 
 9402: SIGUSR2
 9403: 
 9404: Parent Signal assignment:
 9405:     $SIG{USR2} = \&UpdateHosts
 9406: 
 9407: Child signal assignment:
 9408:     NONE
 9409: 
 9410: 
 9411: =item *
 9412: 
 9413: SIGCHLD
 9414: 
 9415: Parent signal assignment:
 9416:  $SIG{CHLD} = \&REAPER;
 9417: 
 9418: Child signal assignment:
 9419:  none
 9420: 
 9421: Command-line invocations:
 9422:  B<kill> B<-s> SIGCHLD I<PID>
 9423: 
 9424: Subroutine B<REAPER>:
 9425:  This is only invoked for the B<lond> parent I<PID>.
 9426: Information pertaining to the child is removed.
 9427: The socket port is cleaned up.
 9428: 
 9429: =back
 9430: 
 9431: B<SERVER-SIDE ACTIVITIES>
 9432: 
 9433: Server-side information can be accepted in an encrypted or non-encrypted
 9434: method.
 9435: 
 9436: =over 4
 9437: 
 9438: =item ping
 9439: 
 9440: Query a client in the hosts.tab table; "Are you there?"
 9441: 
 9442: =item pong
 9443: 
 9444: Respond to a ping query.
 9445: 
 9446: =item ekey
 9447: 
 9448: Read in encrypted key, make cipher.  Respond with a buildkey.
 9449: 
 9450: =item load
 9451: 
 9452: Respond with CPU load based on a computation upon /proc/loadavg.
 9453: 
 9454: =item currentauth
 9455: 
 9456: Reply with current authentication information (only over an
 9457: encrypted channel).
 9458: 
 9459: =item auth
 9460: 
 9461: Only over an encrypted channel, reply as to whether a user's
 9462: authentication information can be validated.
 9463: 
 9464: =item passwd
 9465: 
 9466: Allow for a password to be set.
 9467: 
 9468: =item makeuser
 9469: 
 9470: Make a user.
 9471: 
 9472: =item changeuserauth
 9473: 
 9474: Allow for authentication mechanism and password to be changed.
 9475: 
 9476: =item home
 9477: 
 9478: Respond to a question "are you the home for a given user?"
 9479: 
 9480: =item update
 9481: 
 9482: Update contents of a subscribed resource.
 9483: 
 9484: =item unsubscribe
 9485: 
 9486: The server is unsubscribing from a resource.
 9487: 
 9488: =item subscribe
 9489: 
 9490: The server is subscribing to a resource.
 9491: 
 9492: =item log
 9493: 
 9494: Place in B<logs/lond.log>
 9495: 
 9496: =item put
 9497: 
 9498: stores hash in namespace
 9499: 
 9500: =item rolesput
 9501: 
 9502: put a role into a user's environment
 9503: 
 9504: =item get
 9505: 
 9506: returns hash with keys from array
 9507: reference filled in from namespace
 9508: 
 9509: =item eget
 9510: 
 9511: returns hash with keys from array
 9512: reference filled in from namesp (encrypts the return communication)
 9513: 
 9514: =item rolesget
 9515: 
 9516: get a role from a user's environment
 9517: 
 9518: =item del
 9519: 
 9520: deletes keys out of array from namespace
 9521: 
 9522: =item keys
 9523: 
 9524: returns namespace keys
 9525: 
 9526: =item dump
 9527: 
 9528: dumps the complete (or key matching regexp) namespace into a hash
 9529: 
 9530: =item store
 9531: 
 9532: stores hash permanently
 9533: for this url; hashref needs to be given and should be a \%hashname; the
 9534: remaining args aren't required and if they aren't passed or are '' they will
 9535: be derived from the ENV
 9536: 
 9537: =item restore
 9538: 
 9539: returns a hash for a given url
 9540: 
 9541: =item querysend
 9542: 
 9543: Tells client about the lonsql process that has been launched in response
 9544: to a sent query.
 9545: 
 9546: =item queryreply
 9547: 
 9548: Accept information from lonsql and make appropriate storage in temporary
 9549: file space.
 9550: 
 9551: =item idput
 9552: 
 9553: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
 9554: for each student, defined perhaps by the institutional Registrar.)
 9555: 
 9556: =item idget
 9557: 
 9558: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
 9559: for each student, defined perhaps by the institutional Registrar.)
 9560: 
 9561: =item iddel
 9562: 
 9563: Deletes one or more ids in a domain's id database.
 9564: 
 9565: =item tmpput
 9566: 
 9567: Accept and store information in temporary space.
 9568: 
 9569: =item tmpget
 9570: 
 9571: Send along temporarily stored information.
 9572: 
 9573: =item ls
 9574: 
 9575: List part of a user's directory.
 9576: 
 9577: =item pushtable
 9578: 
 9579: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
 9580: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
 9581: must be restored manually in case of a problem with the new table file.
 9582: pushtable requires that the request be encrypted and validated via
 9583: ValidateManager.  The form of the command is:
 9584: enc:pushtable tablename <tablecontents> \n
 9585: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
 9586: cleartext newline.
 9587: 
 9588: =item Hanging up (exit or init)
 9589: 
 9590: What to do when a client tells the server that they (the client)
 9591: are leaving the network.
 9592: 
 9593: =item unknown command
 9594: 
 9595: If B<lond> is sent an unknown command (not in the list above),
 9596: it replys to the client "unknown_cmd".
 9597: 
 9598: 
 9599: =item UNKNOWN CLIENT
 9600: 
 9601: If the anti-spoofing algorithm cannot verify the client,
 9602: the client is rejected (with a "refused" message sent
 9603: to the client, and the connection is closed.
 9604: 
 9605: =back
 9606: 
 9607: =head1 PREREQUISITES
 9608: 
 9609: IO::Socket
 9610: IO::File
 9611: Apache::File
 9612: POSIX
 9613: Crypt::IDEA
 9614: GDBM_File
 9615: Authen::Krb4
 9616: Authen::Krb5
 9617: 
 9618: =head1 COREQUISITES
 9619: 
 9620: none
 9621: 
 9622: =head1 OSNAMES
 9623: 
 9624: linux
 9625: 
 9626: =head1 SCRIPT CATEGORIES
 9627: 
 9628: Server/Process
 9629: 
 9630: =cut
 9631: 
 9632: 
 9633: =pod
 9634: 
 9635: =head1 LOG MESSAGES
 9636: 
 9637: The messages below can be emitted in the lond log.  This log is located
 9638: in ~httpd/perl/logs/lond.log  Many log messages have HTML encapsulation
 9639: to provide coloring if examined from inside a web page. Some do not.
 9640: Where color is used, the colors are; Red for sometihhng to get excited
 9641: about and to follow up on. Yellow for something to keep an eye on to
 9642: be sure it does not get worse, Green,and Blue for informational items.
 9643: 
 9644: In the discussions below, sometimes reference is made to ~httpd
 9645: when describing file locations.  There isn't really an httpd 
 9646: user, however there is an httpd directory that gets installed in the
 9647: place that user home directories go.  On linux, this is usually
 9648: (always?) /home/httpd.
 9649: 
 9650: 
 9651: Some messages are colorless.  These are usually (not always)
 9652: Green/Blue color level messages.
 9653: 
 9654: =over 2
 9655: 
 9656: =item (Red)  LocalConnection rejecting non local: <ip> ne 127.0.0.1
 9657: 
 9658: A local connection negotiation was attempted by
 9659: a host whose IP address was not 127.0.0.1.
 9660: The socket is closed and the child will exit.
 9661: lond has three ways to establish an encyrption
 9662: key with a client:
 9663: 
 9664: =over 2
 9665: 
 9666: =item local 
 9667: 
 9668: The key is written and read from a file.
 9669: This is only valid for connections from localhost.
 9670: 
 9671: =item insecure 
 9672: 
 9673: The key is generated by the server and
 9674: transmitted to the client.
 9675: 
 9676: =item  ssl (secure)
 9677: 
 9678: An ssl connection is negotiated with the client,
 9679: the key is generated by the server and sent to the 
 9680: client across this ssl connection before the
 9681: ssl connectionis terminated and clear text
 9682: transmission resumes.
 9683: 
 9684: =back
 9685: 
 9686: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
 9687: 
 9688: The client is local but has not sent an initialization
 9689: string that is the literal "init:local"  The connection
 9690: is closed and the child exits.
 9691: 
 9692: =item Red CRITICAL Can't get key file <error>        
 9693: 
 9694: SSL key negotiation is being attempted but the call to
 9695: lonssl::KeyFile failed.  This usually means that the
 9696: configuration file is not correctly defining or protecting
 9697: the directories/files lonCertificateDirectory or
 9698: lonnetPrivateKey
 9699: <error> is a string that describes the reason that
 9700: the key file could not be located.
 9701: 
 9702: =item (Red) CRITICAL  Can't get certificates <error>  
 9703: 
 9704: SSL key negotiation failed because we were not able to retrives our certificate
 9705: or the CA's certificate in the call to lonssl::CertificateFile
 9706: <error> is the textual reason this failed.  Usual reasons:
 9707: 
 9708: =over 2
 9709: 
 9710: =item Apache config file for loncapa  incorrect:
 9711: 
 9712: one of the variables 
 9713: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
 9714: undefined or incorrect
 9715: 
 9716: =item Permission error:
 9717: 
 9718: The directory pointed to by lonCertificateDirectory is not readable by lond
 9719: 
 9720: =item Permission error:
 9721: 
 9722: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
 9723: 
 9724: =item Installation error:                         
 9725: 
 9726: Either the certificate authority file or the certificate have not
 9727: been installed in lonCertificateDirectory.
 9728: 
 9729: =item (Red) CRITICAL SSL Socket promotion failed:  <err> 
 9730: 
 9731: The promotion of the connection from plaintext to SSL failed
 9732: <err> is the reason for the failure.  There are two
 9733: system calls involved in the promotion (one of which failed), 
 9734: a dup to produce
 9735: a second fd on the raw socket over which the encrypted data
 9736: will flow and IO::SOcket::SSL->new_from_fd which creates
 9737: the SSL connection on the duped fd.
 9738: 
 9739: =item (Blue)   WARNING client did not respond to challenge 
 9740: 
 9741: This occurs on an insecure (non SSL) connection negotiation request.
 9742: lond generates some number from the time, the PID and sends it to
 9743: the client.  The client must respond by echoing this information back.
 9744: If the client does not do so, that's a violation of the challenge
 9745: protocols and the connection will be failed.
 9746: 
 9747: =item (Red) No manager table. Nobody can manage!!    
 9748: 
 9749: lond has the concept of privileged hosts that
 9750: can perform remote management function such
 9751: as update the hosts.tab.   The manager hosts
 9752: are described in the 
 9753: ~httpd/lonTabs/managers.tab file.
 9754: this message is logged if this file is missing.
 9755: 
 9756: 
 9757: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
 9758: 
 9759: Reports the successful parse and registration
 9760: of a specific manager. 
 9761: 
 9762: =item Green existing host <clustername:dnsname>  
 9763: 
 9764: The manager host is already defined in the hosts.tab
 9765: the information in that table, rather than the info in the
 9766: manager table will be used to determine the manager's ip.
 9767: 
 9768: =item (Red) Unable to craete <filename>                 
 9769: 
 9770: lond has been asked to create new versions of an administrative
 9771: file (by a manager).  When this is done, the new file is created
 9772: in a temp file and then renamed into place so that there are always
 9773: usable administrative files, even if the update fails.  This failure
 9774: message means that the temp file could not be created.
 9775: The update is abandoned, and the old file is available for use.
 9776: 
 9777: =item (Green) CopyFile from <oldname> to <newname> failed
 9778: 
 9779: In an update of administrative files, the copy of the existing file to a
 9780: backup file failed.  The installation of the new file may still succeed,
 9781: but there will not be a back up file to rever to (this should probably
 9782: be yellow).
 9783: 
 9784: =item (Green) Pushfile: backed up <oldname> to <newname>
 9785: 
 9786: See above, the backup of the old administrative file succeeded.
 9787: 
 9788: =item (Red)  Pushfile: Unable to install <filename> <reason>
 9789: 
 9790: The new administrative file could not be installed.  In this case,
 9791: the old administrative file is still in use.
 9792: 
 9793: =item (Green) Installed new < filename>.                      
 9794: 
 9795: The new administrative file was successfullly installed.                                               
 9796: 
 9797: =item (Red) Reinitializing lond pid=<pid>                    
 9798: 
 9799: The lonc child process <pid> will be sent a USR2 
 9800: signal.
 9801: 
 9802: =item (Red) Reinitializing self                                    
 9803: 
 9804: We've been asked to re-read our administrative files,and
 9805: are doing so.
 9806: 
 9807: =item (Yellow) error:Invalid process identifier <ident>  
 9808: 
 9809: A reinit command was received, but the target part of the 
 9810: command was not valid.  It must be either
 9811: 'lond' or 'lonc' but was <ident>
 9812: 
 9813: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
 9814: 
 9815: Checking to see if lond has been handed a valid edit
 9816: command.  It is possible the edit command is not valid
 9817: in that case there are no log messages to indicate that.
 9818: 
 9819: =item Result of password change for  <username> pwchange_success
 9820: 
 9821: The password for <username> was
 9822: successfully changed.
 9823: 
 9824: =item Unable to open <user> passwd to change password
 9825: 
 9826: Could not rewrite the 
 9827: internal password file for a user
 9828: 
 9829: =item Result of password change for <user> : <result>
 9830: 
 9831: A unix password change for <user> was attempted 
 9832: and the pipe returned <result>  
 9833: 
 9834: =item LWP GET: <message> for <fname> (<remoteurl>)
 9835: 
 9836: The lightweight process fetch for a resource failed
 9837: with <message> the local filename that should
 9838: have existed/been created was  <fname> the
 9839: corresponding URI: <remoteurl>  This is emitted in several
 9840: places.
 9841: 
 9842: =item Unable to move <transname> to <destname>     
 9843: 
 9844: From fetch_user_file_handler - the user file was replicated but could not
 9845: be mv'd to its final location.
 9846: 
 9847: =item Looking for <domain> <username>              
 9848: 
 9849: From user_has_session_handler - This should be a Debug call instead
 9850: it indicates lond is about to check whether the specified user has a 
 9851: session active on the specified domain on the local host.
 9852: 
 9853: =item Client <ip> (<name>) hanging up: <input>     
 9854: 
 9855: lond has been asked to exit by its client.  The <ip> and <name> identify the
 9856: client systemand <input> is the full exit command sent to the server.
 9857: 
 9858: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
 9859: 
 9860: A lond child terminated.  NOte that this termination can also occur when the
 9861: child receives the QUIT or DIE signals.  <pid> is the process id of the child,
 9862: <hostname> the host lond is working for, and <message> the reason the child died
 9863: to the best of our ability to get it (I would guess that any numeric value
 9864: represents and errno value).  This is immediately followed by
 9865: 
 9866: =item  Famous last words: Catching exception - <log> 
 9867: 
 9868: Where log is some recent information about the state of the child.
 9869: 
 9870: =item Red CRITICAL: TIME OUT <pid>                     
 9871: 
 9872: Some timeout occured for server <pid>.  THis is normally a timeout on an LWP
 9873: doing an HTTP::GET.
 9874: 
 9875: =item child <pid> died                              
 9876: 
 9877: The reaper caught a SIGCHILD for the lond child process <pid>
 9878: This should be modified to also display the IP of the dying child
 9879: $children{$pid}
 9880: 
 9881: =item Unknown child 0 died                           
 9882: A child died but the wait for it returned a pid of zero which really should not
 9883: ever happen. 
 9884: 
 9885: =item Child <which> - <pid> looks like we missed it's death 
 9886: 
 9887: When a sigchild is received, the reaper process checks all children to see if they are
 9888: alive.  If children are dying quite quickly, the lack of signal queuing can mean
 9889: that a signal hearalds the death of more than one child.  If so this message indicates
 9890: which other one died. <which> is the ip of a dead child
 9891: 
 9892: =item Free socket: <shutdownretval>                
 9893: 
 9894: The HUNTSMAN sub was called due to a SIGINT in a child process.  The socket is being shutdown.
 9895: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
 9896: to return anything. This is followed by: 
 9897: 
 9898: =item Red CRITICAL: Shutting down                       
 9899: 
 9900: Just prior to exit.
 9901: 
 9902: =item Free socket: <shutdownretval>                 
 9903: 
 9904: The HUPSMAN sub was called due to a SIGHUP.  all children get killsed, and lond execs itself.
 9905: This is followed by:
 9906: 
 9907: =item (Red) CRITICAL: Restarting                         
 9908: 
 9909: lond is about to exec itself to restart.
 9910: 
 9911: =item (Blue) Updating connections                        
 9912: 
 9913: (In response to a USR2).  All the children (except the one for localhost)
 9914: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
 9915: 
 9916: =item (Blue) UpdateHosts killing child <pid> for ip <ip>   
 9917: 
 9918: Due to USR2 as above.
 9919: 
 9920: =item (Green) keeping child for ip <ip> (pid = <pid>)    
 9921: 
 9922: In response to USR2 as above, the child indicated is not being restarted because
 9923: it's assumed that we'll always need a child for the localhost.
 9924: 
 9925: 
 9926: =item Going to check on the children                
 9927: 
 9928: Parent is about to check on the health of the child processes.
 9929: Note that this is in response to a USR1 sent to the parent lond.
 9930: there may be one or more of the next two messages:
 9931: 
 9932: =item <pid> is dead                                 
 9933: 
 9934: A child that we have in our child hash as alive has evidently died.
 9935: 
 9936: =item  Child <pid> did not respond                   
 9937: 
 9938: In the health check the child <pid> did not update/produce a pid_.txt
 9939: file when sent it's USR1 signal.  That process is killed with a 9 signal, as it's
 9940: assumed to be hung in some un-fixable way.
 9941: 
 9942: =item Finished checking children                   
 9943: 
 9944: Master processs's USR1 processing is cojmplete.
 9945: 
 9946: =item (Red) CRITICAL: ------- Starting ------            
 9947: 
 9948: (There are more '-'s on either side).  Lond has forked itself off to 
 9949: form a new session and is about to start actual initialization.
 9950: 
 9951: =item (Green) Attempting to start child (<client>)       
 9952: 
 9953: Started a new child process for <client>.  Client is IO::Socket object
 9954: connected to the child.  This was as a result of a TCP/IP connection from a client.
 9955: 
 9956: =item Unable to determine who caller was, getpeername returned nothing
 9957: 
 9958: In child process initialization.  either getpeername returned undef or
 9959: a zero sized object was returned.  Processing continues, but in my opinion,
 9960: this should be cause for the child to exit.
 9961: 
 9962: =item Unable to determine clientip                  
 9963: 
 9964: In child process initialization.  The peer address from getpeername was not defined.
 9965: The client address is stored as "Unavailable" and processing continues.
 9966: 
 9967: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
 9968: 
 9969: In child initialization.  A good connectionw as received from <ip>.
 9970: 
 9971: =over 2
 9972: 
 9973: =item <name> 
 9974: 
 9975: is the name of the client from hosts.tab.
 9976: 
 9977: =item <type> 
 9978: 
 9979: Is the connection type which is either 
 9980: 
 9981: =over 2
 9982: 
 9983: =item manager 
 9984: 
 9985: The connection is from a manager node, not in hosts.tab
 9986: 
 9987: =item client  
 9988: 
 9989: the connection is from a non-manager in the hosts.tab
 9990: 
 9991: =item both
 9992: 
 9993: The connection is from a manager in the hosts.tab.
 9994: 
 9995: =back
 9996: 
 9997: =back
 9998: 
 9999: =item (Blue) Certificates not installed -- trying insecure auth
10000: 
10001: One of the certificate file, key file or
10002: certificate authority file could not be found for a client attempting
10003: SSL connection intiation.  COnnection will be attemptied in in-secure mode.
10004: (this would be a system with an up to date lond that has not gotten a 
10005: certificate from us).
10006: 
10007: =item (Green)  Successful local authentication            
10008: 
10009: A local connection successfully negotiated the encryption key. 
10010: In this case the IDEA key is in a file (that is hopefully well protected).
10011: 
10012: =item (Green) Successful ssl authentication with <client>  
10013: 
10014: The client (<client> is the peer's name in hosts.tab), has successfully
10015: negotiated an SSL connection with this child process.
10016: 
10017: =item (Green) Successful insecure authentication with <client>
10018: 
10019: 
10020: The client has successfully negotiated an  insecure connection withthe child process.
10021: 
10022: =item (Yellow) Attempted insecure connection disallowed    
10023: 
10024: The client attempted and failed to successfully negotiate a successful insecure
10025: connection.  This can happen either because the variable londAllowInsecure is false
10026: or undefined, or becuse the child did not successfully echo back the challenge
10027: string.
10028: 
10029: 
10030: =back
10031: 
10032: =back
10033: 
10034: 
10035: =cut

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