Annotation of loncom/lond, revision 1.529

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

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