Annotation of loncom/lond, revision 1.543

1.1       albertel    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60      www         4: #
1.543   ! raeburn     5: # $Id: lond,v 1.542 2018/02/01 04:50:41 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.532     raeburn    38: use Socket;
1.1       albertel   39: use IO::Socket;
                     40: use IO::File;
1.126     albertel   41: #use Apache::File;
1.1       albertel   42: use POSIX;
                     43: use Crypt::IDEA;
1.523     raeburn    44: use HTTP::Request;
1.347     raeburn    45: use Digest::MD5 qw(md5_hex);
1.3       www        46: use GDBM_File;
1.91      albertel   47: use Authen::Krb5;
1.49      albertel   48: use localauth;
1.193     raeburn    49: use localenroll;
1.265     albertel   50: use localstudentphoto;
1.143     foxr       51: use File::Copy;
1.292     albertel   52: use File::Find;
1.200     matthew    53: use LONCAPA::lonlocal;
                     54: use LONCAPA::lonssl;
1.221     albertel   55: use Fcntl qw(:flock);
1.383     raeburn    56: use Apache::lonnet;
1.472     raeburn    57: use Mail::Send;
1.518     raeburn    58: use Crypt::Eksblowfish::Bcrypt;
                     59: use Digest::SHA;
                     60: use Encode;
1.523     raeburn    61: use LONCAPA::LWPReq;
1.1       albertel   62: 
1.463     foxr       63: my $DEBUG = 0;		       # Non zero to enable debug log entries.
1.77      foxr       64: 
1.57      www        65: my $status='';
                     66: my $lastlog='';
                     67: 
1.543   ! raeburn    68: my $VERSION='$Revision: 1.542 $'; #' stupid emacs
1.121     albertel   69: my $remoteVERSION;
1.214     foxr       70: my $currenthostid="default";
1.115     albertel   71: my $currentdomainid;
1.134     albertel   72: 
                     73: my $client;
1.200     matthew    74: my $clientip;			# IP address of client.
                     75: my $clientname;			# LonCAPA name of client.
1.448     raeburn    76: my $clientversion;              # LonCAPA version running on client.
                     77: my $clienthomedom;              # LonCAPA domain of homeID for client. 
1.525     raeburn    78: my $clientintdom;               # LonCAPA "internet domain" for client.
1.532     raeburn    79: my $clientsamedom;              # LonCAPA domain same for this host 
                     80:                                 # and client.
1.525     raeburn    81: my $clientsameinst;             # LonCAPA "internet domain" same for 
                     82:                                 # this host and client.
                     83: my $clientremoteok;             # Client allowed to host domain's users.
                     84:                                 # (version constraints ignored), not set
                     85:                                 # if this host and client share "internet domain". 
                     86: my %clientprohibited;           # Actions prohibited on client;
                     87:  
1.134     albertel   88: my $server;
1.200     matthew    89: 
                     90: my $keymode;
1.198     foxr       91: 
1.207     foxr       92: my $cipher;			# Cipher key negotiated with client
                     93: my $tmpsnum = 0;		# Id of tmpputs.
                     94: 
1.178     foxr       95: # 
                     96: #   Connection type is:
                     97: #      client                   - All client actions are allowed
                     98: #      manager                  - only management functions allowed.
                     99: #      both                     - Both management and client actions are allowed
                    100: #
1.161     foxr      101: 
1.178     foxr      102: my $ConnectionType;
1.161     foxr      103: 
1.178     foxr      104: my %managers;			# Ip -> manager names
1.161     foxr      105: 
1.178     foxr      106: my %perlvar;			# Will have the apache conf defined perl vars.
1.134     albertel  107: 
1.532     raeburn   108: my %secureconf;                 # Will have requirements for security 
                    109:                                 # of lond connections
                    110: 
1.480     raeburn   111: my $dist;
                    112: 
1.178     foxr      113: #
1.207     foxr      114: #   The hash below is used for command dispatching, and is therefore keyed on the request keyword.
                    115: #    Each element of the hash contains a reference to an array that contains:
                    116: #          A reference to a sub that executes the request corresponding to the keyword.
                    117: #          A flag that is true if the request must be encoded to be acceptable.
                    118: #          A mask with bits as follows:
                    119: #                      CLIENT_OK    - Set when the function is allowed by ordinary clients
                    120: #                      MANAGER_OK   - Set when the function is allowed to manager clients.
                    121: #
                    122: my $CLIENT_OK  = 1;
                    123: my $MANAGER_OK = 2;
                    124: my %Dispatcher;
                    125: 
                    126: 
                    127: #
1.178     foxr      128: #  The array below are password error strings."
                    129: #
                    130: my $lastpwderror    = 13;		# Largest error number from lcpasswd.
                    131: my @passwderrors = ("ok",
1.287     foxr      132: 		   "pwchange_failure - lcpasswd must be run as user 'www'",
                    133: 		   "pwchange_failure - lcpasswd got incorrect number of arguments",
                    134: 		   "pwchange_failure - lcpasswd did not get the right nubmer of input text lines",
                    135: 		   "pwchange_failure - lcpasswd too many simultaneous pwd changes in progress",
                    136: 		   "pwchange_failure - lcpasswd User does not exist.",
                    137: 		   "pwchange_failure - lcpasswd Incorrect current passwd",
                    138: 		   "pwchange_failure - lcpasswd Unable to su to root.",
                    139: 		   "pwchange_failure - lcpasswd Cannot set new passwd.",
                    140: 		   "pwchange_failure - lcpasswd Username has invalid characters",
                    141: 		   "pwchange_failure - lcpasswd Invalid characters in password",
                    142: 		   "pwchange_failure - lcpasswd User already exists", 
                    143:                    "pwchange_failure - lcpasswd Something went wrong with user addition.",
                    144: 		   "pwchange_failure - lcpasswd Password mismatch",
                    145: 		   "pwchange_failure - lcpasswd Error filename is invalid");
1.97      foxr      146: 
                    147: 
1.412     foxr      148: # This array are the errors from lcinstallfile:
                    149: 
                    150: my @installerrors = ("ok",
                    151: 		     "Initial user id of client not that of www",
                    152: 		     "Usage error, not enough command line arguments",
1.500     bisitz    153: 		     "Source filename does not exist",
                    154: 		     "Destination filename does not exist",
1.412     foxr      155: 		     "Some file operation failed",
                    156: 		     "Invalid table filename."
                    157: 		     );
1.207     foxr      158: 
                    159: #
1.525     raeburn   160: # The %trust hash classifies commands according to type of trust 
                    161: # required for execution of the command.
                    162: #
                    163: # When clients from a different institution request execution of a
                    164: # particular command, the trust settings for that institution set
                    165: # for this domain (or default domain for a multi-domain server) will
                    166: # be checked to see if running the command is allowed.
                    167: #
                    168: # Trust types which depend on the "Trust" domain configuration
                    169: # for the machine's default domain are:
                    170: #
                    171: # content   ("Access to this domain's content by others")
                    172: # shared    ("Access to other domain's content by this domain")
                    173: # enroll    ("Enrollment in this domain's courses by others")
                    174: # coaurem   ("Co-author roles for this domain's users elsewhere")
                    175: # domroles  ("Domain roles in this domain assignable to others")
                    176: # catalog   ("Course Catalog for this domain displayed elsewhere")
                    177: # reqcrs    ("Requests for creation of courses in this domain by others")
                    178: # msg       ("Users in other domains can send messages to this domain")
                    179: # 
                    180: # Trust type which depends on the User Session Hosting (remote) 
                    181: # domain configuration for machine's default domain is: "remote".
                    182: #
                    183: # Trust types which depend on contents of manager.tab in 
                    184: # /home/httpd/lonTabs is: "manageronly".
                    185: # 
                    186: # Trust type which requires client to share the same LON-CAPA
                    187: # "internet domain" (i.e., same institution as this server) is:
                    188: # "institutiononly".
                    189: #
                    190: 
                    191: my %trust = (
                    192:                auth => {remote => 1},
                    193:                autocreatepassword => {remote => 1},
                    194:                autocrsreqchecks => {remote => 1, reqcrs => 1},
                    195:                autocrsrequpdate => {remote => 1},
                    196:                autocrsreqvalidation => {remote => 1},
                    197:                autogetsections => {remote => 1},
                    198:                autoinstcodedefaults => {remote => 1, catalog => 1},
                    199:                autoinstcodeformat => {remote => 1, catalog => 1},
                    200:                autonewcourse => {remote => 1, reqcrs => 1},
                    201:                autophotocheck => {remote => 1, enroll => 1},
                    202:                autophotochoice => {remote => 1},
                    203:                autophotopermission => {remote => 1, enroll => 1},
                    204:                autopossibleinstcodes => {remote => 1, reqcrs => 1},
                    205:                autoretrieve => {remote => 1, enroll => 1, catalog => 1},
                    206:                autorun => {remote => 1, enroll => 1, reqcrs => 1},
                    207:                autovalidateclass_sec => {catalog => 1},
                    208:                autovalidatecourse => {remote => 1, enroll => 1},
                    209:                autovalidateinstcode => {domroles => 1, remote => 1, enroll => 1},
                    210:                changeuserauth => {remote => 1, domroles => 1},
                    211:                chatretr => {remote => 1, enroll => 1},
                    212:                chatsend => {remote => 1, enroll => 1},
                    213:                courseiddump => {remote => 1, domroles => 1, enroll => 1},
                    214:                courseidput => {remote => 1, domroles => 1, enroll => 1},
                    215:                courseidputhash => {remote => 1, domroles => 1, enroll => 1},
                    216:                courselastaccess => {remote => 1, domroles => 1, enroll => 1},
                    217:                currentauth => {remote => 1, domroles => 1, enroll => 1},
                    218:                currentdump => {remote => 1, enroll => 1},
                    219:                currentversion => {remote=> 1, content => 1},
                    220:                dcmaildump => {remote => 1, domroles => 1},
                    221:                dcmailput => {remote => 1, domroles => 1},
                    222:                del => {remote => 1, domroles => 1, enroll => 1, content => 1},
                    223:                deldom => {remote => 1, domroles => 1}, # not currently used
                    224:                devalidatecache => {institutiononly => 1},
                    225:                domroleput => {remote => 1, enroll => 1},
                    226:                domrolesdump => {remote => 1, catalog => 1},
                    227:                du => {remote => 1, enroll => 1},
                    228:                du2 => {remote => 1, enroll => 1},
                    229:                dump => {remote => 1, enroll => 1, domroles => 1},
                    230:                edit => {institutiononly => 1},  #not used currently
                    231:                eget => {remote => 1, domroles => 1, enroll => 1}, #not used currently
1.536     raeburn   232:                egetdom => {remote => 1, domroles => 1, enroll => 1, },
1.525     raeburn   233:                ekey => {}, #not used currently
                    234:                exit => {anywhere => 1},
                    235:                fetchuserfile => {remote => 1, enroll => 1},
                    236:                get => {remote => 1, domroles => 1, enroll => 1},
                    237:                getdom => {anywhere => 1},
                    238:                home => {anywhere => 1},
                    239:                iddel => {remote => 1, enroll => 1},
                    240:                idget => {remote => 1, enroll => 1},
                    241:                idput => {remote => 1, domroles => 1, enroll => 1},
                    242:                inc => {remote => 1, enroll => 1},
                    243:                init => {anywhere => 1},
                    244:                inst_usertypes => {remote => 1, domroles => 1, enroll => 1},
                    245:                instemailrules => {remote => 1, domroles => 1},
                    246:                instidrulecheck => {remote => 1, domroles => 1,},
                    247:                instidrules => {remote => 1, domroles => 1,},
                    248:                instrulecheck => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
                    249:                instselfcreatecheck => {institutiononly => 1},
                    250:                instuserrules => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
                    251:                keys => {remote => 1,},
                    252:                load => {anywhere => 1},
                    253:                log => {anywhere => 1},
                    254:                ls => {remote => 1, enroll => 1, content => 1,},
                    255:                ls2 => {remote => 1, enroll => 1, content => 1,},
                    256:                ls3 => {remote => 1, enroll => 1, content => 1,},
                    257:                makeuser => {remote => 1, enroll => 1, domroles => 1,},
                    258:                mkdiruserfile => {remote => 1, enroll => 1,},
                    259:                newput => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1,},
                    260:                passwd => {remote => 1},
                    261:                ping => {anywhere => 1},
                    262:                pong => {anywhere => 1},
                    263:                pushfile => {manageronly => 1},
                    264:                put => {remote => 1, enroll => 1, domroles => 1, msg => 1, content => 1, shared => 1},
                    265:                putdom => {remote => 1, domroles => 1,},
                    266:                putstore => {remote => 1, enroll => 1},
                    267:                queryreply => {anywhere => 1},
                    268:                querysend => {anywhere => 1},
1.535     raeburn   269:                querysend_activitylog => {remote => 1},
                    270:                querysend_allusers => {remote => 1, domroles => 1},
                    271:                querysend_courselog => {remote => 1},
                    272:                querysend_fetchenrollment => {remote => 1},
                    273:                querysend_getinstuser => {remote => 1},
                    274:                querysend_getmultinstusers => {remote => 1},
                    275:                querysend_instdirsearch => {remote => 1, domroles => 1, coaurem => 1},
                    276:                querysend_institutionalphotos => {remote => 1},
                    277:                querysend_portfolio_metadata => {remote => 1, content => 1},
                    278:                querysend_userlog => {remote => 1, domroles => 1},
                    279:                querysend_usersearch => {remote => 1, enroll => 1, coaurem => 1},
1.525     raeburn   280:                quit => {anywhere => 1},
                    281:                readlonnetglobal => {institutiononly => 1},
                    282:                reinit => {manageronly => 1}, #not used currently
                    283:                removeuserfile => {remote => 1, enroll => 1},
                    284:                renameuserfile => {remote => 1,},
                    285:                restore => {remote => 1, enroll => 1, reqcrs => 1,},
                    286:                rolesdel => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
                    287:                rolesput => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
1.527     raeburn   288:                servercerts => {institutiononly => 1},
1.528     raeburn   289:                serverdistarch => {anywhere => 1},
1.525     raeburn   290:                serverhomeID => {anywhere => 1},
                    291:                serverloncaparev => {anywhere => 1},
                    292:                servertimezone => {remote => 1, enroll => 1},
                    293:                setannounce => {remote => 1, domroles => 1},
                    294:                sethost => {anywhere => 1},
                    295:                store => {remote => 1, enroll => 1, reqcrs => 1,},
                    296:                studentphoto => {remote => 1, enroll => 1},
                    297:                sub => {content => 1,},
                    298:                tmpdel => {anywhere => 1},
                    299:                tmpget => {anywhere => 1},
                    300:                tmpput => {anywhere => 1},
                    301:                tokenauthuserfile => {anywhere => 1},
                    302:                unsub => {content => 1,},
                    303:                update => {shared => 1},
                    304:                updateclickers => {remote => 1},
                    305:                userhassession => {anywhere => 1},
                    306:                userload => {anywhere => 1},
                    307:                version => {anywhere => 1}, #not used
                    308:             );
                    309: 
                    310: #
1.207     foxr      311: #   Statistics that are maintained and dislayed in the status line.
                    312: #
1.212     foxr      313: my $Transactions = 0;		# Number of attempted transactions.
                    314: my $Failures     = 0;		# Number of transcations failed.
1.207     foxr      315: 
                    316: #   ResetStatistics: 
                    317: #      Resets the statistics counters:
                    318: #
                    319: sub ResetStatistics {
                    320:     $Transactions = 0;
                    321:     $Failures     = 0;
                    322: }
                    323: 
1.200     matthew   324: #------------------------------------------------------------------------
                    325: #
                    326: #   LocalConnection
                    327: #     Completes the formation of a locally authenticated connection.
                    328: #     This function will ensure that the 'remote' client is really the
                    329: #     local host.  If not, the connection is closed, and the function fails.
                    330: #     If so, initcmd is parsed for the name of a file containing the
                    331: #     IDEA session key.  The fie is opened, read, deleted and the session
                    332: #     key returned to the caller.
                    333: #
                    334: # Parameters:
                    335: #   $Socket      - Socket open on client.
                    336: #   $initcmd     - The full text of the init command.
                    337: #
                    338: # Returns:
                    339: #     IDEA session key on success.
                    340: #     undef on failure.
                    341: #
                    342: sub LocalConnection {
                    343:     my ($Socket, $initcmd) = @_;
1.373     albertel  344:     Debug("Attempting local connection: $initcmd client: $clientip");
1.277     albertel  345:     if($clientip ne "127.0.0.1") {
1.200     matthew   346: 	&logthis('<font color="red"> LocalConnection rejecting non local: '
1.373     albertel  347: 		 ."$clientip ne 127.0.0.1 </font>");
1.200     matthew   348: 	close $Socket;
                    349: 	return undef;
1.224     foxr      350:     }  else {
1.200     matthew   351: 	chomp($initcmd);	# Get rid of \n in filename.
                    352: 	my ($init, $type, $name) = split(/:/, $initcmd);
                    353: 	Debug(" Init command: $init $type $name ");
                    354: 
                    355: 	# Require that $init = init, and $type = local:  Otherwise
                    356: 	# the caller is insane:
                    357: 
                    358: 	if(($init ne "init") && ($type ne "local")) {
                    359: 	    &logthis('<font color = "red"> LocalConnection: caller is insane! '
                    360: 		     ."init = $init, and type = $type </font>");
                    361: 	    close($Socket);;
                    362: 	    return undef;
                    363: 		
                    364: 	}
                    365: 	#  Now get the key filename:
                    366: 
                    367: 	my $IDEAKey = lonlocal::ReadKeyFile($name);
                    368: 	return $IDEAKey;
                    369:     }
                    370: }
                    371: #------------------------------------------------------------------------------
                    372: #
                    373: #  SSLConnection
                    374: #   Completes the formation of an ssh authenticated connection. The
                    375: #   socket is promoted to an ssl socket.  If this promotion and the associated
                    376: #   certificate exchange are successful, the IDEA key is generated and sent
                    377: #   to the remote peer via the SSL tunnel. The IDEA key is also returned to
                    378: #   the caller after the SSL tunnel is torn down.
                    379: #
                    380: # Parameters:
                    381: #   Name              Type             Purpose
                    382: #   $Socket          IO::Socket::INET  Plaintext socket.
                    383: #
                    384: # Returns:
                    385: #    IDEA key on success.
                    386: #    undef on failure.
                    387: #
                    388: sub SSLConnection {
                    389:     my $Socket   = shift;
                    390: 
                    391:     Debug("SSLConnection: ");
                    392:     my $KeyFile         = lonssl::KeyFile();
                    393:     if(!$KeyFile) {
                    394: 	my $err = lonssl::LastError();
                    395: 	&logthis("<font color=\"red\"> CRITICAL"
                    396: 		 ."Can't get key file $err </font>");
                    397: 	return undef;
                    398:     }
                    399:     my ($CACertificate,
                    400: 	$Certificate) = lonssl::CertificateFile();
                    401: 
                    402: 
                    403:     # If any of the key, certificate or certificate authority 
                    404:     # certificate filenames are not defined, this can't work.
                    405: 
                    406:     if((!$Certificate) || (!$CACertificate)) {
                    407: 	my $err = lonssl::LastError();
                    408: 	&logthis("<font color=\"red\"> CRITICAL"
                    409: 		 ."Can't get certificates: $err </font>");
                    410: 
                    411: 	return undef;
                    412:     }
                    413:     Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
                    414: 
                    415:     # Indicate to our peer that we can procede with
                    416:     # a transition to ssl authentication:
                    417: 
                    418:     print $Socket "ok:ssl\n";
                    419: 
                    420:     Debug("Approving promotion -> ssl");
                    421:     #  And do so:
                    422: 
                    423:     my $SSLSocket = lonssl::PromoteServerSocket($Socket,
                    424: 						$CACertificate,
                    425: 						$Certificate,
                    426: 						$KeyFile);
                    427:     if(! ($SSLSocket) ) {	# SSL socket promotion failed.
                    428: 	my $err = lonssl::LastError();
                    429: 	&logthis("<font color=\"red\"> CRITICAL "
                    430: 		 ."SSL Socket promotion failed: $err </font>");
                    431: 	return undef;
                    432:     }
                    433:     Debug("SSL Promotion successful");
                    434: 
                    435:     # 
                    436:     #  The only thing we'll use the socket for is to send the IDEA key
                    437:     #  to the peer:
                    438: 
                    439:     my $Key = lonlocal::CreateCipherKey();
                    440:     print $SSLSocket "$Key\n";
                    441: 
                    442:     lonssl::Close($SSLSocket); 
                    443: 
                    444:     Debug("Key exchange complete: $Key");
                    445: 
                    446:     return $Key;
                    447: }
                    448: #
                    449: #     InsecureConnection: 
                    450: #        If insecure connections are allowd,
                    451: #        exchange a challenge with the client to 'validate' the
                    452: #        client (not really, but that's the protocol):
                    453: #        We produce a challenge string that's sent to the client.
                    454: #        The client must then echo the challenge verbatim to us.
                    455: #
                    456: #  Parameter:
                    457: #      Socket      - Socket open on the client.
                    458: #  Returns:
                    459: #      1           - success.
                    460: #      0           - failure (e.g.mismatch or insecure not allowed).
                    461: #
                    462: sub InsecureConnection {
                    463:     my $Socket  =  shift;
                    464: 
                    465:     #   Don't even start if insecure connections are not allowed.
1.532     raeburn   466:     #   return 0 if Insecure connections not allowed.
                    467:     #
                    468:     if (ref($secureconf{'connfrom'}) eq 'HASH') {
                    469:         if ($clientsamedom) {
                    470:             if ($secureconf{'connfrom'}{'dom'} eq 'req') {
                    471:                 return 0;
                    472:             } 
                    473:         } elsif ($clientsameinst) {
                    474:             if ($secureconf{'connfrom'}{'intdom'} eq 'req') {
                    475:                 return 0;
                    476:             }
                    477:         } else {
                    478:             if ($secureconf{'connfrom'}{'other'} eq 'req') {
                    479:                 return 0;
                    480:             }
                    481:         }
                    482:     } elsif (!$perlvar{londAllowInsecure}) {
1.200     matthew   483: 	return 0;
                    484:     }
                    485: 
                    486:     #   Fabricate a challenge string and send it..
                    487: 
                    488:     my $challenge = "$$".time;	# pid + time.
                    489:     print $Socket "$challenge\n";
                    490:     &status("Waiting for challenge reply");
                    491: 
                    492:     my $answer = <$Socket>;
                    493:     $answer    =~s/\W//g;
                    494:     if($challenge eq $answer) {
                    495: 	return 1;
1.224     foxr      496:     } else {
1.200     matthew   497: 	logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
                    498: 	&status("No challenge reqply");
                    499: 	return 0;
                    500:     }
                    501:     
                    502: 
                    503: }
1.251     foxr      504: #
                    505: #   Safely execute a command (as long as it's not a shel command and doesn
                    506: #   not require/rely on shell escapes.   The function operates by doing a
                    507: #   a pipe based fork and capturing stdout and stderr  from the pipe.
                    508: #
                    509: # Formal Parameters:
                    510: #     $line                    - A line of text to be executed as a command.
                    511: # Returns:
                    512: #     The output from that command.  If the output is multiline the caller
                    513: #     must know how to split up the output.
                    514: #
                    515: #
                    516: sub execute_command {
                    517:     my ($line)    = @_;
                    518:     my @words     = split(/\s/, $line);	# Bust the command up into words.
                    519:     my $output    = "";
                    520: 
                    521:     my $pid = open(CHILD, "-|");
                    522:     
                    523:     if($pid) {			# Parent process
                    524: 	Debug("In parent process for execute_command");
                    525: 	my @data = <CHILD>;	# Read the child's outupt...
                    526: 	close CHILD;
                    527: 	foreach my $output_line (@data) {
                    528: 	    Debug("Adding $output_line");
                    529: 	    $output .= $output_line; # Presumably has a \n on it.
                    530: 	}
                    531: 
                    532:     } else {			# Child process
                    533: 	close (STDERR);
                    534: 	open  (STDERR, ">&STDOUT");# Combine stderr, and stdout...
                    535: 	exec(@words);		# won't return.
                    536:     }
                    537:     return $output;
                    538: }
                    539: 
1.200     matthew   540: 
1.140     foxr      541: #   GetCertificate: Given a transaction that requires a certificate,
                    542: #   this function will extract the certificate from the transaction
                    543: #   request.  Note that at this point, the only concept of a certificate
                    544: #   is the hostname to which we are connected.
                    545: #
                    546: #   Parameter:
                    547: #      request   - The request sent by our client (this parameterization may
                    548: #                  need to change when we really use a certificate granting
                    549: #                  authority.
                    550: #
                    551: sub GetCertificate {
                    552:     my $request = shift;
                    553: 
                    554:     return $clientip;
                    555: }
1.161     foxr      556: 
1.178     foxr      557: #
                    558: #   Return true if client is a manager.
                    559: #
                    560: sub isManager {
                    561:     return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
                    562: }
                    563: #
                    564: #   Return tru if client can do client functions
                    565: #
                    566: sub isClient {
                    567:     return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
                    568: }
1.161     foxr      569: 
                    570: 
1.156     foxr      571: #
                    572: #   ReadManagerTable: Reads in the current manager table. For now this is
                    573: #                     done on each manager authentication because:
                    574: #                     - These authentications are not frequent
                    575: #                     - This allows dynamic changes to the manager table
                    576: #                       without the need to signal to the lond.
                    577: #
                    578: sub ReadManagerTable {
                    579: 
1.412     foxr      580:     &Debug("Reading manager table");
1.156     foxr      581:     #   Clean out the old table first..
                    582: 
1.166     foxr      583:    foreach my $key (keys %managers) {
                    584:       delete $managers{$key};
                    585:    }
                    586: 
                    587:    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
                    588:    if (!open (MANAGERS, $tablename)) {
1.473     raeburn   589:        my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
                    590:        if (&Apache::lonnet::is_LC_dns($hostname)) {
1.472     raeburn   591:            &logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
                    592:        }
                    593:        return;
1.166     foxr      594:    }
                    595:    while(my $host = <MANAGERS>) {
                    596:       chomp($host);
                    597:       if ($host =~ "^#") {                  # Comment line.
                    598:          next;
                    599:       }
1.368     albertel  600:       if (!defined &Apache::lonnet::get_host_ip($host)) { # This is a non cluster member
1.161     foxr      601: 	    #  The entry is of the form:
                    602: 	    #    cluname:hostname
                    603: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
                    604: 	    #            the host key.
                    605: 	    #  hostname- The dns name of the host.
                    606: 	    #
1.166     foxr      607:           my($cluname, $dnsname) = split(/:/, $host);
                    608:           
                    609:           my $ip = gethostbyname($dnsname);
                    610:           if(defined($ip)) {                 # bad names don't deserve entry.
                    611:             my $hostip = inet_ntoa($ip);
                    612:             $managers{$hostip} = $cluname;
                    613:             logthis('<font color="green"> registering manager '.
                    614:                     "$dnsname as $cluname with $hostip </font>\n");
                    615:          }
                    616:       } else {
                    617:          logthis('<font color="green"> existing host'." $host</font>\n");
1.472     raeburn   618:          $managers{&Apache::lonnet::get_host_ip($host)} = $host;  # Use info from cluster tab if cluster memeber
1.166     foxr      619:       }
                    620:    }
1.156     foxr      621: }
1.140     foxr      622: 
                    623: #
                    624: #  ValidManager: Determines if a given certificate represents a valid manager.
                    625: #                in this primitive implementation, the 'certificate' is
                    626: #                just the connecting loncapa client name.  This is checked
                    627: #                against a valid client list in the configuration.
                    628: #
                    629: #                  
                    630: sub ValidManager {
                    631:     my $certificate = shift; 
                    632: 
1.163     foxr      633:     return isManager;
1.140     foxr      634: }
                    635: #
1.143     foxr      636: #  CopyFile:  Called as part of the process of installing a 
                    637: #             new configuration file.  This function copies an existing
                    638: #             file to a backup file.
                    639: # Parameters:
                    640: #     oldfile  - Name of the file to backup.
                    641: #     newfile  - Name of the backup file.
                    642: # Return:
                    643: #     0   - Failure (errno has failure reason).
                    644: #     1   - Success.
                    645: #
                    646: sub CopyFile {
1.192     foxr      647: 
                    648:     my ($oldfile, $newfile) = @_;
1.143     foxr      649: 
1.281     matthew   650:     if (! copy($oldfile,$newfile)) {
                    651:         return 0;
1.143     foxr      652:     }
1.281     matthew   653:     chmod(0660, $newfile);
                    654:     return 1;
1.143     foxr      655: }
1.157     foxr      656: #
                    657: #  Host files are passed out with externally visible host IPs.
                    658: #  If, for example, we are behind a fire-wall or NAT host, our 
                    659: #  internally visible IP may be different than the externally
                    660: #  visible IP.  Therefore, we always adjust the contents of the
                    661: #  host file so that the entry for ME is the IP that we believe
                    662: #  we have.  At present, this is defined as the entry that
                    663: #  DNS has for us.  If by some chance we are not able to get a
                    664: #  DNS translation for us, then we assume that the host.tab file
                    665: #  is correct.  
                    666: #    BUGBUGBUG - in the future, we really should see if we can
                    667: #       easily query the interface(s) instead.
                    668: # Parameter(s):
                    669: #     contents    - The contents of the host.tab to check.
                    670: # Returns:
                    671: #     newcontents - The adjusted contents.
                    672: #
                    673: #
                    674: sub AdjustHostContents {
                    675:     my $contents  = shift;
                    676:     my $adjusted;
                    677:     my $me        = $perlvar{'lonHostID'};
                    678: 
1.354     albertel  679:     foreach my $line (split(/\n/,$contents)) {
1.472     raeburn   680: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/) ||
                    681:              ($line =~ /^\s*\^/))) {
1.157     foxr      682: 	    chomp($line);
                    683: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
                    684: 	    if ($id eq $me) {
1.354     albertel  685: 		my $ip = gethostbyname($name);
                    686: 		my $ipnew = inet_ntoa($ip);
                    687: 		$ip = $ipnew;
1.157     foxr      688: 		#  Reconstruct the host line and append to adjusted:
                    689: 		
1.354     albertel  690: 		my $newline = "$id:$domain:$role:$name:$ip";
                    691: 		if($maxcon ne "") { # Not all hosts have loncnew tuning params
                    692: 		    $newline .= ":$maxcon:$idleto:$mincon";
                    693: 		}
                    694: 		$adjusted .= $newline."\n";
1.157     foxr      695: 		
1.354     albertel  696: 	    } else {		# Not me, pass unmodified.
                    697: 		$adjusted .= $line."\n";
                    698: 	    }
1.157     foxr      699: 	} else {                  # Blank or comment never re-written.
                    700: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
                    701: 	}
1.354     albertel  702:     }
                    703:     return $adjusted;
1.157     foxr      704: }
1.143     foxr      705: #
                    706: #   InstallFile: Called to install an administrative file:
1.412     foxr      707: #       - The file is created int a temp directory called <name>.tmp
                    708: #       - lcinstall file is called to install the file.
                    709: #         since the web app has no direct write access to the table directory
1.143     foxr      710: #
                    711: #  Parameters:
                    712: #       Name of the file
                    713: #       File Contents.
                    714: #  Return:
                    715: #      nonzero - success.
                    716: #      0       - failure and $! has an errno.
1.412     foxr      717: # Assumptions:
                    718: #    File installtion is a relatively infrequent
1.143     foxr      719: #
                    720: sub InstallFile {
1.192     foxr      721: 
                    722:     my ($Filename, $Contents) = @_;
1.412     foxr      723: #     my $TempFile = $Filename.".tmp";
                    724:     my $exedir = $perlvar{'lonDaemons'};
                    725:     my $tmpdir = $exedir.'/tmp/';
                    726:     my $TempFile = $tmpdir."TempTableFile.tmp";
1.143     foxr      727: 
                    728:     #  Open the file for write:
                    729: 
                    730:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
                    731:     if(!(defined $fh)) {
                    732: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
                    733: 	return 0;
                    734:     }
                    735:     #  write the contents of the file:
                    736: 
                    737:     print $fh ($Contents); 
                    738:     $fh->close;			# In case we ever have a filesystem w. locking
                    739: 
1.412     foxr      740:     chmod(0664, $TempFile);	# Everyone can write it.
                    741: 
                    742:     # Use lcinstall file to put the file in the table directory...
                    743: 
                    744:     &Debug("Opening pipe to $exedir/lcinstallfile $TempFile $Filename");
                    745:     my $pf = IO::File->new("| $exedir/lcinstallfile   $TempFile $Filename > $exedir/logs/lcinstallfile.log");
                    746:     close $pf;
                    747:     my $err = $?;
                    748:     &Debug("Status is $err");
                    749:     if ($err != 0) {
                    750: 	my $msg = $err;
                    751: 	if ($err < @installerrors) {
                    752: 	    $msg = $installerrors[$err];
                    753: 	}
                    754: 	&logthis("Install failed for table file $Filename : $msg");
                    755: 	return 0;
                    756:     }
                    757: 
                    758:     # Remove the temp file:
1.143     foxr      759: 
1.412     foxr      760:     unlink($TempFile);
1.143     foxr      761: 
                    762:     return 1;
                    763: }
1.200     matthew   764: 
                    765: 
1.169     foxr      766: #
                    767: #   ConfigFileFromSelector: converts a configuration file selector
1.411     foxr      768: #                 into a configuration file pathname.
1.472     raeburn   769: #                 Supports the following file selectors: 
                    770: #                 hosts, domain, dns_hosts, dns_domain  
1.411     foxr      771: #
1.169     foxr      772: #
                    773: #  Parameters:
                    774: #      selector  - Configuration file selector.
                    775: #  Returns:
                    776: #      Full path to the file or undef if the selector is invalid.
                    777: #
                    778: sub ConfigFileFromSelector {
                    779:     my $selector   = shift;
                    780:     my $tablefile;
                    781: 
                    782:     my $tabledir = $perlvar{'lonTabDir'}.'/';
1.472     raeburn   783:     if (($selector eq "hosts") || ($selector eq "domain") || 
                    784:         ($selector eq "dns_hosts") || ($selector eq "dns_domain")) {
1.411     foxr      785: 	$tablefile =  $tabledir.$selector.'.tab';
1.169     foxr      786:     }
                    787:     return $tablefile;
                    788: }
1.143     foxr      789: #
1.141     foxr      790: #   PushFile:  Called to do an administrative push of a file.
                    791: #              - Ensure the file being pushed is one we support.
                    792: #              - Backup the old file to <filename.saved>
                    793: #              - Separate the contents of the new file out from the
                    794: #                rest of the request.
                    795: #              - Write the new file.
                    796: #  Parameter:
                    797: #     Request - The entire user request.  This consists of a : separated
                    798: #               string pushfile:tablename:contents.
                    799: #     NOTE:  The contents may have :'s in it as well making things a bit
                    800: #            more interesting... but not much.
                    801: #  Returns:
                    802: #     String to send to client ("ok" or "refused" if bad file).
                    803: #
                    804: sub PushFile {
1.510     raeburn   805:     my $request = shift;
1.141     foxr      806:     my ($command, $filename, $contents) = split(":", $request, 3);
1.412     foxr      807:     &Debug("PushFile");
1.141     foxr      808:     
                    809:     #  At this point in time, pushes for only the following tables are
                    810:     #  supported:
                    811:     #   hosts.tab  ($filename eq host).
                    812:     #   domain.tab ($filename eq domain).
1.472     raeburn   813:     #   dns_hosts.tab ($filename eq dns_host).
                    814:     #   dns_domain.tab ($filename eq dns_domain). 
1.141     foxr      815:     # Construct the destination filename or reject the request.
                    816:     #
                    817:     # lonManage is supposed to ensure this, however this session could be
                    818:     # part of some elaborate spoof that managed somehow to authenticate.
                    819:     #
                    820: 
1.169     foxr      821: 
                    822:     my $tablefile = ConfigFileFromSelector($filename);
                    823:     if(! (defined $tablefile)) {
1.141     foxr      824: 	return "refused";
                    825:     }
1.412     foxr      826: 
1.157     foxr      827:     #  If the file being pushed is the host file, we adjust the entry for ourself so that the
                    828:     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
                    829:     #  to conceive of conditions where we don't have a DNS entry locally.  This is possible in a 
                    830:     #  network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
                    831:     #  that possibilty.
                    832: 
                    833:     if($filename eq "host") {
                    834: 	$contents = AdjustHostContents($contents);
1.510     raeburn   835:     } elsif ($filename eq 'dns_host' || $filename eq 'dns_domain') {
                    836:         if ($contents eq '') {
                    837:             &logthis('<font color="red"> Pushfile: unable to install '
                    838:                     .$tablefile." - no data received from push. </font>");
                    839:             return 'error: push had no data';
                    840:         }
                    841:         if (&Apache::lonnet::get_host_ip($clientname)) {
                    842:             my $clienthost = &Apache::lonnet::hostname($clientname);
                    843:             if ($managers{$clientip} eq $clientname) {
                    844:                 my $clientprotocol = $Apache::lonnet::protocol{$clientname};
                    845:                 $clientprotocol = 'http' if ($clientprotocol ne 'https');
                    846:                 my $url = '/adm/'.$filename;
                    847:                 $url =~ s{_}{/};
                    848:                 my $request=new HTTP::Request('GET',"$clientprotocol://$clienthost$url");
1.523     raeburn   849:                 my $response = LONCAPA::LWPReq::makerequest($clientname,$request,'',\%perlvar,60,0);
1.510     raeburn   850:                 if ($response->is_error()) {
                    851:                     &logthis('<font color="red"> Pushfile: unable to install '
                    852:                             .$tablefile." - error attempting to pull data. </font>");
                    853:                     return 'error: pull failed';
                    854:                 } else {
                    855:                     my $result = $response->content;
                    856:                     chomp($result);
                    857:                     unless ($result eq $contents) {
                    858:                         &logthis('<font color="red"> Pushfile: unable to install '
                    859:                                 .$tablefile." - pushed data and pulled data differ. </font>");
                    860:                         my $pushleng = length($contents);
                    861:                         my $pullleng = length($result);
                    862:                         if ($pushleng != $pullleng) {
                    863:                             return "error: $pushleng vs $pullleng bytes";
                    864:                         } else {
                    865:                             return "error: mismatch push and pull";
                    866:                         }
                    867:                     }
                    868:                 }
                    869:             }
                    870:         }
1.157     foxr      871:     }
                    872: 
1.141     foxr      873:     #  Install the new file:
                    874: 
1.412     foxr      875:     &logthis("Installing new $tablefile contents:\n$contents");
1.143     foxr      876:     if(!InstallFile($tablefile, $contents)) {
                    877: 	&logthis('<font color="red"> Pushfile: unable to install '
1.145     foxr      878: 	 .$tablefile." $! </font>");
1.143     foxr      879: 	return "error:$!";
1.224     foxr      880:     } else {
1.143     foxr      881: 	&logthis('<font color="green"> Installed new '.$tablefile
1.473     raeburn   882: 		 ." - transaction by: $clientname ($clientip)</font>");
1.472     raeburn   883:         my $adminmail = $perlvar{'lonAdmEMail'};
                    884:         my $admindom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                    885:         if ($admindom ne '') {
                    886:             my %domconfig =
                    887:                 &Apache::lonnet::get_dom('configuration',['contacts'],$admindom);
                    888:             if (ref($domconfig{'contacts'}) eq 'HASH') {
                    889:                 if ($domconfig{'contacts'}{'adminemail'} ne '') {
                    890:                     $adminmail = $domconfig{'contacts'}{'adminemail'};
                    891:                 }
                    892:             }
                    893:         }
                    894:         if ($adminmail =~ /^[^\@]+\@[^\@]+$/) {
                    895:             my $msg = new Mail::Send;
                    896:             $msg->to($adminmail);
                    897:             $msg->subject('LON-CAPA DNS update on '.$perlvar{'lonHostID'});
                    898:             $msg->add('Content-type','text/plain; charset=UTF-8');
                    899:             if (my $fh = $msg->open()) {
                    900:                 print $fh 'Update to '.$tablefile.' from Cluster Manager '.
1.473     raeburn   901:                           "$clientname ($clientip)\n";
1.472     raeburn   902:                 $fh->close;
                    903:             }
                    904:         }
1.143     foxr      905:     }
                    906: 
1.141     foxr      907:     #  Indicate success:
                    908:  
                    909:     return "ok";
                    910: 
                    911: }
1.145     foxr      912: 
                    913: #
                    914: #  Called to re-init either lonc or lond.
                    915: #
                    916: #  Parameters:
                    917: #    request   - The full request by the client.  This is of the form
                    918: #                reinit:<process>  
                    919: #                where <process> is allowed to be either of 
                    920: #                lonc or lond
                    921: #
                    922: #  Returns:
                    923: #     The string to be sent back to the client either:
                    924: #   ok         - Everything worked just fine.
                    925: #   error:why  - There was a failure and why describes the reason.
                    926: #
                    927: #
                    928: sub ReinitProcess {
                    929:     my $request = shift;
                    930: 
1.146     foxr      931: 
                    932:     # separate the request (reinit) from the process identifier and
                    933:     # validate it producing the name of the .pid file for the process.
                    934:     #
                    935:     #
                    936:     my ($junk, $process) = split(":", $request);
1.147     foxr      937:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
1.146     foxr      938:     if($process eq 'lonc') {
                    939: 	$processpidfile = $processpidfile."lonc.pid";
1.147     foxr      940: 	if (!open(PIDFILE, "< $processpidfile")) {
                    941: 	    return "error:Open failed for $processpidfile";
                    942: 	}
                    943: 	my $loncpid = <PIDFILE>;
                    944: 	close(PIDFILE);
                    945: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
                    946: 		."</font>");
                    947: 	kill("USR2", $loncpid);
1.146     foxr      948:     } elsif ($process eq 'lond') {
1.147     foxr      949: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
                    950: 	&UpdateHosts;			# Lond is us!!
1.146     foxr      951:     } else {
                    952: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
                    953: 		 ."</font>");
                    954: 	return "error:Invalid process identifier $process";
                    955:     }
1.145     foxr      956:     return 'ok';
                    957: }
1.168     foxr      958: #   Validate a line in a configuration file edit script:
                    959: #   Validation includes:
                    960: #     - Ensuring the command is valid.
                    961: #     - Ensuring the command has sufficient parameters
                    962: #   Parameters:
                    963: #     scriptline - A line to validate (\n has been stripped for what it's worth).
1.167     foxr      964: #
1.168     foxr      965: #   Return:
                    966: #      0     - Invalid scriptline.
                    967: #      1     - Valid scriptline
                    968: #  NOTE:
                    969: #     Only the command syntax is checked, not the executability of the
                    970: #     command.
                    971: #
                    972: sub isValidEditCommand {
                    973:     my $scriptline = shift;
                    974: 
                    975:     #   Line elements are pipe separated:
                    976: 
                    977:     my ($command, $key, $newline)  = split(/\|/, $scriptline);
                    978:     &logthis('<font color="green"> isValideditCommand checking: '.
                    979: 	     "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
                    980:     
                    981:     if ($command eq "delete") {
                    982: 	#
                    983: 	#   key with no newline.
                    984: 	#
                    985: 	if( ($key eq "") || ($newline ne "")) {
                    986: 	    return 0;		# Must have key but no newline.
                    987: 	} else {
                    988: 	    return 1;		# Valid syntax.
                    989: 	}
1.169     foxr      990:     } elsif ($command eq "replace") {
1.168     foxr      991: 	#
                    992: 	#   key and newline:
                    993: 	#
                    994: 	if (($key eq "") || ($newline eq "")) {
                    995: 	    return 0;
                    996: 	} else {
                    997: 	    return 1;
                    998: 	}
1.169     foxr      999:     } elsif ($command eq "append") {
                   1000: 	if (($key ne "") && ($newline eq "")) {
                   1001: 	    return 1;
                   1002: 	} else {
                   1003: 	    return 0;
                   1004: 	}
1.168     foxr     1005:     } else {
                   1006: 	return 0;		# Invalid command.
                   1007:     }
                   1008:     return 0;			# Should not get here!!!
                   1009: }
1.169     foxr     1010: #
                   1011: #   ApplyEdit - Applies an edit command to a line in a configuration 
                   1012: #               file.  It is the caller's responsiblity to validate the
                   1013: #               edit line.
                   1014: #   Parameters:
                   1015: #      $directive - A single edit directive to apply.  
                   1016: #                   Edit directives are of the form:
                   1017: #                  append|newline      - Appends a new line to the file.
                   1018: #                  replace|key|newline - Replaces the line with key value 'key'
                   1019: #                  delete|key          - Deletes the line with key value 'key'.
                   1020: #      $editor   - A config file editor object that contains the
                   1021: #                  file being edited.
                   1022: #
                   1023: sub ApplyEdit {
1.192     foxr     1024: 
                   1025:     my ($directive, $editor) = @_;
1.169     foxr     1026: 
                   1027:     # Break the directive down into its command and its parameters
                   1028:     # (at most two at this point.  The meaning of the parameters, if in fact
                   1029:     #  they exist depends on the command).
                   1030: 
                   1031:     my ($command, $p1, $p2) = split(/\|/, $directive);
                   1032: 
                   1033:     if($command eq "append") {
                   1034: 	$editor->Append($p1);	          # p1 - key p2 null.
                   1035:     } elsif ($command eq "replace") {
                   1036: 	$editor->ReplaceLine($p1, $p2);   # p1 - key p2 = newline.
                   1037:     } elsif ($command eq "delete") {
                   1038: 	$editor->DeleteLine($p1);         # p1 - key p2 null.
                   1039:     } else {			          # Should not get here!!!
                   1040: 	die "Invalid command given to ApplyEdit $command"
                   1041:     }
                   1042: }
                   1043: #
                   1044: # AdjustOurHost:
                   1045: #           Adjusts a host file stored in a configuration file editor object
                   1046: #           for the true IP address of this host. This is necessary for hosts
                   1047: #           that live behind a firewall.
                   1048: #           Those hosts have a publicly distributed IP of the firewall, but
                   1049: #           internally must use their actual IP.  We assume that a given
                   1050: #           host only has a single IP interface for now.
                   1051: # Formal Parameters:
                   1052: #     editor   - The configuration file editor to adjust.  This
                   1053: #                editor is assumed to contain a hosts.tab file.
                   1054: # Strategy:
                   1055: #    - Figure out our hostname.
                   1056: #    - Lookup the entry for this host.
                   1057: #    - Modify the line to contain our IP
                   1058: #    - Do a replace for this host.
                   1059: sub AdjustOurHost {
                   1060:     my $editor        = shift;
                   1061: 
                   1062:     # figure out who I am.
                   1063: 
                   1064:     my $myHostName    = $perlvar{'lonHostID'}; # LonCAPA hostname.
                   1065: 
                   1066:     #  Get my host file entry.
                   1067: 
                   1068:     my $ConfigLine    = $editor->Find($myHostName);
                   1069:     if(! (defined $ConfigLine)) {
                   1070: 	die "AdjustOurHost - no entry for me in hosts file $myHostName";
                   1071:     }
                   1072:     # figure out my IP:
                   1073:     #   Use the config line to get my hostname.
                   1074:     #   Use gethostbyname to translate that into an IP address.
                   1075:     #
1.338     albertel 1076:     my ($id,$domain,$role,$name,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
1.169     foxr     1077:     #
                   1078:     #  Reassemble the config line from the elements in the list.
                   1079:     #  Note that if the loncnew items were not present before, they will
                   1080:     #  be now even if they would be empty
                   1081:     #
                   1082:     my $newConfigLine = $id;
1.338     albertel 1083:     foreach my $item ($domain, $role, $name, $maxcon, $idleto, $mincon) {
1.169     foxr     1084: 	$newConfigLine .= ":".$item;
                   1085:     }
                   1086:     #  Replace the line:
                   1087: 
                   1088:     $editor->ReplaceLine($id, $newConfigLine);
                   1089:     
                   1090: }
                   1091: #
                   1092: #   ReplaceConfigFile:
                   1093: #              Replaces a configuration file with the contents of a
                   1094: #              configuration file editor object.
                   1095: #              This is done by:
                   1096: #              - Copying the target file to <filename>.old
                   1097: #              - Writing the new file to <filename>.tmp
                   1098: #              - Moving <filename.tmp>  -> <filename>
                   1099: #              This laborious process ensures that the system is never without
                   1100: #              a configuration file that's at least valid (even if the contents
                   1101: #              may be dated).
                   1102: #   Parameters:
                   1103: #        filename   - Name of the file to modify... this is a full path.
                   1104: #        editor     - Editor containing the file.
                   1105: #
                   1106: sub ReplaceConfigFile {
1.192     foxr     1107:     
                   1108:     my ($filename, $editor) = @_;
1.168     foxr     1109: 
1.169     foxr     1110:     CopyFile ($filename, $filename.".old");
                   1111: 
                   1112:     my $contents  = $editor->Get(); # Get the contents of the file.
                   1113: 
                   1114:     InstallFile($filename, $contents);
                   1115: }
1.168     foxr     1116: #   
                   1117: #
                   1118: #   Called to edit a configuration table  file
1.167     foxr     1119: #   Parameters:
                   1120: #      request           - The entire command/request sent by lonc or lonManage
                   1121: #   Return:
                   1122: #      The reply to send to the client.
1.168     foxr     1123: #
1.167     foxr     1124: sub EditFile {
                   1125:     my $request = shift;
                   1126: 
                   1127:     #  Split the command into it's pieces:  edit:filetype:script
                   1128: 
1.339     albertel 1129:     my ($cmd, $filetype, $script) = split(/:/, $request,3);	# : in script
1.167     foxr     1130: 
                   1131:     #  Check the pre-coditions for success:
                   1132: 
1.339     albertel 1133:     if($cmd != "edit") {	# Something is amiss afoot alack.
1.167     foxr     1134: 	return "error:edit request detected, but request != 'edit'\n";
                   1135:     }
                   1136:     if( ($filetype ne "hosts")  &&
                   1137: 	($filetype ne "domain")) {
                   1138: 	return "error:edit requested with invalid file specifier: $filetype \n";
                   1139:     }
                   1140: 
                   1141:     #   Split the edit script and check it's validity.
1.168     foxr     1142: 
                   1143:     my @scriptlines = split(/\n/, $script);  # one line per element.
                   1144:     my $linecount   = scalar(@scriptlines);
                   1145:     for(my $i = 0; $i < $linecount; $i++) {
                   1146: 	chomp($scriptlines[$i]);
                   1147: 	if(!isValidEditCommand($scriptlines[$i])) {
                   1148: 	    return "error:edit with bad script line: '$scriptlines[$i]' \n";
                   1149: 	}
                   1150:     }
1.145     foxr     1151: 
1.167     foxr     1152:     #   Execute the edit operation.
1.169     foxr     1153:     #   - Create a config file editor for the appropriate file and 
                   1154:     #   - execute each command in the script:
                   1155:     #
                   1156:     my $configfile = ConfigFileFromSelector($filetype);
                   1157:     if (!(defined $configfile)) {
                   1158: 	return "refused\n";
                   1159:     }
                   1160:     my $editor = ConfigFileEdit->new($configfile);
1.167     foxr     1161: 
1.169     foxr     1162:     for (my $i = 0; $i < $linecount; $i++) {
                   1163: 	ApplyEdit($scriptlines[$i], $editor);
                   1164:     }
                   1165:     # If the file is the host file, ensure that our host is
                   1166:     # adjusted to have our ip:
                   1167:     #
                   1168:     if($filetype eq "host") {
                   1169: 	AdjustOurHost($editor);
                   1170:     }
                   1171:     #  Finally replace the current file with our file.
                   1172:     #
                   1173:     ReplaceConfigFile($configfile, $editor);
1.167     foxr     1174: 
                   1175:     return "ok\n";
                   1176: }
1.207     foxr     1177: 
1.255     foxr     1178: #   read_profile
                   1179: #
                   1180: #   Returns a set of specific entries from a user's profile file.
                   1181: #   this is a utility function that is used by both get_profile_entry and
                   1182: #   get_profile_entry_encrypted.
                   1183: #
                   1184: # Parameters:
                   1185: #    udom       - Domain in which the user exists.
                   1186: #    uname      - User's account name (loncapa account)
                   1187: #    namespace  - The profile namespace to open.
                   1188: #    what       - A set of & separated queries.
                   1189: # Returns:
                   1190: #    If all ok: - The string that needs to be shipped back to the user.
                   1191: #    If failure - A string that starts with error: followed by the failure
                   1192: #                 reason.. note that this probabyl gets shipped back to the
                   1193: #                 user as well.
                   1194: #
                   1195: sub read_profile {
                   1196:     my ($udom, $uname, $namespace, $what) = @_;
                   1197:     
                   1198:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   1199: 				 &GDBM_READER());
                   1200:     if ($hashref) {
                   1201:         my @queries=split(/\&/,$what);
1.440     raeburn  1202:         if ($namespace eq 'roles') {
                   1203:             @queries = map { &unescape($_); } @queries; 
                   1204:         }
1.255     foxr     1205:         my $qresult='';
                   1206: 	
                   1207: 	for (my $i=0;$i<=$#queries;$i++) {
                   1208: 	    $qresult.="$hashref->{$queries[$i]}&";    # Presumably failure gives empty string.
                   1209: 	}
                   1210: 	$qresult=~s/\&$//;              # Remove trailing & from last lookup.
1.311     albertel 1211: 	if (&untie_user_hash($hashref)) {
1.255     foxr     1212: 	    return $qresult;
                   1213: 	} else {
                   1214: 	    return "error: ".($!+0)." untie (GDBM) Failed";
                   1215: 	}
                   1216:     } else {
                   1217: 	if ($!+0 == 2) {
                   1218: 	    return "error:No such file or GDBM reported bad block error";
                   1219: 	} else {
                   1220: 	    return "error: ".($!+0)." tie (GDBM) Failed";
                   1221: 	}
                   1222:     }
                   1223: 
                   1224: }
1.214     foxr     1225: #--------------------- Request Handlers --------------------------------------------
                   1226: #
1.215     foxr     1227: #   By convention each request handler registers itself prior to the sub 
                   1228: #   declaration:
1.214     foxr     1229: #
                   1230: 
1.216     foxr     1231: #++
                   1232: #
1.214     foxr     1233: #  Handles ping requests.
                   1234: #  Parameters:
                   1235: #      $cmd    - the actual keyword that invoked us.
                   1236: #      $tail   - the tail of the request that invoked us.
                   1237: #      $replyfd- File descriptor connected to the client
                   1238: #  Implicit Inputs:
                   1239: #      $currenthostid - Global variable that carries the name of the host we are
                   1240: #                       known as.
                   1241: #  Returns:
                   1242: #      1       - Ok to continue processing.
                   1243: #      0       - Program should exit.
                   1244: #  Side effects:
                   1245: #      Reply information is sent to the client.
                   1246: sub ping_handler {
                   1247:     my ($cmd, $tail, $client) = @_;
                   1248:     Debug("$cmd $tail $client .. $currenthostid:");
                   1249:    
1.387     albertel 1250:     Reply( $client,\$currenthostid,"$cmd:$tail");
1.214     foxr     1251:    
                   1252:     return 1;
                   1253: }
                   1254: &register_handler("ping", \&ping_handler, 0, 1, 1);       # Ping unencoded, client or manager.
                   1255: 
1.216     foxr     1256: #++
1.215     foxr     1257: #
                   1258: # Handles pong requests.  Pong replies with our current host id, and
                   1259: #                         the results of a ping sent to us via our lonc.
                   1260: #
                   1261: # Parameters:
                   1262: #      $cmd    - the actual keyword that invoked us.
                   1263: #      $tail   - the tail of the request that invoked us.
                   1264: #      $replyfd- File descriptor connected to the client
                   1265: #  Implicit Inputs:
                   1266: #      $currenthostid - Global variable that carries the name of the host we are
                   1267: #                       connected to.
                   1268: #  Returns:
                   1269: #      1       - Ok to continue processing.
                   1270: #      0       - Program should exit.
                   1271: #  Side effects:
                   1272: #      Reply information is sent to the client.
                   1273: sub pong_handler {
                   1274:     my ($cmd, $tail, $replyfd) = @_;
                   1275: 
1.365     albertel 1276:     my $reply=&Apache::lonnet::reply("ping",$clientname);
1.215     foxr     1277:     &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail"); 
                   1278:     return 1;
                   1279: }
                   1280: &register_handler("pong", \&pong_handler, 0, 1, 1);       # Pong unencoded, client or manager
                   1281: 
1.216     foxr     1282: #++
                   1283: #      Called to establish an encrypted session key with the remote client.
                   1284: #      Note that with secure lond, in most cases this function is never
                   1285: #      invoked.  Instead, the secure session key is established either
                   1286: #      via a local file that's locked down tight and only lives for a short
                   1287: #      time, or via an ssl tunnel...and is generated from a bunch-o-random
                   1288: #      bits from /dev/urandom, rather than the predictable pattern used by
                   1289: #      by this sub.  This sub is only used in the old-style insecure
                   1290: #      key negotiation.
                   1291: # Parameters:
                   1292: #      $cmd    - the actual keyword that invoked us.
                   1293: #      $tail   - the tail of the request that invoked us.
                   1294: #      $replyfd- File descriptor connected to the client
                   1295: #  Implicit Inputs:
                   1296: #      $currenthostid - Global variable that carries the name of the host
                   1297: #                       known as.
1.448     raeburn  1298: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.216     foxr     1299: #  Returns:
                   1300: #      1       - Ok to continue processing.
                   1301: #      0       - Program should exit.
                   1302: #  Implicit Outputs:
                   1303: #      Reply information is sent to the client.
                   1304: #      $cipher is set with a reference to a new IDEA encryption object.
                   1305: #
                   1306: sub establish_key_handler {
                   1307:     my ($cmd, $tail, $replyfd) = @_;
                   1308: 
                   1309:     my $buildkey=time.$$.int(rand 100000);
                   1310:     $buildkey=~tr/1-6/A-F/;
                   1311:     $buildkey=int(rand 100000).$buildkey.int(rand 100000);
                   1312:     my $key=$currenthostid.$clientname;
                   1313:     $key=~tr/a-z/A-Z/;
                   1314:     $key=~tr/G-P/0-9/;
                   1315:     $key=~tr/Q-Z/0-9/;
                   1316:     $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
                   1317:     $key=substr($key,0,32);
                   1318:     my $cipherkey=pack("H32",$key);
                   1319:     $cipher=new IDEA $cipherkey;
1.387     albertel 1320:     &Reply($replyfd, \$buildkey, "$cmd:$tail"); 
1.216     foxr     1321:    
                   1322:     return 1;
                   1323: 
                   1324: }
                   1325: &register_handler("ekey", \&establish_key_handler, 0, 1,1);
                   1326: 
1.217     foxr     1327: #     Handler for the load command.  Returns the current system load average
                   1328: #     to the requestor.
                   1329: #
                   1330: # Parameters:
                   1331: #      $cmd    - the actual keyword that invoked us.
                   1332: #      $tail   - the tail of the request that invoked us.
                   1333: #      $replyfd- File descriptor connected to the client
                   1334: #  Implicit Inputs:
                   1335: #      $currenthostid - Global variable that carries the name of the host
                   1336: #                       known as.
1.448     raeburn  1337: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1338: #  Returns:
                   1339: #      1       - Ok to continue processing.
                   1340: #      0       - Program should exit.
                   1341: #  Side effects:
                   1342: #      Reply information is sent to the client.
                   1343: sub load_handler {
                   1344:     my ($cmd, $tail, $replyfd) = @_;
                   1345: 
1.463     foxr     1346: 
                   1347: 
1.217     foxr     1348:    # Get the load average from /proc/loadavg and calculate it as a percentage of
                   1349:    # the allowed load limit as set by the perl global variable lonLoadLim
                   1350: 
                   1351:     my $loadavg;
                   1352:     my $loadfile=IO::File->new('/proc/loadavg');
                   1353:    
                   1354:     $loadavg=<$loadfile>;
                   1355:     $loadavg =~ s/\s.*//g;                      # Extract the first field only.
                   1356:    
                   1357:     my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
                   1358: 
1.387     albertel 1359:     &Reply( $replyfd, \$loadpercent, "$cmd:$tail");
1.217     foxr     1360:    
                   1361:     return 1;
                   1362: }
1.263     albertel 1363: &register_handler("load", \&load_handler, 0, 1, 0);
1.217     foxr     1364: 
                   1365: #
                   1366: #   Process the userload request.  This sub returns to the client the current
                   1367: #  user load average.  It can be invoked either by clients or managers.
                   1368: #
                   1369: # Parameters:
                   1370: #      $cmd    - the actual keyword that invoked us.
                   1371: #      $tail   - the tail of the request that invoked us.
                   1372: #      $replyfd- File descriptor connected to the client
                   1373: #  Implicit Inputs:
                   1374: #      $currenthostid - Global variable that carries the name of the host
                   1375: #                       known as.
1.448     raeburn  1376: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1377: #  Returns:
                   1378: #      1       - Ok to continue processing.
                   1379: #      0       - Program should exit
                   1380: # Implicit inputs:
                   1381: #     whatever the userload() function requires.
                   1382: #  Implicit outputs:
                   1383: #     the reply is written to the client.
                   1384: #
                   1385: sub user_load_handler {
                   1386:     my ($cmd, $tail, $replyfd) = @_;
                   1387: 
1.365     albertel 1388:     my $userloadpercent=&Apache::lonnet::userload();
1.387     albertel 1389:     &Reply($replyfd, \$userloadpercent, "$cmd:$tail");
1.217     foxr     1390:     
                   1391:     return 1;
                   1392: }
1.263     albertel 1393: &register_handler("userload", \&user_load_handler, 0, 1, 0);
1.217     foxr     1394: 
1.218     foxr     1395: #   Process a request for the authorization type of a user:
                   1396: #   (userauth).
                   1397: #
                   1398: # Parameters:
                   1399: #      $cmd    - the actual keyword that invoked us.
                   1400: #      $tail   - the tail of the request that invoked us.
                   1401: #      $replyfd- File descriptor connected to the client
                   1402: #  Returns:
                   1403: #      1       - Ok to continue processing.
                   1404: #      0       - Program should exit
                   1405: # Implicit outputs:
                   1406: #    The user authorization type is written to the client.
                   1407: #
                   1408: sub user_authorization_type {
                   1409:     my ($cmd, $tail, $replyfd) = @_;
                   1410:    
                   1411:     my $userinput = "$cmd:$tail";
                   1412:    
                   1413:     #  Pull the domain and username out of the command tail.
1.222     foxr     1414:     # and call get_auth_type to determine the authentication type.
1.218     foxr     1415:    
                   1416:     my ($udom,$uname)=split(/:/,$tail);
1.222     foxr     1417:     my $result = &get_auth_type($udom, $uname);
1.218     foxr     1418:     if($result eq "nouser") {
                   1419: 	&Failure( $replyfd, "unknown_user\n", $userinput);
                   1420:     } else {
                   1421: 	#
1.222     foxr     1422: 	# We only want to pass the second field from get_auth_type
1.218     foxr     1423: 	# for ^krb.. otherwise we'll be handing out the encrypted
                   1424: 	# password for internals e.g.
                   1425: 	#
                   1426: 	my ($type,$otherinfo) = split(/:/,$result);
                   1427: 	if($type =~ /^krb/) {
                   1428: 	    $type = $result;
1.269     raeburn  1429: 	} else {
                   1430:             $type .= ':';
                   1431:         }
1.387     albertel 1432: 	&Reply( $replyfd, \$type, $userinput);
1.218     foxr     1433:     }
                   1434:   
                   1435:     return 1;
                   1436: }
                   1437: &register_handler("currentauth", \&user_authorization_type, 1, 1, 0);
                   1438: 
                   1439: #   Process a request by a manager to push a hosts or domain table 
                   1440: #   to us.  We pick apart the command and pass it on to the subs
                   1441: #   that already exist to do this.
                   1442: #
                   1443: # Parameters:
                   1444: #      $cmd    - the actual keyword that invoked us.
                   1445: #      $tail   - the tail of the request that invoked us.
                   1446: #      $client - File descriptor connected to the client
                   1447: #  Returns:
                   1448: #      1       - Ok to continue processing.
                   1449: #      0       - Program should exit
                   1450: # Implicit Output:
                   1451: #    a reply is written to the client.
                   1452: sub push_file_handler {
                   1453:     my ($cmd, $tail, $client) = @_;
1.412     foxr     1454:     &Debug("In push file handler");
1.218     foxr     1455:     my $userinput = "$cmd:$tail";
                   1456: 
                   1457:     # At this time we only know that the IP of our partner is a valid manager
                   1458:     # the code below is a hook to do further authentication (e.g. to resolve
                   1459:     # spoofing).
                   1460: 
                   1461:     my $cert = &GetCertificate($userinput);
1.412     foxr     1462:     if(&ValidManager($cert)) {
                   1463: 	&Debug("Valid manager: $client");
1.218     foxr     1464: 
                   1465: 	# Now presumably we have the bona fides of both the peer host and the
                   1466: 	# process making the request.
                   1467:       
                   1468: 	my $reply = &PushFile($userinput);
1.387     albertel 1469: 	&Reply($client, \$reply, $userinput);
1.218     foxr     1470: 
                   1471:     } else {
1.412     foxr     1472: 	&logthis("push_file_handler $client is not valid");
1.218     foxr     1473: 	&Failure( $client, "refused\n", $userinput);
                   1474:     } 
1.219     foxr     1475:     return 1;
1.218     foxr     1476: }
                   1477: &register_handler("pushfile", \&push_file_handler, 1, 0, 1);
                   1478: 
1.399     raeburn  1479: # The du_handler routine should be considered obsolete and is retained
                   1480: # for communication with legacy servers.  Please see the du2_handler.
1.243     banghart 1481: #
1.399     raeburn  1482: #   du  - list the disk usage of a directory recursively. 
1.243     banghart 1483: #    
                   1484: #   note: stolen code from the ls file handler
                   1485: #   under construction by Rick Banghart 
                   1486: #    .
                   1487: # Parameters:
                   1488: #    $cmd        - The command that dispatched us (du).
                   1489: #    $ududir     - The directory path to list... I'm not sure what this
                   1490: #                  is relative as things like ls:. return e.g.
                   1491: #                  no_such_dir.
                   1492: #    $client     - Socket open on the client.
                   1493: # Returns:
                   1494: #     1 - indicating that the daemon should not disconnect.
                   1495: # Side Effects:
                   1496: #   The reply is written to  $client.
                   1497: #
                   1498: sub du_handler {
                   1499:     my ($cmd, $ududir, $client) = @_;
1.339     albertel 1500:     ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
1.251     foxr     1501:     my $userinput = "$cmd:$ududir";
                   1502: 
1.245     albertel 1503:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
                   1504: 	&Failure($client,"refused\n","$cmd:$ududir");
                   1505: 	return 1;
                   1506:     }
1.249     foxr     1507:     #  Since $ududir could have some nasties in it,
                   1508:     #  we will require that ududir is a valid
                   1509:     #  directory.  Just in case someone tries to
                   1510:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1511:     #  etc.
                   1512:     #
                   1513:     if (-d $ududir) {
1.292     albertel 1514: 	my $total_size=0;
                   1515: 	my $code=sub { 
                   1516: 	    if ($_=~/\.\d+\./) { return;} 
                   1517: 	    if ($_=~/\.meta$/) { return;}
1.362     albertel 1518: 	    if (-d $_)         { return;}
1.292     albertel 1519: 	    $total_size+=(stat($_))[7];
                   1520: 	};
1.295     raeburn  1521: 	chdir($ududir);
1.292     albertel 1522: 	find($code,$ududir);
                   1523: 	$total_size=int($total_size/1024);
1.387     albertel 1524: 	&Reply($client,\$total_size,"$cmd:$ududir");
1.249     foxr     1525:     } else {
1.251     foxr     1526: 	&Failure($client, "bad_directory:$ududir\n","$cmd:$ududir"); 
1.249     foxr     1527:     }
1.243     banghart 1528:     return 1;
                   1529: }
                   1530: &register_handler("du", \&du_handler, 0, 1, 0);
1.218     foxr     1531: 
1.399     raeburn  1532: # Please also see the du_handler, which is obsoleted by du2. 
                   1533: # du2_handler differs from du_handler in that required path to directory
                   1534: # provided by &propath() is prepended in the handler instead of on the 
                   1535: # client side.
1.239     foxr     1536: #
1.399     raeburn  1537: #   du2  - list the disk usage of a directory recursively.
                   1538: #
                   1539: # Parameters:
                   1540: #    $cmd        - The command that dispatched us (du).
                   1541: #    $tail       - The tail of the request that invoked us.
                   1542: #                  $tail is a : separated list of the following:
                   1543: #                   - $ududir - directory path to list (before prepending)
                   1544: #                   - $getpropath = 1 if &propath() should prepend
                   1545: #                   - $uname - username to use for &propath or user dir
                   1546: #                   - $udom - domain to use for &propath or user dir
                   1547: #                   All are escaped.
                   1548: #    $client     - Socket open on the client.
                   1549: # Returns:
                   1550: #     1 - indicating that the daemon should not disconnect.
                   1551: # Side Effects:
                   1552: #   The reply is written to $client.
                   1553: #
                   1554: 
                   1555: sub du2_handler {
                   1556:     my ($cmd, $tail, $client) = @_;
                   1557:     my ($ududir,$getpropath,$uname,$udom) = map { &unescape($_) } (split(/:/, $tail));
                   1558:     my $userinput = "$cmd:$tail";
                   1559:     if (($ududir=~/\.\./) || (($ududir!~m|^/home/httpd/|) && (!$getpropath))) {
                   1560:         &Failure($client,"refused\n","$cmd:$tail");
                   1561:         return 1;
                   1562:     }
                   1563:     if ($getpropath) {
                   1564:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1565:             $ududir = &propath($udom,$uname).'/'.$ududir;
                   1566:         } else {
                   1567:             &Failure($client,"refused\n","$cmd:$tail");
                   1568:             return 1;
                   1569:         }
                   1570:     }
                   1571:     #  Since $ududir could have some nasties in it,
                   1572:     #  we will require that ududir is a valid
                   1573:     #  directory.  Just in case someone tries to
                   1574:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1575:     #  etc.
                   1576:     #
                   1577:     if (-d $ududir) {
                   1578:         my $total_size=0;
                   1579:         my $code=sub {
                   1580:             if ($_=~/\.\d+\./) { return;}
                   1581:             if ($_=~/\.meta$/) { return;}
                   1582:             if (-d $_)         { return;}
                   1583:             $total_size+=(stat($_))[7];
                   1584:         };
                   1585:         chdir($ududir);
                   1586:         find($code,$ududir);
                   1587:         $total_size=int($total_size/1024);
                   1588:         &Reply($client,\$total_size,"$cmd:$ududir");
                   1589:     } else {
                   1590:         &Failure($client, "bad_directory:$ududir\n","$cmd:$tail");
                   1591:     }
                   1592:     return 1;
                   1593: }
                   1594: &register_handler("du2", \&du2_handler, 0, 1, 0);
                   1595: 
                   1596: #
                   1597: # The ls_handler routine should be considered obsolete and is retained
                   1598: # for communication with legacy servers.  Please see the ls3_handler.
1.280     matthew  1599: #
1.239     foxr     1600: #   ls  - list the contents of a directory.  For each file in the
                   1601: #    selected directory the filename followed by the full output of
                   1602: #    the stat function is returned.  The returned info for each
                   1603: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1604: #
                   1605: #    If the requested path contains /../ or is:
                   1606: #
                   1607: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1608: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1609: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1610: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
                   1611: #    or is:
                   1612: #
1.538     raeburn  1613: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1614: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1615: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1616: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529     raeburn  1617: #
                   1618: #    the response will be "refused".
                   1619: #
1.239     foxr     1620: # Parameters:
                   1621: #    $cmd        - The command that dispatched us (ls).
                   1622: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1623: #                  is relative as things like ls:. return e.g.
                   1624: #                  no_such_dir.
                   1625: #    $client     - Socket open on the client.
                   1626: # Returns:
                   1627: #     1 - indicating that the daemon should not disconnect.
                   1628: # Side Effects:
                   1629: #   The reply is written to  $client.
                   1630: #
                   1631: sub ls_handler {
1.280     matthew  1632:     # obsoleted by ls2_handler
1.239     foxr     1633:     my ($cmd, $ulsdir, $client) = @_;
                   1634: 
                   1635:     my $userinput = "$cmd:$ulsdir";
                   1636: 
                   1637:     my $obs;
                   1638:     my $rights;
                   1639:     my $ulsout='';
                   1640:     my $ulsfn;
1.529     raeburn  1641:     if ($ulsdir =~m{/\.\./}) {
                   1642:         &Failure($client,"refused\n",$userinput);
                   1643:         return 1;
                   1644:     }
1.239     foxr     1645:     if (-e $ulsdir) {
                   1646: 	if(-d $ulsdir) {
1.539     raeburn  1647:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1648:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529     raeburn  1649:                 &Failure($client,"refused\n",$userinput);
                   1650:                 return 1;
                   1651:             }
1.239     foxr     1652: 	    if (opendir(LSDIR,$ulsdir)) {
                   1653: 		while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1654: 		    undef($obs);
                   1655: 		    undef($rights); 
1.239     foxr     1656: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1657: 		    #We do some obsolete checking here
                   1658: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1659: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1660: 			my @obsolete=<FILE>;
                   1661: 			foreach my $obsolete (@obsolete) {
1.301     www      1662: 			    if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.239     foxr     1663: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
                   1664: 			}
                   1665: 		    }
                   1666: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
                   1667: 		    if($obs eq '1') { $ulsout.="&1"; }
                   1668: 		    else { $ulsout.="&0"; }
                   1669: 		    if($rights eq '1') { $ulsout.="&1:"; }
                   1670: 		    else { $ulsout.="&0:"; }
                   1671: 		}
                   1672: 		closedir(LSDIR);
                   1673: 	    }
                   1674: 	} else {
1.539     raeburn  1675:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1676:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529     raeburn  1677:                 &Failure($client,"refused\n",$userinput);
                   1678:                 return 1;
                   1679:             }
1.239     foxr     1680: 	    my @ulsstats=stat($ulsdir);
                   1681: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1682: 	}
                   1683:     } else {
                   1684: 	$ulsout='no_such_dir';
                   1685:     }
                   1686:     if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1687:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.239     foxr     1688:     
                   1689:     return 1;
                   1690: 
                   1691: }
                   1692: &register_handler("ls", \&ls_handler, 0, 1, 0);
                   1693: 
1.399     raeburn  1694: # The ls2_handler routine should be considered obsolete and is retained
                   1695: # for communication with legacy servers.  Please see the ls3_handler.
                   1696: # Please also see the ls_handler, which was itself obsoleted by ls2.
1.280     matthew  1697: # ls2_handler differs from ls_handler in that it escapes its return 
                   1698: # values before concatenating them together with ':'s.
                   1699: #
                   1700: #   ls2  - list the contents of a directory.  For each file in the
                   1701: #    selected directory the filename followed by the full output of
                   1702: #    the stat function is returned.  The returned info for each
                   1703: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1704: #
                   1705: #    If the requested path contains /../ or is:
                   1706: #
                   1707: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1708: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1709: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1710: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
                   1711: #    or is:
                   1712: #
1.538     raeburn  1713: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1714: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1715: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1716: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529     raeburn  1717: #
                   1718: #    the response will be "refused".
                   1719: #
1.280     matthew  1720: # Parameters:
                   1721: #    $cmd        - The command that dispatched us (ls).
                   1722: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1723: #                  is relative as things like ls:. return e.g.
                   1724: #                  no_such_dir.
                   1725: #    $client     - Socket open on the client.
                   1726: # Returns:
                   1727: #     1 - indicating that the daemon should not disconnect.
                   1728: # Side Effects:
                   1729: #   The reply is written to  $client.
                   1730: #
                   1731: sub ls2_handler {
                   1732:     my ($cmd, $ulsdir, $client) = @_;
                   1733: 
                   1734:     my $userinput = "$cmd:$ulsdir";
                   1735: 
                   1736:     my $obs;
                   1737:     my $rights;
                   1738:     my $ulsout='';
                   1739:     my $ulsfn;
1.529     raeburn  1740:     if ($ulsdir =~m{/\.\./}) {
                   1741:         &Failure($client,"refused\n",$userinput);
                   1742:         return 1;
                   1743:     }
1.280     matthew  1744:     if (-e $ulsdir) {
                   1745:         if(-d $ulsdir) {
1.539     raeburn  1746:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1747:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529     raeburn  1748:                 &Failure($client,"refused\n","$userinput");
                   1749:                 return 1;
                   1750:             }
1.280     matthew  1751:             if (opendir(LSDIR,$ulsdir)) {
                   1752:                 while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1753:                     undef($obs);
                   1754: 		    undef($rights); 
1.280     matthew  1755:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1756:                     #We do some obsolete checking here
                   1757:                     if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1758:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1759:                         my @obsolete=<FILE>;
                   1760:                         foreach my $obsolete (@obsolete) {
1.301     www      1761:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.280     matthew  1762:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1763:                                 $rights = 1;
                   1764:                             }
                   1765:                         }
                   1766:                     }
                   1767:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1768:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1769:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1770:                     $ulsout.= &escape($tmp).':';
                   1771:                 }
                   1772:                 closedir(LSDIR);
                   1773:             }
                   1774:         } else {
1.539     raeburn  1775:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1776:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529     raeburn  1777:                 &Failure($client,"refused\n",$userinput);
                   1778:                 return 1;
                   1779:             }
1.280     matthew  1780:             my @ulsstats=stat($ulsdir);
                   1781:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1782:         }
                   1783:     } else {
                   1784:         $ulsout='no_such_dir';
                   1785:    }
                   1786:    if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1787:    &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.280     matthew  1788:    return 1;
                   1789: }
                   1790: &register_handler("ls2", \&ls2_handler, 0, 1, 0);
1.399     raeburn  1791: #
                   1792: #   ls3  - list the contents of a directory.  For each file in the
                   1793: #    selected directory the filename followed by the full output of
                   1794: #    the stat function is returned.  The returned info for each
                   1795: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1796: #
                   1797: #    If the requested path (after prepending) contains /../ or is:
                   1798: #
                   1799: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1800: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1801: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1802: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
1.539     raeburn  1803: #        (d) /home/httpd/html/priv/<domain> and client is the homeserver
1.529     raeburn  1804: #
1.530     raeburn  1805: #    or is:
1.529     raeburn  1806: #
1.538     raeburn  1807: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1808: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1809: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1810: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
                   1811: #        (d) /home/httpd/html/priv/<domain>/<username>/ and client is the homeserver
1.529     raeburn  1812: #
                   1813: #    the response will be "refused".
                   1814: #
1.399     raeburn  1815: # Parameters:
                   1816: #    $cmd        - The command that dispatched us (ls).
                   1817: #    $tail       - The tail of the request that invoked us.
                   1818: #                  $tail is a : separated list of the following:
                   1819: #                   - $ulsdir - directory path to list (before prepending)
                   1820: #                   - $getpropath = 1 if &propath() should prepend
                   1821: #                   - $getuserdir = 1 if path to user dir in lonUsers should
                   1822: #                                     prepend
                   1823: #                   - $alternate_root - path to prepend
                   1824: #                   - $uname - username to use for &propath or user dir
                   1825: #                   - $udom - domain to use for &propath or user dir
                   1826: #            All of these except $getpropath and &getuserdir are escaped.    
                   1827: #                  no_such_dir.
                   1828: #    $client     - Socket open on the client.
                   1829: # Returns:
                   1830: #     1 - indicating that the daemon should not disconnect.
                   1831: # Side Effects:
                   1832: #   The reply is written to $client.
                   1833: #
                   1834: 
                   1835: sub ls3_handler {
                   1836:     my ($cmd, $tail, $client) = @_;
                   1837:     my $userinput = "$cmd:$tail";
                   1838:     my ($ulsdir,$getpropath,$getuserdir,$alternate_root,$uname,$udom) =
                   1839:         split(/:/,$tail);
                   1840:     if (defined($ulsdir)) {
                   1841:         $ulsdir = &unescape($ulsdir);
                   1842:     }
                   1843:     if (defined($alternate_root)) {
                   1844:         $alternate_root = &unescape($alternate_root);
                   1845:     }
                   1846:     if (defined($uname)) {
                   1847:         $uname = &unescape($uname);
                   1848:     }
                   1849:     if (defined($udom)) {
                   1850:         $udom = &unescape($udom);
                   1851:     }
                   1852: 
                   1853:     my $dir_root = $perlvar{'lonDocRoot'};
1.529     raeburn  1854:     if (($getpropath) || ($getuserdir)) {
1.399     raeburn  1855:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1856:             $dir_root = &propath($udom,$uname);
                   1857:             $dir_root =~ s/\/$//;
                   1858:         } else {
1.529     raeburn  1859:             &Failure($client,"refused\n",$userinput);
1.399     raeburn  1860:             return 1;
                   1861:         }
1.400     raeburn  1862:     } elsif ($alternate_root ne '') {
1.399     raeburn  1863:         $dir_root = $alternate_root;
                   1864:     }
1.408     raeburn  1865:     if (($dir_root ne '') && ($dir_root ne '/')) {
1.400     raeburn  1866:         if ($ulsdir =~ /^\//) {
                   1867:             $ulsdir = $dir_root.$ulsdir;
                   1868:         } else {
                   1869:             $ulsdir = $dir_root.'/'.$ulsdir;
                   1870:         }
1.399     raeburn  1871:     }
1.529     raeburn  1872:     if ($ulsdir =~m{/\.\./}) {
                   1873:         &Failure($client,"refused\n",$userinput);
                   1874:         return 1;
                   1875:     }
                   1876:     my $islocal;
                   1877:     my @machine_ids = &Apache::lonnet::current_machine_ids();
                   1878:     if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   1879:         $islocal = 1;
                   1880:     }
1.399     raeburn  1881:     my $obs;
                   1882:     my $rights;
                   1883:     my $ulsout='';
                   1884:     my $ulsfn;
                   1885:     if (-e $ulsdir) {
                   1886:         if(-d $ulsdir) {
1.529     raeburn  1887:             unless (($getpropath) || ($getuserdir) ||
1.539     raeburn  1888:                     ($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1889:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles}) ||
                   1890:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain}) && ($islocal))) {
1.529     raeburn  1891:                 &Failure($client,"refused\n",$userinput);
                   1892:                 return 1;
                   1893:             }
1.399     raeburn  1894:             if (opendir(LSDIR,$ulsdir)) {
                   1895:                 while ($ulsfn=readdir(LSDIR)) {
                   1896:                     undef($obs);
                   1897:                     undef($rights);
                   1898:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1899:                     #We do some obsolete checking here
                   1900:                     if(-e $ulsdir.'/'.$ulsfn.".meta") {
                   1901:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1902:                         my @obsolete=<FILE>;
                   1903:                         foreach my $obsolete (@obsolete) {
                   1904:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
                   1905:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1906:                                 $rights = 1;
                   1907:                             }
                   1908:                         }
                   1909:                     }
                   1910:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1911:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1912:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1913:                     $ulsout.= &escape($tmp).':';
                   1914:                 }
                   1915:                 closedir(LSDIR);
                   1916:             }
                   1917:         } else {
1.529     raeburn  1918:             unless (($getpropath) || ($getuserdir) ||
1.539     raeburn  1919:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1920:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/}) ||
                   1921:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain/$LONCAPA::match_name/}) && ($islocal))) {
1.529     raeburn  1922:                 &Failure($client,"refused\n",$userinput);
                   1923:                 return 1;
                   1924:             }
1.399     raeburn  1925:             my @ulsstats=stat($ulsdir);
                   1926:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1927:         }
                   1928:     } else {
                   1929:         $ulsout='no_such_dir';
1.400     raeburn  1930:     }
                   1931:     if ($ulsout eq '') { $ulsout='empty'; }
                   1932:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
                   1933:     return 1;
1.399     raeburn  1934: }
                   1935: &register_handler("ls3", \&ls3_handler, 0, 1, 0);
1.280     matthew  1936: 
1.477     raeburn  1937: sub read_lonnet_global {
                   1938:     my ($cmd,$tail,$client) = @_;
                   1939:     my $userinput = "$cmd:$tail";
                   1940:     my $requested = &Apache::lonnet::thaw_unescape($tail);
                   1941:     my $result;
1.480     raeburn  1942:     my %packagevars = (
                   1943:                         spareid => \%Apache::lonnet::spareid,
                   1944:                         perlvar => \%Apache::lonnet::perlvar,
                   1945:                       );
                   1946:     my %limit_to = (
                   1947:                     perlvar => {
1.531     raeburn  1948:                                  lonOtherAuthen  => 1,
                   1949:                                  lonBalancer     => 1,
                   1950:                                  lonVersion      => 1,
                   1951:                                  lonAdmEMail     => 1,
                   1952:                                  lonSupportEMail => 1,  
                   1953:                                  lonSysEMail     => 1,
                   1954:                                  lonHostID       => 1,
                   1955:                                  lonRole         => 1,
                   1956:                                  lonDefDomain    => 1,
                   1957:                                  lonLoadLim      => 1,
                   1958:                                  lonUserLoadLim  => 1,
1.480     raeburn  1959:                                }
                   1960:                   );
1.477     raeburn  1961:     if (ref($requested) eq 'HASH') {
                   1962:         foreach my $what (keys(%{$requested})) {
                   1963:             my $response;
1.480     raeburn  1964:             my $items = {};
                   1965:             if (exists($packagevars{$what})) {
                   1966:                 if (ref($limit_to{$what}) eq 'HASH') {
                   1967:                     foreach my $varname (keys(%{$packagevars{$what}})) {
                   1968:                         if ($limit_to{$what}{$varname}) {
                   1969:                             $items->{$varname} = $packagevars{$what}{$varname};
                   1970:                         }
                   1971:                     }
                   1972:                 } else {
                   1973:                     $items = $packagevars{$what};
1.477     raeburn  1974:                 }
1.480     raeburn  1975:                 if ($what eq 'perlvar') {
                   1976:                     if (!exists($packagevars{$what}{'lonBalancer'})) {
                   1977:                         if ($dist =~ /^(centos|rhes|fedora|scientific)/) {
                   1978:                             my $othervarref=LONCAPA::Configuration::read_conf('httpd.conf');
                   1979:                             if (ref($othervarref) eq 'HASH') {
                   1980:                                 $items->{'lonBalancer'} = $othervarref->{'lonBalancer'};
                   1981:                             }
                   1982:                         }
                   1983:                     }
1.477     raeburn  1984:                 }
1.480     raeburn  1985:                 $response = &Apache::lonnet::freeze_escape($items);
1.477     raeburn  1986:             }
1.478     raeburn  1987:             $result .= &escape($what).'='.$response.'&';
1.477     raeburn  1988:         }
                   1989:     }
                   1990:     $result =~ s/\&$//;
                   1991:     &Reply($client,\$result,$userinput);
                   1992:     return 1;
                   1993: }
                   1994: &register_handler("readlonnetglobal", \&read_lonnet_global, 0, 1, 0);
                   1995: 
1.479     raeburn  1996: sub server_devalidatecache_handler {
                   1997:     my ($cmd,$tail,$client) = @_;
                   1998:     my $userinput = "$cmd:$tail";
1.503     raeburn  1999:     my $items = &unescape($tail);
                   2000:     my @cached = split(/\&/,$items);
                   2001:     foreach my $key (@cached) {
                   2002:         if ($key =~ /:/) {
                   2003:             my ($name,$id) = map { &unescape($_); } split(/:/,$key);
                   2004:             &Apache::lonnet::devalidate_cache_new($name,$id);
                   2005:         }
                   2006:     }
1.479     raeburn  2007:     my $result = 'ok';
                   2008:     &Reply($client,\$result,$userinput);
                   2009:     return 1;
                   2010: }
1.481     raeburn  2011: &register_handler("devalidatecache", \&server_devalidatecache_handler, 0, 1, 0);
1.479     raeburn  2012: 
1.410     raeburn  2013: sub server_timezone_handler {
                   2014:     my ($cmd,$tail,$client) = @_;
                   2015:     my $userinput = "$cmd:$tail";
                   2016:     my $timezone;
                   2017:     my $clockfile = '/etc/sysconfig/clock'; # Fedora/CentOS/SuSE
                   2018:     my $tzfile = '/etc/timezone'; # Debian/Ubuntu
                   2019:     if (-e $clockfile) {
                   2020:         if (open(my $fh,"<$clockfile")) {
                   2021:             while (<$fh>) {
                   2022:                 next if (/^[\#\s]/);
                   2023:                 if (/^(?:TIME)?ZONE\s*=\s*['"]?\s*([\w\/]+)/) {
                   2024:                     $timezone = $1;
                   2025:                     last;
                   2026:                 }
                   2027:             }
                   2028:             close($fh);
                   2029:         }
                   2030:     } elsif (-e $tzfile) {
                   2031:         if (open(my $fh,"<$tzfile")) {
                   2032:             $timezone = <$fh>;
                   2033:             close($fh);
                   2034:             chomp($timezone);
                   2035:             if ($timezone =~ m{^Etc/(\w+)$}) {
                   2036:                 $timezone = $1;
                   2037:             }
                   2038:         }
                   2039:     }
                   2040:     &Reply($client,\$timezone,$userinput); # This supports debug logging.
                   2041:     return 1;
                   2042: }
                   2043: &register_handler("servertimezone", \&server_timezone_handler, 0, 1, 0);
                   2044: 
1.413     raeburn  2045: sub server_loncaparev_handler {
                   2046:     my ($cmd,$tail,$client) = @_;
                   2047:     my $userinput = "$cmd:$tail";
                   2048:     &Reply($client,\$perlvar{'lonVersion'},$userinput);
                   2049:     return 1;
                   2050: }
                   2051: &register_handler("serverloncaparev", \&server_loncaparev_handler, 0, 1, 0);
                   2052: 
1.448     raeburn  2053: sub server_homeID_handler {
                   2054:     my ($cmd,$tail,$client) = @_;
                   2055:     my $userinput = "$cmd:$tail";
                   2056:     &Reply($client,\$perlvar{'lonHostID'},$userinput);
                   2057:     return 1;
                   2058: }
                   2059: &register_handler("serverhomeID", \&server_homeID_handler, 0, 1, 0);
                   2060: 
1.471     raeburn  2061: sub server_distarch_handler {
                   2062:     my ($cmd,$tail,$client) = @_;
                   2063:     my $userinput = "$cmd:$tail";
                   2064:     my $reply = &distro_and_arch();
                   2065:     &Reply($client,\$reply,$userinput);
                   2066:     return 1;
                   2067: }
                   2068: &register_handler("serverdistarch", \&server_distarch_handler, 0, 1, 0);
                   2069: 
1.523     raeburn  2070: sub server_certs_handler {
                   2071:     my ($cmd,$tail,$client) = @_;
                   2072:     my $userinput = "$cmd:$tail";
                   2073:     my $result;
                   2074:     my $result = &LONCAPA::Lond::server_certs(\%perlvar);
                   2075:     &Reply($client,\$result,$userinput);
                   2076:     return;
                   2077: }
                   2078: &register_handler("servercerts", \&server_certs_handler, 0, 1, 0);
                   2079: 
1.218     foxr     2080: #   Process a reinit request.  Reinit requests that either
                   2081: #   lonc or lond be reinitialized so that an updated 
                   2082: #   host.tab or domain.tab can be processed.
                   2083: #
                   2084: # Parameters:
                   2085: #      $cmd    - the actual keyword that invoked us.
                   2086: #      $tail   - the tail of the request that invoked us.
                   2087: #      $client - File descriptor connected to the client
                   2088: #  Returns:
                   2089: #      1       - Ok to continue processing.
                   2090: #      0       - Program should exit
                   2091: #  Implicit output:
                   2092: #     a reply is sent to the client.
                   2093: #
                   2094: sub reinit_process_handler {
                   2095:     my ($cmd, $tail, $client) = @_;
                   2096:    
                   2097:     my $userinput = "$cmd:$tail";
                   2098:    
                   2099:     my $cert = &GetCertificate($userinput);
                   2100:     if(&ValidManager($cert)) {
                   2101: 	chomp($userinput);
                   2102: 	my $reply = &ReinitProcess($userinput);
1.387     albertel 2103: 	&Reply( $client,  \$reply, $userinput);
1.218     foxr     2104:     } else {
                   2105: 	&Failure( $client, "refused\n", $userinput);
                   2106:     }
                   2107:     return 1;
                   2108: }
                   2109: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
                   2110: 
                   2111: #  Process the editing script for a table edit operation.
                   2112: #  the editing operation must be encrypted and requested by
                   2113: #  a manager host.
                   2114: #
                   2115: # Parameters:
                   2116: #      $cmd    - the actual keyword that invoked us.
                   2117: #      $tail   - the tail of the request that invoked us.
                   2118: #      $client - File descriptor connected to the client
                   2119: #  Returns:
                   2120: #      1       - Ok to continue processing.
                   2121: #      0       - Program should exit
                   2122: #  Implicit output:
                   2123: #     a reply is sent to the client.
                   2124: #
                   2125: sub edit_table_handler {
                   2126:     my ($command, $tail, $client) = @_;
                   2127:    
                   2128:     my $userinput = "$command:$tail";
                   2129: 
                   2130:     my $cert = &GetCertificate($userinput);
                   2131:     if(&ValidManager($cert)) {
                   2132: 	my($filetype, $script) = split(/:/, $tail);
                   2133: 	if (($filetype eq "hosts") || 
                   2134: 	    ($filetype eq "domain")) {
                   2135: 	    if($script ne "") {
                   2136: 		&Reply($client,              # BUGBUG - EditFile
                   2137: 		      &EditFile($userinput), #   could fail.
                   2138: 		      $userinput);
                   2139: 	    } else {
                   2140: 		&Failure($client,"refused\n",$userinput);
                   2141: 	    }
                   2142: 	} else {
                   2143: 	    &Failure($client,"refused\n",$userinput);
                   2144: 	}
                   2145:     } else {
                   2146: 	&Failure($client,"refused\n",$userinput);
                   2147:     }
                   2148:     return 1;
                   2149: }
1.263     albertel 2150: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
1.218     foxr     2151: 
1.220     foxr     2152: #
                   2153: #   Authenticate a user against the LonCAPA authentication
                   2154: #   database.  Note that there are several authentication
                   2155: #   possibilities:
                   2156: #   - unix     - The user can be authenticated against the unix
                   2157: #                password file.
                   2158: #   - internal - The user can be authenticated against a purely 
                   2159: #                internal per user password file.
                   2160: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
                   2161: #                ticket granting authority.
                   2162: #   - user     - The person tailoring LonCAPA can supply a user authentication
                   2163: #                mechanism that is per system.
                   2164: #
                   2165: # Parameters:
                   2166: #    $cmd      - The command that got us here.
                   2167: #    $tail     - Tail of the command (remaining parameters).
                   2168: #    $client   - File descriptor connected to client.
                   2169: # Returns
                   2170: #     0        - Requested to exit, caller should shut down.
                   2171: #     1        - Continue processing.
                   2172: # Implicit inputs:
                   2173: #    The authentication systems describe above have their own forms of implicit
                   2174: #    input into the authentication process that are described above.
                   2175: #
                   2176: sub authenticate_handler {
                   2177:     my ($cmd, $tail, $client) = @_;
                   2178: 
                   2179:     
                   2180:     #  Regenerate the full input line 
                   2181:     
                   2182:     my $userinput  = $cmd.":".$tail;
                   2183:     
                   2184:     #  udom    - User's domain.
                   2185:     #  uname   - Username.
                   2186:     #  upass   - User's password.
1.396     raeburn  2187:     #  checkdefauth - Pass to validate_user() to try authentication
                   2188:     #                 with default auth type(s) if no user account.
1.447     raeburn  2189:     #  clientcancheckhost - Passed by clients with functionality in lonauth.pm
                   2190:     #                       to check if session can be hosted.
1.220     foxr     2191:     
1.447     raeburn  2192:     my ($udom, $uname, $upass, $checkdefauth, $clientcancheckhost)=split(/:/,$tail);
1.399     raeburn  2193:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass,  checkdefauth = $checkdefauth");
1.220     foxr     2194:     chomp($upass);
                   2195:     $upass=&unescape($upass);
                   2196: 
1.396     raeburn  2197:     my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
1.220     foxr     2198:     if($pwdcorrect) {
1.447     raeburn  2199:         my $canhost = 1;
                   2200:         unless ($clientcancheckhost) {
1.448     raeburn  2201:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   2202:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.452     raeburn  2203:             my @intdoms;
                   2204:             my $internet_names = &Apache::lonnet::get_internet_names($clientname);
                   2205:             if (ref($internet_names) eq 'ARRAY') {
                   2206:                 @intdoms = @{$internet_names};
                   2207:             }
1.448     raeburn  2208:             unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
1.447     raeburn  2209:                 my ($remote,$hosted);
                   2210:                 my $remotesession = &get_usersession_config($udom,'remotesession');
                   2211:                 if (ref($remotesession) eq 'HASH') {
1.525     raeburn  2212:                     $remote = $remotesession->{'remote'};
1.447     raeburn  2213:                 }
1.448     raeburn  2214:                 my $hostedsession = &get_usersession_config($clienthomedom,'hostedsession');
1.447     raeburn  2215:                 if (ref($hostedsession) eq 'HASH') {
                   2216:                     $hosted = $hostedsession->{'hosted'};
                   2217:                 }
1.448     raeburn  2218:                 $canhost = &Apache::lonnet::can_host_session($udom,$clientname,
1.492     droeschl 2219:                                                              $clientversion,
1.447     raeburn  2220:                                                              $remote,$hosted);
                   2221:             }
                   2222:         }
                   2223:         if ($canhost) {               
                   2224:             &Reply( $client, "authorized\n", $userinput);
                   2225:         } else {
                   2226:             &Reply( $client, "not_allowed_to_host\n", $userinput);
                   2227:         }
1.220     foxr     2228: 	#
                   2229: 	#  Bad credentials: Failed to authorize
                   2230: 	#
                   2231:     } else {
                   2232: 	&Failure( $client, "non_authorized\n", $userinput);
                   2233:     }
                   2234: 
                   2235:     return 1;
                   2236: }
1.263     albertel 2237: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
1.214     foxr     2238: 
1.222     foxr     2239: #
                   2240: #   Change a user's password.  Note that this function is complicated by
                   2241: #   the fact that a user may be authenticated in more than one way:
                   2242: #   At present, we are not able to change the password for all types of
                   2243: #   authentication methods.  Only for:
                   2244: #      unix    - unix password or shadow passoword style authentication.
                   2245: #      local   - Locally written authentication mechanism.
                   2246: #   For now, kerb4 and kerb5 password changes are not supported and result
                   2247: #   in an error.
                   2248: # FUTURE WORK:
                   2249: #    Support kerberos passwd changes?
                   2250: # Parameters:
                   2251: #    $cmd      - The command that got us here.
                   2252: #    $tail     - Tail of the command (remaining parameters).
                   2253: #    $client   - File descriptor connected to client.
                   2254: # Returns
                   2255: #     0        - Requested to exit, caller should shut down.
                   2256: #     1        - Continue processing.
                   2257: # Implicit inputs:
                   2258: #    The authentication systems describe above have their own forms of implicit
                   2259: #    input into the authentication process that are described above.
                   2260: sub change_password_handler {
                   2261:     my ($cmd, $tail, $client) = @_;
                   2262: 
                   2263:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
                   2264: 
                   2265:     #
                   2266:     #  udom  - user's domain.
                   2267:     #  uname - Username.
                   2268:     #  upass - Current password.
                   2269:     #  npass - New password.
1.346     raeburn  2270:     #  context - Context in which this was called 
                   2271:     #            (preferences or reset_by_email).
1.428     raeburn  2272:     #  lonhost - HostID of server where request originated 
1.222     foxr     2273:    
1.428     raeburn  2274:     my ($udom,$uname,$upass,$npass,$context,$lonhost)=split(/:/,$tail);
1.222     foxr     2275: 
                   2276:     $upass=&unescape($upass);
                   2277:     $npass=&unescape($npass);
                   2278:     &Debug("Trying to change password for $uname");
                   2279: 
                   2280:     # First require that the user can be authenticated with their
1.346     raeburn  2281:     # old password unless context was 'reset_by_email':
                   2282:     
1.428     raeburn  2283:     my ($validated,$failure);
1.346     raeburn  2284:     if ($context eq 'reset_by_email') {
1.428     raeburn  2285:         if ($lonhost eq '') {
                   2286:             $failure = 'invalid_client';
                   2287:         } else {
                   2288:             $validated = 1;
                   2289:         }
1.346     raeburn  2290:     } else {
                   2291:         $validated = &validate_user($udom, $uname, $upass);
                   2292:     }
1.222     foxr     2293:     if($validated) {
                   2294: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
                   2295: 	
                   2296: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
                   2297: 	if ($howpwd eq 'internal') {
                   2298: 	    &Debug("internal auth");
1.518     raeburn  2299:             my $ncpass = &hash_passwd($udom,$npass);
1.222     foxr     2300: 	    if(&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
1.428     raeburn  2301: 		my $msg="Result of password change for $uname: pwchange_success";
                   2302:                 if ($lonhost) {
                   2303:                     $msg .= " - request originated from: $lonhost";
                   2304:                 }
                   2305:                 &logthis($msg);
1.518     raeburn  2306:                 &update_passwd_history($uname,$udom,$howpwd,$context);
1.222     foxr     2307: 		&Reply($client, "ok\n", $userinput);
                   2308: 	    } else {
                   2309: 		&logthis("Unable to open $uname passwd "               
                   2310: 			 ."to change password");
                   2311: 		&Failure( $client, "non_authorized\n",$userinput);
                   2312: 	    }
1.346     raeburn  2313: 	} elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
1.287     foxr     2314: 	    my $result = &change_unix_password($uname, $npass);
1.518     raeburn  2315:             if ($result eq 'ok') {
                   2316:                 &update_passwd_history($uname,$udom,$howpwd,$context);
                   2317:              }
1.222     foxr     2318: 	    &logthis("Result of password change for $uname: ".
1.287     foxr     2319: 		     $result);
1.387     albertel 2320: 	    &Reply($client, \$result, $userinput);
1.222     foxr     2321: 	} else {
                   2322: 	    # this just means that the current password mode is not
                   2323: 	    # one we know how to change (e.g the kerberos auth modes or
                   2324: 	    # locally written auth handler).
                   2325: 	    #
                   2326: 	    &Failure( $client, "auth_mode_error\n", $userinput);
                   2327: 	}  
                   2328: 	
1.224     foxr     2329:     } else {
1.428     raeburn  2330: 	if ($failure eq '') {
                   2331: 	    $failure = 'non_authorized';
                   2332: 	}
                   2333: 	&Failure( $client, "$failure\n", $userinput);
1.222     foxr     2334:     }
                   2335: 
                   2336:     return 1;
                   2337: }
1.263     albertel 2338: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
1.222     foxr     2339: 
1.518     raeburn  2340: sub hash_passwd {
                   2341:     my ($domain,$plainpass,@rest) = @_;
                   2342:     my ($salt,$cost);
                   2343:     if (@rest) {
                   2344:         $cost = $rest[0];
                   2345:         # salt is first 22 characters, base-64 encoded by bcrypt
                   2346:         my $plainsalt = substr($rest[1],0,22);
                   2347:         $salt = Crypt::Eksblowfish::Bcrypt::de_base64($plainsalt);
                   2348:     } else {
1.533     raeburn  2349:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2350:         my $defaultcost = $domdefaults{'intauth_cost'};
1.518     raeburn  2351:         if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   2352:             $cost = 10;
                   2353:         } else {
                   2354:             $cost = $defaultcost;
                   2355:         }
                   2356:         # Generate random 16-octet base64 salt
                   2357:         $salt = "";
                   2358:         $salt .= pack("C", int rand(256)) for 1..16;
                   2359:     }
                   2360:     my $hash = &Crypt::Eksblowfish::Bcrypt::bcrypt_hash({
                   2361:         key_nul => 1,
                   2362:         cost    => $cost,
                   2363:         salt    => $salt,
                   2364:     }, Digest::SHA::sha512(Encode::encode('UTF-8',$plainpass)));
                   2365: 
                   2366:     my $result = join("!", "", "bcrypt", sprintf("%02d",$cost),
                   2367:                 &Crypt::Eksblowfish::Bcrypt::en_base64($salt).
                   2368:                 &Crypt::Eksblowfish::Bcrypt::en_base64($hash));
                   2369:     return $result;
                   2370: }
                   2371: 
1.225     foxr     2372: #
                   2373: #   Create a new user.  User in this case means a lon-capa user.
                   2374: #   The user must either already exist in some authentication realm
                   2375: #   like kerberos or the /etc/passwd.  If not, a user completely local to
                   2376: #   this loncapa system is created.
                   2377: #
                   2378: # Parameters:
                   2379: #    $cmd      - The command that got us here.
                   2380: #    $tail     - Tail of the command (remaining parameters).
                   2381: #    $client   - File descriptor connected to client.
                   2382: # Returns
                   2383: #     0        - Requested to exit, caller should shut down.
                   2384: #     1        - Continue processing.
                   2385: # Implicit inputs:
                   2386: #    The authentication systems describe above have their own forms of implicit
                   2387: #    input into the authentication process that are described above.
                   2388: sub add_user_handler {
                   2389: 
                   2390:     my ($cmd, $tail, $client) = @_;
                   2391: 
                   2392: 
                   2393:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2394:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
                   2395: 
                   2396:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
                   2397: 
                   2398: 
                   2399:     if($udom eq $currentdomainid) { # Reject new users for other domains...
                   2400: 	
                   2401: 	my $oldumask=umask(0077);
                   2402: 	chomp($npass);
                   2403: 	$npass=&unescape($npass);
                   2404: 	my $passfilename  = &password_path($udom, $uname);
                   2405: 	&Debug("Password file created will be:".$passfilename);
                   2406: 	if (-e $passfilename) {
                   2407: 	    &Failure( $client, "already_exists\n", $userinput);
                   2408: 	} else {
                   2409: 	    my $fperror='';
1.264     albertel 2410: 	    if (!&mkpath($passfilename)) {
                   2411: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
                   2412: 		    ."makeuser";
1.225     foxr     2413: 	    }
                   2414: 	    unless ($fperror) {
1.518     raeburn  2415: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2416:                                              $passfilename,'makeuser');
1.390     raeburn  2417: 		&Reply($client,\$result, $userinput);     #BUGBUG - could be fail
1.225     foxr     2418: 	    } else {
1.387     albertel 2419: 		&Failure($client, \$fperror, $userinput);
1.225     foxr     2420: 	    }
                   2421: 	}
                   2422: 	umask($oldumask);
                   2423:     }  else {
                   2424: 	&Failure($client, "not_right_domain\n",
                   2425: 		$userinput);	# Even if we are multihomed.
                   2426:     
                   2427:     }
                   2428:     return 1;
                   2429: 
                   2430: }
                   2431: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
                   2432: 
                   2433: #
                   2434: #   Change the authentication method of a user.  Note that this may
                   2435: #   also implicitly change the user's password if, for example, the user is
                   2436: #   joining an existing authentication realm.  Known authentication realms at
                   2437: #   this time are:
                   2438: #    internal   - Purely internal password file (only loncapa knows this user)
                   2439: #    local      - Institutionally written authentication module.
                   2440: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
                   2441: #    kerb4      - kerberos version 4
                   2442: #    kerb5      - kerberos version 5
                   2443: #
                   2444: # Parameters:
                   2445: #    $cmd      - The command that got us here.
                   2446: #    $tail     - Tail of the command (remaining parameters).
                   2447: #    $client   - File descriptor connected to client.
                   2448: # Returns
                   2449: #     0        - Requested to exit, caller should shut down.
                   2450: #     1        - Continue processing.
                   2451: # Implicit inputs:
                   2452: #    The authentication systems describe above have their own forms of implicit
                   2453: #    input into the authentication process that are described above.
1.287     foxr     2454: # NOTE:
                   2455: #   This is also used to change the authentication credential values (e.g. passwd).
                   2456: #   
1.225     foxr     2457: #
                   2458: sub change_authentication_handler {
                   2459: 
                   2460:     my ($cmd, $tail, $client) = @_;
                   2461:    
                   2462:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
                   2463: 
                   2464:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2465:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
                   2466:     if ($udom ne $currentdomainid) {
                   2467: 	&Failure( $client, "not_right_domain\n", $client);
                   2468:     } else {
                   2469: 	
                   2470: 	chomp($npass);
                   2471: 	
                   2472: 	$npass=&unescape($npass);
1.261     foxr     2473: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
1.225     foxr     2474: 	my $passfilename = &password_path($udom, $uname);
                   2475: 	if ($passfilename) {	# Not allowed to create a new user!!
1.287     foxr     2476: 	    # If just changing the unix passwd. need to arrange to run
1.502     raeburn  2477: 	    # passwd since otherwise make_passwd_file will fail as 
                   2478: 	    # creation of unix authenticated users is no longer supported
                   2479:             # except from the command line, when running make_domain_coordinator.pl
1.287     foxr     2480: 
                   2481: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
                   2482: 		my $result = &change_unix_password($uname, $npass);
                   2483: 		&logthis("Result of password change for $uname: ".$result);
                   2484: 		if ($result eq "ok") {
1.518     raeburn  2485:                     &update_passwd_history($uname,$udom,$umode,'changeuserauth'); 
1.390     raeburn  2486: 		    &Reply($client, \$result);
1.288     albertel 2487: 		} else {
1.387     albertel 2488: 		    &Failure($client, \$result);
1.287     foxr     2489: 		}
1.288     albertel 2490: 	    } else {
1.518     raeburn  2491: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2492:                                              $passfilename,'changeuserauth');
1.287     foxr     2493: 		#
                   2494: 		#  If the current auth mode is internal, and the old auth mode was
                   2495: 		#  unix, or krb*,  and the user is an author for this domain,
                   2496: 		#  re-run manage_permissions for that role in order to be able
                   2497: 		#  to take ownership of the construction space back to www:www
                   2498: 		#
1.502     raeburn  2499: 
                   2500: 
1.387     albertel 2501: 		&Reply($client, \$result, $userinput);
1.261     foxr     2502: 	    }
                   2503: 	       
                   2504: 
1.225     foxr     2505: 	} else {	       
1.251     foxr     2506: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
1.225     foxr     2507: 	}
                   2508:     }
                   2509:     return 1;
                   2510: }
                   2511: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
                   2512: 
1.518     raeburn  2513: sub update_passwd_history {
                   2514:     my ($uname,$udom,$umode,$context) = @_;
                   2515:     my $proname=&propath($udom,$uname);
                   2516:     my $now = time;
                   2517:     if (open(my $fh,">>$proname/passwd.log")) {
                   2518:         print $fh "$now:$umode:$context\n";
                   2519:         close($fh);
                   2520:     }
                   2521:     return;
                   2522: }
                   2523: 
1.225     foxr     2524: #
                   2525: #   Determines if this is the home server for a user.  The home server
                   2526: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
                   2527: #   to do is determine if this file exists.
                   2528: #
                   2529: # Parameters:
                   2530: #    $cmd      - The command that got us here.
                   2531: #    $tail     - Tail of the command (remaining parameters).
                   2532: #    $client   - File descriptor connected to client.
                   2533: # Returns
                   2534: #     0        - Requested to exit, caller should shut down.
                   2535: #     1        - Continue processing.
                   2536: # Implicit inputs:
                   2537: #    The authentication systems describe above have their own forms of implicit
                   2538: #    input into the authentication process that are described above.
                   2539: #
                   2540: sub is_home_handler {
                   2541:     my ($cmd, $tail, $client) = @_;
                   2542:    
                   2543:     my $userinput  = "$cmd:$tail";
                   2544:    
                   2545:     my ($udom,$uname)=split(/:/,$tail);
                   2546:     chomp($uname);
                   2547:     my $passfile = &password_filename($udom, $uname);
                   2548:     if($passfile) {
                   2549: 	&Reply( $client, "found\n", $userinput);
                   2550:     } else {
                   2551: 	&Failure($client, "not_found\n", $userinput);
                   2552:     }
                   2553:     return 1;
                   2554: }
                   2555: &register_handler("home", \&is_home_handler, 0,1,0);
                   2556: 
                   2557: #
1.434     www      2558: #   Process an update request for a resource.
                   2559: #   A resource has been modified that we hold a subscription to.
1.225     foxr     2560: #   If the resource is not local, then we must update, or at least invalidate our
                   2561: #   cached copy of the resource. 
                   2562: # Parameters:
                   2563: #    $cmd      - The command that got us here.
                   2564: #    $tail     - Tail of the command (remaining parameters).
                   2565: #    $client   - File descriptor connected to client.
                   2566: # Returns
                   2567: #     0        - Requested to exit, caller should shut down.
                   2568: #     1        - Continue processing.
                   2569: # Implicit inputs:
                   2570: #    The authentication systems describe above have their own forms of implicit
                   2571: #    input into the authentication process that are described above.
                   2572: #
                   2573: sub update_resource_handler {
                   2574: 
                   2575:     my ($cmd, $tail, $client) = @_;
                   2576:    
                   2577:     my $userinput = "$cmd:$tail";
                   2578:    
                   2579:     my $fname= $tail;		# This allows interactive testing
                   2580: 
                   2581: 
                   2582:     my $ownership=ishome($fname);
                   2583:     if ($ownership eq 'not_owner') {
                   2584: 	if (-e $fname) {
1.434     www      2585:             # Delete preview file, if exists
                   2586:             unlink("$fname.tmp");
                   2587:             # Get usage stats
1.225     foxr     2588: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
                   2589: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
                   2590: 	    my $now=time;
                   2591: 	    my $since=$now-$atime;
1.434     www      2592:             # If the file has not been used within lonExpire seconds,
                   2593:             # unsubscribe from it and delete local copy
1.225     foxr     2594: 	    if ($since>$perlvar{'lonExpire'}) {
1.365     albertel 2595: 		my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
1.308     albertel 2596: 		&devalidate_meta_cache($fname);
1.225     foxr     2597: 		unlink("$fname");
1.334     albertel 2598: 		unlink("$fname.meta");
1.225     foxr     2599: 	    } else {
1.434     www      2600:             # Yes, this is in active use. Get a fresh copy. Since it might be in
                   2601:             # very active use and huge (like a movie), copy it to "in.transfer" filename first.
1.225     foxr     2602: 		my $transname="$fname.in.transfer";
1.365     albertel 2603: 		my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
1.225     foxr     2604: 		my $response;
1.537     raeburn  2605: # FIXME: cannot replicate files that take more than two minutes to transfer -- needs checking now 1200s timeout used
                   2606: # for LWP request.
                   2607: 		my $request=new HTTP::Request('GET',"$remoteurl");
                   2608:                 $response=&LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,0,1);
1.225     foxr     2609: 		if ($response->is_error()) {
1.541     raeburn  2610:                     my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
                   2611:                     &devalidate_meta_cache($fname);
                   2612:                     if (-e $transname) {
                   2613:                         unlink($transname);
                   2614:                     }
                   2615:                     unlink($fname);
1.225     foxr     2616: 		    my $message=$response->status_line;
                   2617: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2618: 		} else {
                   2619: 		    if ($remoteurl!~/\.meta$/) {
1.537     raeburn  2620: 			my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2621:                         my $mresponse = &LONCAPA::LWPReq::makerequest($clientname,$mrequest,$fname.'.meta',\%perlvar,120,0,1);
                   2622: 			if ($mresponse->is_error()) {
                   2623: 			    unlink($fname.'.meta');
1.225     foxr     2624: 			}
                   2625: 		    }
1.434     www      2626:                     # we successfully transfered, copy file over to real name
1.225     foxr     2627: 		    rename($transname,$fname);
1.308     albertel 2628: 		    &devalidate_meta_cache($fname);
1.225     foxr     2629: 		}
                   2630: 	    }
                   2631: 	    &Reply( $client, "ok\n", $userinput);
                   2632: 	} else {
                   2633: 	    &Failure($client, "not_found\n", $userinput);
                   2634: 	}
                   2635:     } else {
                   2636: 	&Failure($client, "rejected\n", $userinput);
                   2637:     }
                   2638:     return 1;
                   2639: }
                   2640: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
                   2641: 
1.308     albertel 2642: sub devalidate_meta_cache {
                   2643:     my ($url) = @_;
                   2644:     use Cache::Memcached;
                   2645:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.365     albertel 2646:     $url = &Apache::lonnet::declutter($url);
1.308     albertel 2647:     $url =~ s-\.meta$--;
                   2648:     my $id = &escape('meta:'.$url);
                   2649:     $memcache->delete($id);
                   2650: }
                   2651: 
1.225     foxr     2652: #
1.226     foxr     2653: #   Fetch a user file from a remote server to the user's home directory
                   2654: #   userfiles subdir.
1.225     foxr     2655: # Parameters:
                   2656: #    $cmd      - The command that got us here.
                   2657: #    $tail     - Tail of the command (remaining parameters).
                   2658: #    $client   - File descriptor connected to client.
                   2659: # Returns
                   2660: #     0        - Requested to exit, caller should shut down.
                   2661: #     1        - Continue processing.
                   2662: #
                   2663: sub fetch_user_file_handler {
                   2664: 
                   2665:     my ($cmd, $tail, $client) = @_;
                   2666: 
                   2667:     my $userinput = "$cmd:$tail";
                   2668:     my $fname           = $tail;
1.232     foxr     2669:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1.225     foxr     2670:     my $udir=&propath($udom,$uname).'/userfiles';
                   2671:     unless (-e $udir) {
                   2672: 	mkdir($udir,0770); 
                   2673:     }
1.232     foxr     2674:     Debug("fetch user file for $fname");
1.225     foxr     2675:     if (-e $udir) {
                   2676: 	$ufile=~s/^[\.\~]+//;
1.232     foxr     2677: 
                   2678: 	# IF necessary, create the path right down to the file.
                   2679: 	# Note that any regular files in the way of this path are
                   2680: 	# wiped out to deal with some earlier folly of mine.
                   2681: 
1.267     raeburn  2682: 	if (!&mkpath($udir.'/'.$ufile)) {
1.264     albertel 2683: 	    &Failure($client, "unable_to_create\n", $userinput);	    
1.232     foxr     2684: 	}
                   2685: 
1.225     foxr     2686: 	my $destname=$udir.'/'.$ufile;
                   2687: 	my $transname=$udir.'/'.$ufile.'.in.transit';
1.476     raeburn  2688:         my $clientprotocol=$Apache::lonnet::protocol{$clientname};
                   2689:         $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.486     raeburn  2690: 	my $clienthost = &Apache::lonnet::hostname($clientname);
                   2691: 	my $remoteurl=$clientprotocol.'://'.$clienthost.'/userfiles/'.$fname;
1.225     foxr     2692: 	my $response;
1.232     foxr     2693: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
1.537     raeburn  2694: 	my $request=new HTTP::Request('GET',"$remoteurl");
                   2695:         my $verifycert = 1;
                   2696:         my @machine_ids = &Apache::lonnet::current_machine_ids();
                   2697:         if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   2698:             $verifycert = 0;
                   2699:         }
                   2700:         $response = &LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,$verifycert);
1.225     foxr     2701: 	if ($response->is_error()) {
                   2702: 	    unlink($transname);
                   2703: 	    my $message=$response->status_line;
                   2704: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2705: 	    &Failure($client, "failed\n", $userinput);
                   2706: 	} else {
1.232     foxr     2707: 	    Debug("Renaming $transname to $destname");
1.225     foxr     2708: 	    if (!rename($transname,$destname)) {
                   2709: 		&logthis("Unable to move $transname to $destname");
                   2710: 		unlink($transname);
                   2711: 		&Failure($client, "failed\n", $userinput);
                   2712: 	    } else {
1.495     raeburn  2713:                 if ($fname =~ /^default.+\.(page|sequence)$/) {
                   2714:                     my ($major,$minor) = split(/\./,$clientversion);
                   2715:                     if (($major < 2) || ($major == 2 && $minor < 11)) {
                   2716:                         my $now = time;
                   2717:                         &Apache::lonnet::do_cache_new('crschange',$udom.'_'.$uname,$now,600);
                   2718:                         my $key = &escape('internal.contentchange');
                   2719:                         my $what = "$key=$now";
                   2720:                         my $hashref = &tie_user_hash($udom,$uname,'environment',
                   2721:                                                      &GDBM_WRCREAT(),"P",$what);
                   2722:                         if ($hashref) {
                   2723:                             $hashref->{$key}=$now;
                   2724:                             if (!&untie_user_hash($hashref)) {
                   2725:                                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   2726:                                          "when updating internal.contentchange");
                   2727:                             }
                   2728:                         }
                   2729:                     }
                   2730:                 }
1.225     foxr     2731: 		&Reply($client, "ok\n", $userinput);
                   2732: 	    }
                   2733: 	}   
                   2734:     } else {
                   2735: 	&Failure($client, "not_home\n", $userinput);
                   2736:     }
                   2737:     return 1;
                   2738: }
                   2739: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
                   2740: 
1.226     foxr     2741: #
                   2742: #   Remove a file from a user's home directory userfiles subdirectory.
                   2743: # Parameters:
                   2744: #    cmd   - the Lond request keyword that got us here.
                   2745: #    tail  - the part of the command past the keyword.
                   2746: #    client- File descriptor connected with the client.
                   2747: #
                   2748: # Returns:
                   2749: #    1    - Continue processing.
                   2750: sub remove_user_file_handler {
                   2751:     my ($cmd, $tail, $client) = @_;
                   2752: 
                   2753:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2754: 
                   2755:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2756:     if ($ufile =~m|/\.\./|) {
                   2757: 	# any files paths with /../ in them refuse 
                   2758: 	# to deal with
                   2759: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2760:     } else {
                   2761: 	my $udir = &propath($udom,$uname);
                   2762: 	if (-e $udir) {
                   2763: 	    my $file=$udir.'/userfiles/'.$ufile;
                   2764: 	    if (-e $file) {
1.253     foxr     2765: 		#
                   2766: 		#   If the file is a regular file unlink is fine...
1.520     raeburn  2767: 		#   However it's possible the client wants a dir 
                   2768: 		#   removed, in which case rmdir is more appropriate.
                   2769: 		#   Note: rmdir will only remove an empty directory.
1.253     foxr     2770: 		#
1.240     banghart 2771: 	        if (-f $file){
1.241     albertel 2772: 		    unlink($file);
1.520     raeburn  2773:                     # for html files remove the associated .bak file 
                   2774:                     # which may have been created by the editor.
                   2775:                     if ($ufile =~ m{^((docs|supplemental)/(?:\d+|default)/\d+(?:|/.+)/)[^/]+\.x?html?$}i) {
                   2776:                         my $path = $1;
                   2777:                         if (-e $file.'.bak') {
                   2778:                             unlink($file.'.bak');
                   2779:                         }
                   2780:                     }
1.241     albertel 2781: 		} elsif(-d $file) {
                   2782: 		    rmdir($file);
1.240     banghart 2783: 		}
1.226     foxr     2784: 		if (-e $file) {
1.253     foxr     2785: 		    #  File is still there after we deleted it ?!?
                   2786: 
1.226     foxr     2787: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2788: 		} else {
                   2789: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2790: 		}
                   2791: 	    } else {
                   2792: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2793: 	    }
                   2794: 	} else {
                   2795: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2796: 	}
                   2797:     }
                   2798:     return 1;
                   2799: }
                   2800: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
                   2801: 
1.236     albertel 2802: #
                   2803: #   make a directory in a user's home directory userfiles subdirectory.
                   2804: # Parameters:
                   2805: #    cmd   - the Lond request keyword that got us here.
                   2806: #    tail  - the part of the command past the keyword.
                   2807: #    client- File descriptor connected with the client.
                   2808: #
                   2809: # Returns:
                   2810: #    1    - Continue processing.
                   2811: sub mkdir_user_file_handler {
                   2812:     my ($cmd, $tail, $client) = @_;
                   2813: 
                   2814:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2815:     $dir=&unescape($dir);
                   2816:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2817:     if ($ufile =~m|/\.\./|) {
                   2818: 	# any files paths with /../ in them refuse 
                   2819: 	# to deal with
                   2820: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2821:     } else {
                   2822: 	my $udir = &propath($udom,$uname);
                   2823: 	if (-e $udir) {
1.264     albertel 2824: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
                   2825: 	    if (!&mkpath($newdir)) {
                   2826: 		&Failure($client, "failed\n", "$cmd:$tail");
1.236     albertel 2827: 	    }
1.264     albertel 2828: 	    &Reply($client, "ok\n", "$cmd:$tail");
1.236     albertel 2829: 	} else {
                   2830: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2831: 	}
                   2832:     }
                   2833:     return 1;
                   2834: }
                   2835: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
                   2836: 
1.237     albertel 2837: #
                   2838: #   rename a file in a user's home directory userfiles subdirectory.
                   2839: # Parameters:
                   2840: #    cmd   - the Lond request keyword that got us here.
                   2841: #    tail  - the part of the command past the keyword.
                   2842: #    client- File descriptor connected with the client.
                   2843: #
                   2844: # Returns:
                   2845: #    1    - Continue processing.
                   2846: sub rename_user_file_handler {
                   2847:     my ($cmd, $tail, $client) = @_;
                   2848: 
                   2849:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
                   2850:     $old=&unescape($old);
                   2851:     $new=&unescape($new);
                   2852:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
                   2853: 	# any files paths with /../ in them refuse to deal with
                   2854: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2855:     } else {
                   2856: 	my $udir = &propath($udom,$uname);
                   2857: 	if (-e $udir) {
                   2858: 	    my $oldfile=$udir.'/userfiles/'.$old;
                   2859: 	    my $newfile=$udir.'/userfiles/'.$new;
                   2860: 	    if (-e $newfile) {
                   2861: 		&Failure($client, "exists\n", "$cmd:$tail");
                   2862: 	    } elsif (! -e $oldfile) {
                   2863: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2864: 	    } else {
                   2865: 		if (!rename($oldfile,$newfile)) {
                   2866: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2867: 		} else {
                   2868: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2869: 		}
                   2870: 	    }
                   2871: 	} else {
                   2872: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2873: 	}
                   2874:     }
                   2875:     return 1;
                   2876: }
                   2877: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
                   2878: 
1.227     foxr     2879: #
1.382     albertel 2880: #  Checks if the specified user has an active session on the server
                   2881: #  return ok if so, not_found if not
                   2882: #
                   2883: # Parameters:
                   2884: #   cmd      - The request keyword that dispatched to tus.
                   2885: #   tail     - The tail of the request (colon separated parameters).
                   2886: #   client   - Filehandle open on the client.
                   2887: # Return:
                   2888: #    1.
                   2889: sub user_has_session_handler {
                   2890:     my ($cmd, $tail, $client) = @_;
                   2891: 
                   2892:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
                   2893:     
                   2894:     opendir(DIR,$perlvar{'lonIDsDir'});
                   2895:     my $filename;
                   2896:     while ($filename=readdir(DIR)) {
                   2897: 	last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
                   2898:     }
                   2899:     if ($filename) {
                   2900: 	&Reply($client, "ok\n", "$cmd:$tail");
                   2901:     } else {
                   2902: 	&Failure($client, "not_found\n", "$cmd:$tail");
                   2903:     }
                   2904:     return 1;
                   2905: 
                   2906: }
                   2907: &register_handler("userhassession", \&user_has_session_handler, 0,1,0);
                   2908: 
                   2909: #
1.263     albertel 2910: #  Authenticate access to a user file by checking that the token the user's 
                   2911: #  passed also exists in their session file
1.227     foxr     2912: #
                   2913: # Parameters:
                   2914: #   cmd      - The request keyword that dispatched to tus.
                   2915: #   tail     - The tail of the request (colon separated parameters).
                   2916: #   client   - Filehandle open on the client.
                   2917: # Return:
                   2918: #    1.
                   2919: sub token_auth_user_file_handler {
                   2920:     my ($cmd, $tail, $client) = @_;
                   2921: 
                   2922:     my ($fname, $session) = split(/:/, $tail);
                   2923:     
                   2924:     chomp($session);
1.393     raeburn  2925:     my $reply="non_auth";
1.343     albertel 2926:     my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
                   2927:     if (open(ENVIN,"$file")) {
1.332     albertel 2928: 	flock(ENVIN,LOCK_SH);
1.343     albertel 2929: 	tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
                   2930: 	if (exists($disk_env{"userfile.$fname"})) {
1.393     raeburn  2931: 	    $reply="ok";
1.343     albertel 2932: 	} else {
                   2933: 	    foreach my $envname (keys(%disk_env)) {
                   2934: 		if ($envname=~ m|^userfile\.\Q$fname\E|) {
1.393     raeburn  2935: 		    $reply="ok";
1.343     albertel 2936: 		    last;
                   2937: 		}
                   2938: 	    }
1.227     foxr     2939: 	}
1.343     albertel 2940: 	untie(%disk_env);
1.227     foxr     2941: 	close(ENVIN);
1.387     albertel 2942: 	&Reply($client, \$reply, "$cmd:$tail");
1.227     foxr     2943:     } else {
                   2944: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
                   2945:     }
                   2946:     return 1;
                   2947: 
                   2948: }
                   2949: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229     foxr     2950: 
                   2951: #
                   2952: #   Unsubscribe from a resource.
                   2953: #
                   2954: # Parameters:
                   2955: #    $cmd      - The command that got us here.
                   2956: #    $tail     - Tail of the command (remaining parameters).
                   2957: #    $client   - File descriptor connected to client.
                   2958: # Returns
                   2959: #     0        - Requested to exit, caller should shut down.
                   2960: #     1        - Continue processing.
                   2961: #
                   2962: sub unsubscribe_handler {
                   2963:     my ($cmd, $tail, $client) = @_;
                   2964: 
                   2965:     my $userinput= "$cmd:$tail";
                   2966:     
                   2967:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
                   2968: 
                   2969:     &Debug("Unsubscribing $fname");
                   2970:     if (-e $fname) {
                   2971: 	&Debug("Exists");
                   2972: 	&Reply($client, &unsub($fname,$clientip), $userinput);
                   2973:     } else {
                   2974: 	&Failure($client, "not_found\n", $userinput);
                   2975:     }
                   2976:     return 1;
                   2977: }
                   2978: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
1.263     albertel 2979: 
1.230     foxr     2980: #   Subscribe to a resource
                   2981: #
                   2982: # Parameters:
                   2983: #    $cmd      - The command that got us here.
                   2984: #    $tail     - Tail of the command (remaining parameters).
                   2985: #    $client   - File descriptor connected to client.
                   2986: # Returns
                   2987: #     0        - Requested to exit, caller should shut down.
                   2988: #     1        - Continue processing.
                   2989: #
                   2990: sub subscribe_handler {
                   2991:     my ($cmd, $tail, $client)= @_;
                   2992: 
                   2993:     my $userinput  = "$cmd:$tail";
                   2994: 
                   2995:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
                   2996: 
                   2997:     return 1;
                   2998: }
                   2999: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
                   3000: 
                   3001: #
1.379     albertel 3002: #   Determine the latest version of a resource (it looks for the highest
                   3003: #   past version and then returns that +1)
1.230     foxr     3004: #
                   3005: # Parameters:
                   3006: #    $cmd      - The command that got us here.
                   3007: #    $tail     - Tail of the command (remaining parameters).
1.379     albertel 3008: #                 (Should consist of an absolute path to a file)
1.230     foxr     3009: #    $client   - File descriptor connected to client.
                   3010: # Returns
                   3011: #     0        - Requested to exit, caller should shut down.
                   3012: #     1        - Continue processing.
                   3013: #
                   3014: sub current_version_handler {
                   3015:     my ($cmd, $tail, $client) = @_;
                   3016: 
                   3017:     my $userinput= "$cmd:$tail";
                   3018:    
                   3019:     my $fname   = $tail;
                   3020:     &Reply( $client, &currentversion($fname)."\n", $userinput);
                   3021:     return 1;
                   3022: 
                   3023: }
                   3024: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
                   3025: 
                   3026: #  Make an entry in a user's activity log.
                   3027: #
                   3028: # Parameters:
                   3029: #    $cmd      - The command that got us here.
                   3030: #    $tail     - Tail of the command (remaining parameters).
                   3031: #    $client   - File descriptor connected to client.
                   3032: # Returns
                   3033: #     0        - Requested to exit, caller should shut down.
                   3034: #     1        - Continue processing.
                   3035: #
                   3036: sub activity_log_handler {
                   3037:     my ($cmd, $tail, $client) = @_;
                   3038: 
                   3039: 
                   3040:     my $userinput= "$cmd:$tail";
                   3041: 
                   3042:     my ($udom,$uname,$what)=split(/:/,$tail);
                   3043:     chomp($what);
                   3044:     my $proname=&propath($udom,$uname);
                   3045:     my $now=time;
                   3046:     my $hfh;
                   3047:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
                   3048: 	print $hfh "$now:$clientname:$what\n";
                   3049: 	&Reply( $client, "ok\n", $userinput); 
                   3050:     } else {
                   3051: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
                   3052: 		 ."while attempting log\n", 
                   3053: 		 $userinput);
                   3054:     }
                   3055: 
                   3056:     return 1;
                   3057: }
1.263     albertel 3058: &register_handler("log", \&activity_log_handler, 0, 1, 0);
1.230     foxr     3059: 
                   3060: #
                   3061: #   Put a namespace entry in a user profile hash.
                   3062: #   My druthers would be for this to be an encrypted interaction too.
                   3063: #   anything that might be an inadvertent covert channel about either
                   3064: #   user authentication or user personal information....
                   3065: #
                   3066: # Parameters:
                   3067: #    $cmd      - The command that got us here.
                   3068: #    $tail     - Tail of the command (remaining parameters).
                   3069: #    $client   - File descriptor connected to client.
                   3070: # Returns
                   3071: #     0        - Requested to exit, caller should shut down.
                   3072: #     1        - Continue processing.
                   3073: #
                   3074: sub put_user_profile_entry {
                   3075:     my ($cmd, $tail, $client)  = @_;
1.229     foxr     3076: 
1.230     foxr     3077:     my $userinput = "$cmd:$tail";
                   3078:     
1.242     raeburn  3079:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
1.230     foxr     3080:     if ($namespace ne 'roles') {
                   3081: 	chomp($what);
                   3082: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3083: 				  &GDBM_WRCREAT(),"P",$what);
                   3084: 	if($hashref) {
                   3085: 	    my @pairs=split(/\&/,$what);
                   3086: 	    foreach my $pair (@pairs) {
                   3087: 		my ($key,$value)=split(/=/,$pair);
                   3088: 		$hashref->{$key}=$value;
                   3089: 	    }
1.311     albertel 3090: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3091: 		&Reply( $client, "ok\n", $userinput);
                   3092: 	    } else {
                   3093: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3094: 			"while attempting put\n", 
                   3095: 			$userinput);
                   3096: 	    }
                   3097: 	} else {
1.316     albertel 3098: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.230     foxr     3099: 		     "while attempting put\n", $userinput);
                   3100: 	}
                   3101:     } else {
                   3102:         &Failure( $client, "refused\n", $userinput);
                   3103:     }
                   3104:     
                   3105:     return 1;
                   3106: }
                   3107: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
                   3108: 
1.283     albertel 3109: #   Put a piece of new data in hash, returns error if entry already exists
                   3110: # Parameters:
                   3111: #    $cmd      - The command that got us here.
                   3112: #    $tail     - Tail of the command (remaining parameters).
                   3113: #    $client   - File descriptor connected to client.
                   3114: # Returns
                   3115: #     0        - Requested to exit, caller should shut down.
                   3116: #     1        - Continue processing.
                   3117: #
                   3118: sub newput_user_profile_entry {
                   3119:     my ($cmd, $tail, $client)  = @_;
                   3120: 
                   3121:     my $userinput = "$cmd:$tail";
                   3122: 
                   3123:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
                   3124:     if ($namespace eq 'roles') {
                   3125:         &Failure( $client, "refused\n", $userinput);
                   3126: 	return 1;
                   3127:     }
                   3128: 
                   3129:     chomp($what);
                   3130: 
                   3131:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3132: 				 &GDBM_WRCREAT(),"N",$what);
                   3133:     if(!$hashref) {
1.316     albertel 3134: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.283     albertel 3135: 		  "while attempting put\n", $userinput);
                   3136: 	return 1;
                   3137:     }
                   3138: 
                   3139:     my @pairs=split(/\&/,$what);
                   3140:     foreach my $pair (@pairs) {
                   3141: 	my ($key,$value)=split(/=/,$pair);
                   3142: 	if (exists($hashref->{$key})) {
1.513     raeburn  3143:             if (!&untie_user_hash($hashref)) {
                   3144:                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   3145:                          "while attempting newput - early out as key exists");
                   3146:             }
                   3147:             &Failure($client, "key_exists: ".$key."\n",$userinput);
                   3148:             return 1;
1.283     albertel 3149: 	}
                   3150:     }
                   3151: 
                   3152:     foreach my $pair (@pairs) {
                   3153: 	my ($key,$value)=split(/=/,$pair);
                   3154: 	$hashref->{$key}=$value;
                   3155:     }
                   3156: 
1.311     albertel 3157:     if (&untie_user_hash($hashref)) {
1.283     albertel 3158: 	&Reply( $client, "ok\n", $userinput);
                   3159:     } else {
                   3160: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3161: 		 "while attempting put\n", 
                   3162: 		 $userinput);
                   3163:     }
                   3164:     return 1;
                   3165: }
                   3166: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
                   3167: 
1.230     foxr     3168: # 
                   3169: #   Increment a profile entry in the user history file.
                   3170: #   The history contains keyword value pairs.  In this case,
                   3171: #   The value itself is a pair of numbers.  The first, the current value
                   3172: #   the second an increment that this function applies to the current
                   3173: #   value.
                   3174: #
                   3175: # Parameters:
                   3176: #    $cmd      - The command that got us here.
                   3177: #    $tail     - Tail of the command (remaining parameters).
                   3178: #    $client   - File descriptor connected to client.
                   3179: # Returns
                   3180: #     0        - Requested to exit, caller should shut down.
                   3181: #     1        - Continue processing.
                   3182: #
                   3183: sub increment_user_value_handler {
                   3184:     my ($cmd, $tail, $client) = @_;
                   3185:     
                   3186:     my $userinput   = "$cmd:$tail";
                   3187:     
                   3188:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
                   3189:     if ($namespace ne 'roles') {
                   3190:         chomp($what);
                   3191: 	my $hashref = &tie_user_hash($udom, $uname,
                   3192: 				     $namespace, &GDBM_WRCREAT(),
                   3193: 				     "P",$what);
                   3194: 	if ($hashref) {
                   3195: 	    my @pairs=split(/\&/,$what);
                   3196: 	    foreach my $pair (@pairs) {
                   3197: 		my ($key,$value)=split(/=/,$pair);
1.284     raeburn  3198:                 $value = &unescape($value);
1.230     foxr     3199: 		# We could check that we have a number...
                   3200: 		if (! defined($value) || $value eq '') {
                   3201: 		    $value = 1;
                   3202: 		}
                   3203: 		$hashref->{$key}+=$value;
1.284     raeburn  3204:                 if ($namespace eq 'nohist_resourcetracker') {
                   3205:                     if ($hashref->{$key} < 0) {
                   3206:                         $hashref->{$key} = 0;
                   3207:                     }
                   3208:                 }
1.230     foxr     3209: 	    }
1.311     albertel 3210: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3211: 		&Reply( $client, "ok\n", $userinput);
                   3212: 	    } else {
                   3213: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3214: 			 "while attempting inc\n", $userinput);
                   3215: 	    }
                   3216: 	} else {
                   3217: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3218: 		     "while attempting inc\n", $userinput);
                   3219: 	}
                   3220:     } else {
                   3221: 	&Failure($client, "refused\n", $userinput);
                   3222:     }
                   3223:     
                   3224:     return 1;
                   3225: }
                   3226: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
                   3227: 
                   3228: #
                   3229: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
                   3230: #   Each 'role' a user has implies a set of permissions.  Adding a new role
                   3231: #   for a person grants the permissions packaged with that role
                   3232: #   to that user when the role is selected.
                   3233: #
                   3234: # Parameters:
                   3235: #    $cmd       - The command string (rolesput).
                   3236: #    $tail      - The remainder of the request line.  For rolesput this
                   3237: #                 consists of a colon separated list that contains:
                   3238: #                 The domain and user that is granting the role (logged).
                   3239: #                 The domain and user that is getting the role.
                   3240: #                 The roles being granted as a set of & separated pairs.
                   3241: #                 each pair a key value pair.
                   3242: #    $client    - File descriptor connected to the client.
                   3243: # Returns:
                   3244: #     0         - If the daemon should exit
                   3245: #     1         - To continue processing.
                   3246: #
                   3247: #
                   3248: sub roles_put_handler {
                   3249:     my ($cmd, $tail, $client) = @_;
                   3250: 
                   3251:     my $userinput  = "$cmd:$tail";
                   3252: 
                   3253:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
                   3254:     
                   3255: 
                   3256:     my $namespace='roles';
                   3257:     chomp($what);
                   3258:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3259: 				 &GDBM_WRCREAT(), "P",
                   3260: 				 "$exedom:$exeuser:$what");
                   3261:     #
                   3262:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
                   3263:     #  handle is open for the minimal amount of time.  Since the flush
                   3264:     #  is done on close this improves the chances the log will be an un-
                   3265:     #  corrupted ordered thing.
                   3266:     if ($hashref) {
1.261     foxr     3267: 	my $pass_entry = &get_auth_type($udom, $uname);
                   3268: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
                   3269: 	$auth_type = $auth_type.":";
1.230     foxr     3270: 	my @pairs=split(/\&/,$what);
                   3271: 	foreach my $pair (@pairs) {
                   3272: 	    my ($key,$value)=split(/=/,$pair);
                   3273: 	    &manage_permissions($key, $udom, $uname,
1.260     foxr     3274: 			       $auth_type);
1.230     foxr     3275: 	    $hashref->{$key}=$value;
                   3276: 	}
1.311     albertel 3277: 	if (&untie_user_hash($hashref)) {
1.230     foxr     3278: 	    &Reply($client, "ok\n", $userinput);
                   3279: 	} else {
                   3280: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3281: 		     "while attempting rolesput\n", $userinput);
                   3282: 	}
                   3283:     } else {
                   3284: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3285: 		 "while attempting rolesput\n", $userinput);
                   3286:     }
                   3287:     return 1;
                   3288: }
                   3289: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
                   3290: 
                   3291: #
1.231     foxr     3292: #   Deletes (removes) a role for a user.   This is equivalent to removing
                   3293: #  a permissions package associated with the role from the user's profile.
                   3294: #
                   3295: # Parameters:
                   3296: #     $cmd                 - The command (rolesdel)
                   3297: #     $tail                - The remainder of the request line. This consists
                   3298: #                             of:
                   3299: #                             The domain and user requesting the change (logged)
                   3300: #                             The domain and user being changed.
                   3301: #                             The roles being revoked.  These are shipped to us
                   3302: #                             as a bunch of & separated role name keywords.
                   3303: #     $client              - The file handle open on the client.
                   3304: # Returns:
                   3305: #     1                    - Continue processing
                   3306: #     0                    - Exit.
                   3307: #
                   3308: sub roles_delete_handler {
                   3309:     my ($cmd, $tail, $client)  = @_;
                   3310: 
                   3311:     my $userinput    = "$cmd:$tail";
                   3312:    
                   3313:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
                   3314:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
                   3315: 	   "what = ".$what);
                   3316:     my $namespace='roles';
                   3317:     chomp($what);
                   3318:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3319: 				 &GDBM_WRCREAT(), "D",
                   3320: 				 "$exedom:$exeuser:$what");
                   3321:     
                   3322:     if ($hashref) {
                   3323: 	my @rolekeys=split(/\&/,$what);
                   3324: 	
                   3325: 	foreach my $key (@rolekeys) {
                   3326: 	    delete $hashref->{$key};
                   3327: 	}
1.315     albertel 3328: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3329: 	    &Reply($client, "ok\n", $userinput);
                   3330: 	} else {
                   3331: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3332: 		     "while attempting rolesdel\n", $userinput);
                   3333: 	}
                   3334:     } else {
                   3335:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3336: 		 "while attempting rolesdel\n", $userinput);
                   3337:     }
                   3338:     
                   3339:     return 1;
                   3340: }
                   3341: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
                   3342: 
                   3343: # Unencrypted get from a user's profile database.  See 
                   3344: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
                   3345: # This function retrieves a keyed item from a specific named database in the
                   3346: # user's directory.
                   3347: #
                   3348: # Parameters:
                   3349: #   $cmd             - Command request keyword (get).
                   3350: #   $tail            - Tail of the command.  This is a colon separated list
                   3351: #                      consisting of the domain and username that uniquely
                   3352: #                      identifies the profile,
                   3353: #                      The 'namespace' which selects the gdbm file to 
                   3354: #                      do the lookup in, 
                   3355: #                      & separated list of keys to lookup.  Note that
                   3356: #                      the values are returned as an & separated list too.
                   3357: #   $client          - File descriptor open on the client.
                   3358: # Returns:
                   3359: #   1       - Continue processing.
                   3360: #   0       - Exit.
                   3361: #
                   3362: sub get_profile_entry {
                   3363:     my ($cmd, $tail, $client) = @_;
                   3364: 
                   3365:     my $userinput= "$cmd:$tail";
                   3366:    
                   3367:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3368:     chomp($what);
1.255     foxr     3369: 
1.390     raeburn  3370: 
1.255     foxr     3371:     my $replystring = read_profile($udom, $uname, $namespace, $what);
                   3372:     my ($first) = split(/:/,$replystring);
                   3373:     if($first ne "error") {
1.387     albertel 3374: 	&Reply($client, \$replystring, $userinput);
1.231     foxr     3375:     } else {
1.255     foxr     3376: 	&Failure($client, $replystring." while attempting get\n", $userinput);
1.231     foxr     3377:     }
                   3378:     return 1;
1.255     foxr     3379: 
                   3380: 
1.231     foxr     3381: }
                   3382: &register_handler("get", \&get_profile_entry, 0,1,0);
                   3383: 
                   3384: #
                   3385: #  Process the encrypted get request.  Note that the request is sent
                   3386: #  in clear, but the reply is encrypted.  This is a small covert channel:
                   3387: #  information about the sensitive keys is given to the snooper.  Just not
                   3388: #  information about the values of the sensitive key.  Hmm if I wanted to
                   3389: #  know these I'd snoop for the egets. Get the profile item names from them
                   3390: #  and then issue a get for them since there's no enforcement of the
                   3391: #  requirement of an encrypted get for particular profile items.  If I
                   3392: #  were re-doing this, I'd force the request to be encrypted as well as the
                   3393: #  reply.  I'd also just enforce encrypted transactions for all gets since
                   3394: #  that would prevent any covert channel snooping.
                   3395: #
                   3396: #  Parameters:
                   3397: #     $cmd               - Command keyword of request (eget).
1.536     raeburn  3398: #     $tail              - Tail of the command.  See GetProfileEntry
                   3399: #                          for more information about this.
1.231     foxr     3400: #     $client            - File open on the client.
                   3401: #  Returns:
                   3402: #     1      - Continue processing
                   3403: #     0      - server should exit.
                   3404: sub get_profile_entry_encrypted {
                   3405:     my ($cmd, $tail, $client) = @_;
                   3406: 
                   3407:     my $userinput = "$cmd:$tail";
                   3408:    
1.339     albertel 3409:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
1.231     foxr     3410:     chomp($what);
1.255     foxr     3411:     my $qresult = read_profile($udom, $uname, $namespace, $what);
                   3412:     my ($first) = split(/:/, $qresult);
                   3413:     if($first ne "error") {
                   3414: 	
                   3415: 	if ($cipher) {
                   3416: 	    my $cmdlength=length($qresult);
                   3417: 	    $qresult.="         ";
                   3418: 	    my $encqresult='';
                   3419: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   3420: 		$encqresult.= unpack("H16", 
                   3421: 				     $cipher->encrypt(substr($qresult,
                   3422: 							     $encidx,
                   3423: 							     8)));
                   3424: 	    }
                   3425: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   3426: 	} else {
1.231     foxr     3427: 		&Failure( $client, "error:no_key\n", $userinput);
                   3428: 	    }
                   3429:     } else {
1.255     foxr     3430: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
                   3431: 
1.231     foxr     3432:     }
                   3433:     
                   3434:     return 1;
                   3435: }
1.255     foxr     3436: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263     albertel 3437: 
1.231     foxr     3438: #
                   3439: #   Deletes a key in a user profile database.
                   3440: #   
                   3441: #   Parameters:
                   3442: #       $cmd                  - Command keyword (del).
                   3443: #       $tail                 - Command tail.  IN this case a colon
                   3444: #                               separated list containing:
                   3445: #                               The domain and user that identifies uniquely
                   3446: #                               the identity of the user.
                   3447: #                               The profile namespace (name of the profile
                   3448: #                               database file).
                   3449: #                               & separated list of keywords to delete.
                   3450: #       $client              - File open on client socket.
                   3451: # Returns:
                   3452: #     1   - Continue processing
                   3453: #     0   - Exit server.
                   3454: #
                   3455: #
                   3456: sub delete_profile_entry {
                   3457:     my ($cmd, $tail, $client) = @_;
                   3458: 
                   3459:     my $userinput = "cmd:$tail";
                   3460: 
                   3461:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3462:     chomp($what);
                   3463:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3464: 				 &GDBM_WRCREAT(),
                   3465: 				 "D",$what);
                   3466:     if ($hashref) {
                   3467:         my @keys=split(/\&/,$what);
                   3468: 	foreach my $key (@keys) {
                   3469: 	    delete($hashref->{$key});
                   3470: 	}
1.315     albertel 3471: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3472: 	    &Reply($client, "ok\n", $userinput);
                   3473: 	} else {
                   3474: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3475: 		    "while attempting del\n", $userinput);
                   3476: 	}
                   3477:     } else {
                   3478: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3479: 		 "while attempting del\n", $userinput);
                   3480:     }
                   3481:     return 1;
                   3482: }
                   3483: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263     albertel 3484: 
1.231     foxr     3485: #
                   3486: #  List the set of keys that are defined in a profile database file.
                   3487: #  A successful reply from this will contain an & separated list of
                   3488: #  the keys. 
                   3489: # Parameters:
                   3490: #     $cmd              - Command request (keys).
                   3491: #     $tail             - Remainder of the request, a colon separated
                   3492: #                         list containing domain/user that identifies the
                   3493: #                         user being queried, and the database namespace
                   3494: #                         (database filename essentially).
                   3495: #     $client           - File open on the client.
                   3496: #  Returns:
                   3497: #    1    - Continue processing.
                   3498: #    0    - Exit the server.
                   3499: #
                   3500: sub get_profile_keys {
                   3501:     my ($cmd, $tail, $client) = @_;
                   3502: 
                   3503:     my $userinput = "$cmd:$tail";
                   3504: 
                   3505:     my ($udom,$uname,$namespace)=split(/:/,$tail);
                   3506:     my $qresult='';
                   3507:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3508: 				  &GDBM_READER());
                   3509:     if ($hashref) {
                   3510: 	foreach my $key (keys %$hashref) {
                   3511: 	    $qresult.="$key&";
                   3512: 	}
1.315     albertel 3513: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3514: 	    $qresult=~s/\&$//;
1.387     albertel 3515: 	    &Reply($client, \$qresult, $userinput);
1.231     foxr     3516: 	} else {
                   3517: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3518: 		    "while attempting keys\n", $userinput);
                   3519: 	}
                   3520:     } else {
                   3521: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3522: 		 "while attempting keys\n", $userinput);
                   3523:     }
                   3524:    
                   3525:     return 1;
                   3526: }
                   3527: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
                   3528: 
                   3529: #
                   3530: #   Dump the contents of a user profile database.
                   3531: #   Note that this constitutes a very large covert channel too since
                   3532: #   the dump will return sensitive information that is not encrypted.
                   3533: #   The naive security assumption is that the session negotiation ensures
                   3534: #   our client is trusted and I don't believe that's assured at present.
                   3535: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
                   3536: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
                   3537: # 
                   3538: #  Parameters:
                   3539: #     $cmd           - The command request keyword (currentdump).
                   3540: #     $tail          - Remainder of the request, consisting of a colon
                   3541: #                      separated list that has the domain/username and
                   3542: #                      the namespace to dump (database file).
                   3543: #     $client        - file open on the remote client.
                   3544: # Returns:
                   3545: #     1    - Continue processing.
                   3546: #     0    - Exit the server.
                   3547: #
                   3548: sub dump_profile_database {
                   3549:     my ($cmd, $tail, $client) = @_;
                   3550: 
1.494     droeschl 3551:     my $res = LONCAPA::Lond::dump_profile_database($tail);
                   3552: 
                   3553:     if ($res =~ /^error:/) {
                   3554:         Failure($client, \$res, "$cmd:$tail");
                   3555:     } else {
                   3556:         Reply($client, \$res, "$cmd:$tail");
                   3557:     }
                   3558: 
                   3559:     return 1;  
                   3560: 
                   3561:     #TODO remove 
1.231     foxr     3562:     my $userinput = "$cmd:$tail";
                   3563:    
                   3564:     my ($udom,$uname,$namespace) = split(/:/,$tail);
                   3565:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3566: 				 &GDBM_READER());
                   3567:     if ($hashref) {
                   3568: 	# Structure of %data:
                   3569: 	# $data{$symb}->{$parameter}=$value;
                   3570: 	# $data{$symb}->{'v.'.$parameter}=$version;
                   3571: 	# since $parameter will be unescaped, we do not
                   3572:  	# have to worry about silly parameter names...
                   3573: 	
                   3574:         my $qresult='';
                   3575: 	my %data = ();                     # A hash of anonymous hashes..
                   3576: 	while (my ($key,$value) = each(%$hashref)) {
                   3577: 	    my ($v,$symb,$param) = split(/:/,$key);
                   3578: 	    next if ($v eq 'version' || $symb eq 'keys');
                   3579: 	    next if (exists($data{$symb}) && 
                   3580: 		     exists($data{$symb}->{$param}) &&
                   3581: 		     $data{$symb}->{'v.'.$param} > $v);
                   3582: 	    $data{$symb}->{$param}=$value;
                   3583: 	    $data{$symb}->{'v.'.$param}=$v;
                   3584: 	}
1.311     albertel 3585: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3586: 	    while (my ($symb,$param_hash) = each(%data)) {
                   3587: 		while(my ($param,$value) = each (%$param_hash)){
                   3588: 		    next if ($param =~ /^v\./);       # Ignore versions...
                   3589: 		    #
                   3590: 		    #   Just dump the symb=value pairs separated by &
                   3591: 		    #
                   3592: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
                   3593: 		}
                   3594: 	    }
                   3595: 	    chop($qresult);
1.387     albertel 3596: 	    &Reply($client , \$qresult, $userinput);
1.231     foxr     3597: 	} else {
                   3598: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3599: 		     "while attempting currentdump\n", $userinput);
                   3600: 	}
                   3601:     } else {
                   3602: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3603: 		"while attempting currentdump\n", $userinput);
                   3604:     }
                   3605: 
                   3606:     return 1;
                   3607: }
                   3608: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
                   3609: 
                   3610: #
                   3611: #   Dump a profile database with an optional regular expression
                   3612: #   to match against the keys.  In this dump, no effort is made
                   3613: #   to separate symb from version information. Presumably the
                   3614: #   databases that are dumped by this command are of a different
                   3615: #   structure.  Need to look at this and improve the documentation of
                   3616: #   both this and the currentdump handler.
                   3617: # Parameters:
                   3618: #    $cmd                     - The command keyword.
                   3619: #    $tail                    - All of the characters after the $cmd:
                   3620: #                               These are expected to be a colon
                   3621: #                               separated list containing:
                   3622: #                               domain/user - identifying the user.
                   3623: #                               namespace   - identifying the database.
                   3624: #                               regexp      - optional regular expression
                   3625: #                                             that is matched against
                   3626: #                                             database keywords to do
                   3627: #                                             selective dumps.
1.488     raeburn  3628: #                               range       - optional range of entries
                   3629: #                                             e.g., 10-20 would return the
                   3630: #                                             10th to 19th items, etc.  
1.231     foxr     3631: #   $client                   - Channel open on the client.
                   3632: # Returns:
                   3633: #    1    - Continue processing.
                   3634: # Side effects:
                   3635: #    response is written to $client.
                   3636: #
                   3637: sub dump_with_regexp {
                   3638:     my ($cmd, $tail, $client) = @_;
                   3639: 
1.494     droeschl 3640:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
1.490     droeschl 3641:     
                   3642:     if ($res =~ /^error:/) {
                   3643:         Failure($client, \$res, "$cmd:$tail");
                   3644:     } else {
                   3645:         Reply($client, \$res, "$cmd:$tail");
                   3646:     }
1.231     foxr     3647: 
                   3648:     return 1;
                   3649: }
                   3650: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
                   3651: 
                   3652: #  Store a set of key=value pairs associated with a versioned name.
                   3653: #
                   3654: #  Parameters:
                   3655: #    $cmd                - Request command keyword.
                   3656: #    $tail               - Tail of the request.  This is a colon
                   3657: #                          separated list containing:
                   3658: #                          domain/user - User and authentication domain.
                   3659: #                          namespace   - Name of the database being modified
                   3660: #                          rid         - Resource keyword to modify.
                   3661: #                          what        - new value associated with rid.
1.512     raeburn  3662: #                          laststore   - (optional) version=timestamp
                   3663: #                                        for most recent transaction for rid
                   3664: #                                        in namespace, when cstore was called
1.231     foxr     3665: #
                   3666: #    $client             - Socket open on the client.
                   3667: #
                   3668: #
                   3669: #  Returns:
                   3670: #      1 (keep on processing).
                   3671: #  Side-Effects:
                   3672: #    Writes to the client
1.512     raeburn  3673: #    Successful storage will cause either 'ok', or, if $laststore was included
                   3674: #    in the tail of the request, and the version number for the last transaction
                   3675: #    is larger than the version in $laststore, delay:$numtrans , where $numtrans
                   3676: #    is the number of store evevnts recorded for rid in namespace since
                   3677: #    lonnet::store() was called by the client.
                   3678: #
1.231     foxr     3679: sub store_handler {
                   3680:     my ($cmd, $tail, $client) = @_;
                   3681:  
                   3682:     my $userinput = "$cmd:$tail";
1.512     raeburn  3683:     chomp($tail);
                   3684:     my ($udom,$uname,$namespace,$rid,$what,$laststore) =split(/:/,$tail);
1.231     foxr     3685:     if ($namespace ne 'roles') {
                   3686: 
                   3687: 	my @pairs=split(/\&/,$what);
                   3688: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
1.268     albertel 3689: 				       &GDBM_WRCREAT(), "S",
1.231     foxr     3690: 				       "$rid:$what");
                   3691: 	if ($hashref) {
                   3692: 	    my $now = time;
1.512     raeburn  3693:             my $numtrans;
                   3694:             if ($laststore) {
                   3695:                 my ($previousversion,$previoustime) = split(/\=/,$laststore);
                   3696:                 my ($lastversion,$lasttime) = (0,0);
                   3697:                 $lastversion = $hashref->{"version:$rid"};
                   3698:                 if ($lastversion) {
                   3699:                     $lasttime = $hashref->{"$lastversion:$rid:timestamp"};
                   3700:                 }
                   3701:                 if (($previousversion) && ($previousversion !~ /\D/)) {
                   3702:                     if (($lastversion > $previousversion) && ($lasttime >= $previoustime)) {
                   3703:                         $numtrans = $lastversion - $previousversion;
                   3704:                     }
                   3705:                 } elsif ($lastversion) {
                   3706:                     $numtrans = $lastversion;
                   3707:                 }
                   3708:                 if ($numtrans) {
                   3709:                     $numtrans =~ s/D//g;
                   3710:                 }
                   3711:             }
1.231     foxr     3712: 	    $hashref->{"version:$rid"}++;
                   3713: 	    my $version=$hashref->{"version:$rid"};
                   3714: 	    my $allkeys=''; 
                   3715: 	    foreach my $pair (@pairs) {
                   3716: 		my ($key,$value)=split(/=/,$pair);
                   3717: 		$allkeys.=$key.':';
                   3718: 		$hashref->{"$version:$rid:$key"}=$value;
                   3719: 	    }
                   3720: 	    $hashref->{"$version:$rid:timestamp"}=$now;
                   3721: 	    $allkeys.='timestamp';
                   3722: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
1.311     albertel 3723: 	    if (&untie_user_hash($hashref)) {
1.512     raeburn  3724:                 my $msg = 'ok';
                   3725:                 if ($numtrans) {
                   3726:                     $msg = 'delay:'.$numtrans;
                   3727:                 }
                   3728: 		&Reply($client, "$msg\n", $userinput);
1.231     foxr     3729: 	    } else {
                   3730: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3731: 			"while attempting store\n", $userinput);
                   3732: 	    }
                   3733: 	} else {
                   3734: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3735: 		     "while attempting store\n", $userinput);
                   3736: 	}
                   3737:     } else {
                   3738: 	&Failure($client, "refused\n", $userinput);
                   3739:     }
                   3740: 
                   3741:     return 1;
                   3742: }
                   3743: &register_handler("store", \&store_handler, 0, 1, 0);
1.263     albertel 3744: 
1.323     albertel 3745: #  Modify a set of key=value pairs associated with a versioned name.
                   3746: #
                   3747: #  Parameters:
                   3748: #    $cmd                - Request command keyword.
                   3749: #    $tail               - Tail of the request.  This is a colon
                   3750: #                          separated list containing:
                   3751: #                          domain/user - User and authentication domain.
                   3752: #                          namespace   - Name of the database being modified
                   3753: #                          rid         - Resource keyword to modify.
                   3754: #                          v           - Version item to modify
                   3755: #                          what        - new value associated with rid.
                   3756: #
                   3757: #    $client             - Socket open on the client.
                   3758: #
                   3759: #
                   3760: #  Returns:
                   3761: #      1 (keep on processing).
                   3762: #  Side-Effects:
                   3763: #    Writes to the client
                   3764: sub putstore_handler {
                   3765:     my ($cmd, $tail, $client) = @_;
                   3766:  
                   3767:     my $userinput = "$cmd:$tail";
                   3768: 
                   3769:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
                   3770:     if ($namespace ne 'roles') {
                   3771: 
                   3772: 	chomp($what);
                   3773: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
                   3774: 				       &GDBM_WRCREAT(), "M",
                   3775: 				       "$rid:$v:$what");
                   3776: 	if ($hashref) {
                   3777: 	    my $now = time;
                   3778: 	    my %data = &hash_extract($what);
                   3779: 	    my @allkeys;
                   3780: 	    while (my($key,$value) = each(%data)) {
                   3781: 		push(@allkeys,$key);
                   3782: 		$hashref->{"$v:$rid:$key"} = $value;
                   3783: 	    }
                   3784: 	    my $allkeys = join(':',@allkeys);
                   3785: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
                   3786: 
                   3787: 	    if (&untie_user_hash($hashref)) {
                   3788: 		&Reply($client, "ok\n", $userinput);
                   3789: 	    } else {
                   3790: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3791: 			"while attempting store\n", $userinput);
                   3792: 	    }
                   3793: 	} else {
                   3794: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3795: 		     "while attempting store\n", $userinput);
                   3796: 	}
                   3797:     } else {
                   3798: 	&Failure($client, "refused\n", $userinput);
                   3799:     }
                   3800: 
                   3801:     return 1;
                   3802: }
                   3803: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
                   3804: 
                   3805: sub hash_extract {
                   3806:     my ($str)=@_;
                   3807:     my %hash;
                   3808:     foreach my $pair (split(/\&/,$str)) {
                   3809: 	my ($key,$value)=split(/=/,$pair);
                   3810: 	$hash{$key}=$value;
                   3811:     }
                   3812:     return (%hash);
                   3813: }
                   3814: sub hash_to_str {
                   3815:     my ($hash_ref)=@_;
                   3816:     my $str;
                   3817:     foreach my $key (keys(%$hash_ref)) {
                   3818: 	$str.=$key.'='.$hash_ref->{$key}.'&';
                   3819:     }
                   3820:     $str=~s/\&$//;
                   3821:     return $str;
                   3822: }
                   3823: 
1.231     foxr     3824: #
                   3825: #  Dump out all versions of a resource that has key=value pairs associated
                   3826: # with it for each version.  These resources are built up via the store
                   3827: # command.
                   3828: #
                   3829: #  Parameters:
                   3830: #     $cmd               - Command keyword.
                   3831: #     $tail              - Remainder of the request which consists of:
                   3832: #                          domain/user   - User and auth. domain.
                   3833: #                          namespace     - name of resource database.
                   3834: #                          rid           - Resource id.
                   3835: #    $client             - socket open on the client.
                   3836: #
                   3837: # Returns:
                   3838: #      1  indicating the caller should not yet exit.
                   3839: # Side-effects:
                   3840: #   Writes a reply to the client.
                   3841: #   The reply is a string of the following shape:
                   3842: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
                   3843: #    Where the 1 above represents version 1.
                   3844: #    this continues for all pairs of keys in all versions.
                   3845: #
                   3846: #
                   3847: #    
                   3848: #
                   3849: sub restore_handler {
                   3850:     my ($cmd, $tail, $client) = @_;
                   3851: 
                   3852:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
1.351     banghart 3853:     my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
1.352     albertel 3854:     $namespace=~s/\//\_/g;
1.350     albertel 3855:     $namespace = &LONCAPA::clean_username($namespace);
1.349     albertel 3856: 
1.231     foxr     3857:     chomp($rid);
                   3858:     my $qresult='';
1.309     albertel 3859:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
                   3860:     if ($hashref) {
                   3861: 	my $version=$hashref->{"version:$rid"};
1.231     foxr     3862: 	$qresult.="version=$version&";
                   3863: 	my $scope;
                   3864: 	for ($scope=1;$scope<=$version;$scope++) {
1.309     albertel 3865: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
1.231     foxr     3866: 	    my @keys=split(/:/,$vkeys);
                   3867: 	    my $key;
                   3868: 	    $qresult.="$scope:keys=$vkeys&";
                   3869: 	    foreach $key (@keys) {
1.309     albertel 3870: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
1.231     foxr     3871: 	    }                                  
                   3872: 	}
1.311     albertel 3873: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3874: 	    $qresult=~s/\&$//;
1.387     albertel 3875: 	    &Reply( $client, \$qresult, $userinput);
1.231     foxr     3876: 	} else {
                   3877: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3878: 		    "while attempting restore\n", $userinput);
                   3879: 	}
                   3880:     } else {
                   3881: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3882: 		"while attempting restore\n", $userinput);
                   3883:     }
                   3884:   
                   3885:     return 1;
                   3886: 
                   3887: 
                   3888: }
                   3889: &register_handler("restore", \&restore_handler, 0,1,0);
1.234     foxr     3890: 
                   3891: #
1.324     raeburn  3892: #   Add a chat message to a synchronous discussion board.
1.234     foxr     3893: #
                   3894: # Parameters:
                   3895: #    $cmd                - Request keyword.
                   3896: #    $tail               - Tail of the command. A colon separated list
                   3897: #                          containing:
                   3898: #                          cdom    - Domain on which the chat board lives
1.324     raeburn  3899: #                          cnum    - Course containing the chat board.
                   3900: #                          newpost - Body of the posting.
                   3901: #                          group   - Optional group, if chat board is only 
                   3902: #                                    accessible in a group within the course 
1.234     foxr     3903: #   $client              - Socket open on the client.
                   3904: # Returns:
                   3905: #   1    - Indicating caller should keep on processing.
                   3906: #
                   3907: # Side-effects:
                   3908: #   writes a reply to the client.
                   3909: #
                   3910: #
                   3911: sub send_chat_handler {
                   3912:     my ($cmd, $tail, $client) = @_;
                   3913: 
                   3914:     
                   3915:     my $userinput = "$cmd:$tail";
                   3916: 
1.324     raeburn  3917:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
                   3918:     &chat_add($cdom,$cnum,$newpost,$group);
1.234     foxr     3919:     &Reply($client, "ok\n", $userinput);
                   3920: 
                   3921:     return 1;
                   3922: }
                   3923: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263     albertel 3924: 
1.234     foxr     3925: #
1.324     raeburn  3926: #   Retrieve the set of chat messages from a discussion board.
1.234     foxr     3927: #
                   3928: #  Parameters:
                   3929: #    $cmd             - Command keyword that initiated the request.
                   3930: #    $tail            - Remainder of the request after the command
                   3931: #                       keyword.  In this case a colon separated list of
                   3932: #                       chat domain    - Which discussion board.
                   3933: #                       chat id        - Discussion thread(?)
                   3934: #                       domain/user    - Authentication domain and username
                   3935: #                                        of the requesting person.
1.324     raeburn  3936: #                       group          - Optional course group containing
                   3937: #                                        the board.      
1.234     foxr     3938: #   $client           - Socket open on the client program.
                   3939: # Returns:
                   3940: #    1     - continue processing
                   3941: # Side effects:
                   3942: #    Response is written to the client.
                   3943: #
                   3944: sub retrieve_chat_handler {
                   3945:     my ($cmd, $tail, $client) = @_;
                   3946: 
                   3947: 
                   3948:     my $userinput = "$cmd:$tail";
                   3949: 
1.324     raeburn  3950:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
1.234     foxr     3951:     my $reply='';
1.324     raeburn  3952:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
1.234     foxr     3953: 	$reply.=&escape($_).':';
                   3954:     }
                   3955:     $reply=~s/\:$//;
1.387     albertel 3956:     &Reply($client, \$reply, $userinput);
1.234     foxr     3957: 
                   3958: 
                   3959:     return 1;
                   3960: }
                   3961: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
                   3962: 
                   3963: #
                   3964: #  Initiate a query of an sql database.  SQL query repsonses get put in
                   3965: #  a file for later retrieval.  This prevents sql query results from
                   3966: #  bottlenecking the system.  Note that with loncnew, perhaps this is
                   3967: #  less of an issue since multiple outstanding requests can be concurrently
                   3968: #  serviced.
                   3969: #
                   3970: #  Parameters:
1.535     raeburn  3971: #     $cmd       - Command keyword that initiated the request.
1.234     foxr     3972: #     $tail      - Remainder of the command after the keyword.
                   3973: #                  For this function, this consists of a query and
                   3974: #                  3 arguments that are self-documentingly labelled
                   3975: #                  in the original arg1, arg2, arg3.
                   3976: #     $client    - Socket open on the client.
                   3977: # Return:
                   3978: #    1   - Indicating processing should continue.
                   3979: # Side-effects:
                   3980: #    a reply is written to $client.
                   3981: #
                   3982: sub send_query_handler {
                   3983:     my ($cmd, $tail, $client) = @_;
                   3984: 
                   3985:     my $userinput = "$cmd:$tail";
                   3986: 
                   3987:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
                   3988:     $query=~s/\n*$//g;
1.534     raeburn  3989:     if (($query eq 'usersearch') || ($query eq 'instdirsearch')) {
                   3990:         my $usersearchconf = &get_usersearch_config($currentdomainid,'directorysrch');
                   3991:         my $earlyout;
                   3992:         if (ref($usersearchconf) eq 'HASH') {
                   3993:             if ($currentdomainid eq $clienthomedom) {
                   3994:                 if ($query eq 'usersearch') {
                   3995:                     if ($usersearchconf->{'lcavailable'} eq '0') {
                   3996:                         $earlyout = 1;
                   3997:                     }
                   3998:                 } else {
                   3999:                     if ($usersearchconf->{'available'} eq '0') {
                   4000:                         $earlyout = 1;
                   4001:                     }
                   4002:                 }
                   4003:             } else {
                   4004:                 if ($query eq 'usersearch') {
                   4005:                     if ($usersearchconf->{'lclocalonly'}) {
                   4006:                         $earlyout = 1;
                   4007:                     }
                   4008:                 } else {
                   4009:                     if ($usersearchconf->{'localonly'}) {
                   4010:                         $earlyout = 1;
                   4011:                     }
                   4012:                 }
                   4013:             }
                   4014:         }
                   4015:         if ($earlyout) {
                   4016:             &Reply($client, "query_not_authorized\n");
                   4017:             return 1;
                   4018:         }
                   4019:     }
1.234     foxr     4020:     &Reply($client, "". &sql_reply("$clientname\&$query".
                   4021: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
                   4022: 	  $userinput);
                   4023:     
                   4024:     return 1;
                   4025: }
                   4026: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
                   4027: 
                   4028: #
                   4029: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
                   4030: #   The query is submitted via a "querysend" transaction.
                   4031: #   There it is passed on to the lonsql daemon, queued and issued to
                   4032: #   mysql.
                   4033: #     This transaction is invoked when the sql transaction is complete
                   4034: #   it stores the query results in flie and indicates query completion.
                   4035: #   presumably local software then fetches this response... I'm guessing
                   4036: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
                   4037: #   lonsql on completion of the query interacts with the lond of our
                   4038: #   client to do a query reply storing two files:
                   4039: #    - id     - The results of the query.
                   4040: #    - id.end - Indicating the transaction completed. 
                   4041: #    NOTE: id is a unique id assigned to the query and querysend time.
                   4042: # Parameters:
                   4043: #    $cmd        - Command keyword that initiated this request.
                   4044: #    $tail       - Remainder of the tail.  In this case that's a colon
                   4045: #                  separated list containing the query Id and the 
                   4046: #                  results of the query.
                   4047: #    $client     - Socket open on the client.
                   4048: # Return:
                   4049: #    1           - Indicating that we should continue processing.
                   4050: # Side effects:
                   4051: #    ok written to the client.
                   4052: #
                   4053: sub reply_query_handler {
                   4054:     my ($cmd, $tail, $client) = @_;
                   4055: 
                   4056: 
                   4057:     my $userinput = "$cmd:$tail";
                   4058: 
1.339     albertel 4059:     my ($id,$reply)=split(/:/,$tail); 
1.234     foxr     4060:     my $store;
                   4061:     my $execdir=$perlvar{'lonDaemons'};
                   4062:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
                   4063: 	$reply=~s/\&/\n/g;
                   4064: 	print $store $reply;
                   4065: 	close $store;
                   4066: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
                   4067: 	print $store2 "done\n";
                   4068: 	close $store2;
                   4069: 	&Reply($client, "ok\n", $userinput);
                   4070:     } else {
                   4071: 	&Failure($client, "error: ".($!+0)
                   4072: 		." IO::File->new Failed ".
                   4073: 		"while attempting queryreply\n", $userinput);
                   4074:     }
                   4075:  
                   4076: 
                   4077:     return 1;
                   4078: }
                   4079: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
                   4080: 
                   4081: #
                   4082: #  Process the courseidput request.  Not quite sure what this means
                   4083: #  at the system level sense.  It appears a gdbm file in the 
                   4084: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
                   4085: #  a set of entries made in that database.
                   4086: #
                   4087: # Parameters:
                   4088: #   $cmd      - The command keyword that initiated this request.
                   4089: #   $tail     - Tail of the command.  In this case consists of a colon
                   4090: #               separated list contaning the domain to apply this to and
                   4091: #               an ampersand separated list of keyword=value pairs.
1.272     raeburn  4092: #               Each value is a colon separated list that includes:  
                   4093: #               description, institutional code and course owner.
                   4094: #               For backward compatibility with versions included
                   4095: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
                   4096: #               code and/or course owner are preserved from the existing 
                   4097: #               record when writing a new record in response to 1.1 or 
                   4098: #               1.2 implementations of lonnet::flushcourselogs().   
                   4099: #                      
1.234     foxr     4100: #   $client   - Socket open on the client.
                   4101: # Returns:
                   4102: #   1    - indicating that processing should continue
                   4103: #
                   4104: # Side effects:
                   4105: #   reply is written to the client.
                   4106: #
                   4107: sub put_course_id_handler {
                   4108:     my ($cmd, $tail, $client) = @_;
                   4109: 
                   4110: 
                   4111:     my $userinput = "$cmd:$tail";
                   4112: 
1.266     raeburn  4113:     my ($udom, $what) = split(/:/, $tail,2);
1.234     foxr     4114:     chomp($what);
                   4115:     my $now=time;
                   4116:     my @pairs=split(/\&/,$what);
                   4117: 
                   4118:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4119:     if ($hashref) {
                   4120: 	foreach my $pair (@pairs) {
1.271     raeburn  4121:             my ($key,$courseinfo) = split(/=/,$pair,2);
                   4122:             $courseinfo =~ s/=/:/g;
1.384     raeburn  4123:             if (defined($hashref->{$key})) {
                   4124:                 my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
                   4125:                 if (ref($value) eq 'HASH') {
                   4126:                     my @items = ('description','inst_code','owner','type');
                   4127:                     my @new_items = split(/:/,$courseinfo,-1);
                   4128:                     my %storehash; 
                   4129:                     for (my $i=0; $i<@new_items; $i++) {
1.391     raeburn  4130:                         $storehash{$items[$i]} = &unescape($new_items[$i]);
1.384     raeburn  4131:                     }
                   4132:                     $hashref->{$key} = 
                   4133:                         &Apache::lonnet::freeze_escape(\%storehash);
                   4134:                     my $unesc_key = &unescape($key);
                   4135:                     $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4136:                     next;
1.383     raeburn  4137:                 }
1.384     raeburn  4138:             }
                   4139:             my @current_items = split(/:/,$hashref->{$key},-1);
                   4140:             shift(@current_items); # remove description
                   4141:             pop(@current_items);   # remove last access
                   4142:             my $numcurrent = scalar(@current_items);
                   4143:             if ($numcurrent > 3) {
                   4144:                 $numcurrent = 3;
                   4145:             }
                   4146:             my @new_items = split(/:/,$courseinfo,-1);
                   4147:             my $numnew = scalar(@new_items);
                   4148:             if ($numcurrent > 0) {
                   4149:                 if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2 
                   4150:                     for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
                   4151:                         $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
1.333     raeburn  4152:                     }
1.272     raeburn  4153:                 }
                   4154:             }
1.384     raeburn  4155:             $hashref->{$key}=$courseinfo.':'.$now;
1.234     foxr     4156: 	}
1.311     albertel 4157: 	if (&untie_domain_hash($hashref)) {
1.253     foxr     4158: 	    &Reply( $client, "ok\n", $userinput);
1.234     foxr     4159: 	} else {
1.253     foxr     4160: 	    &Failure($client, "error: ".($!+0)
1.234     foxr     4161: 		     ." untie(GDBM) Failed ".
                   4162: 		     "while attempting courseidput\n", $userinput);
                   4163: 	}
                   4164:     } else {
1.253     foxr     4165: 	&Failure($client, "error: ".($!+0)
1.234     foxr     4166: 		 ." tie(GDBM) Failed ".
                   4167: 		 "while attempting courseidput\n", $userinput);
                   4168:     }
                   4169: 
                   4170:     return 1;
                   4171: }
                   4172: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
                   4173: 
1.383     raeburn  4174: sub put_course_id_hash_handler {
                   4175:     my ($cmd, $tail, $client) = @_;
                   4176:     my $userinput = "$cmd:$tail";
1.384     raeburn  4177:     my ($udom,$mode,$what) = split(/:/, $tail,3);
1.383     raeburn  4178:     chomp($what);
                   4179:     my $now=time;
                   4180:     my @pairs=split(/\&/,$what);
1.384     raeburn  4181:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
1.383     raeburn  4182:     if ($hashref) {
                   4183:         foreach my $pair (@pairs) {
                   4184:             my ($key,$value)=split(/=/,$pair);
1.384     raeburn  4185:             my $unesc_key = &unescape($key);
                   4186:             if ($mode ne 'timeonly') {
                   4187:                 if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
                   4188:                     my $curritems = &Apache::lonnet::thaw_unescape($key); 
                   4189:                     if (ref($curritems) ne 'HASH') {
                   4190:                         my @current_items = split(/:/,$hashref->{$key},-1);
                   4191:                         my $lasttime = pop(@current_items);
                   4192:                         $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
                   4193:                     } else {
                   4194:                         $hashref->{&escape('lasttime:'.$unesc_key)} = '';
                   4195:                     }
                   4196:                 } 
                   4197:                 $hashref->{$key} = $value;
                   4198:             }
                   4199:             if ($mode ne 'notime') {
                   4200:                 $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4201:             }
1.383     raeburn  4202:         }
                   4203:         if (&untie_domain_hash($hashref)) {
                   4204:             &Reply($client, "ok\n", $userinput);
                   4205:         } else {
                   4206:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4207:                      "while attempting courseidputhash\n", $userinput);
                   4208:         }
                   4209:     } else {
                   4210:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4211:                   "while attempting courseidputhash\n", $userinput);
                   4212:     }
                   4213:     return 1;
                   4214: }
                   4215: &register_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
                   4216: 
1.234     foxr     4217: #  Retrieves the value of a course id resource keyword pattern
                   4218: #  defined since a starting date.  Both the starting date and the
                   4219: #  keyword pattern are optional.  If the starting date is not supplied it
                   4220: #  is treated as the beginning of time.  If the pattern is not found,
                   4221: #  it is treatred as "." matching everything.
                   4222: #
                   4223: #  Parameters:
                   4224: #     $cmd     - Command keyword that resulted in us being dispatched.
                   4225: #     $tail    - The remainder of the command that, in this case, consists
                   4226: #                of a colon separated list of:
                   4227: #                 domain   - The domain in which the course database is 
                   4228: #                            defined.
                   4229: #                 since    - Optional parameter describing the minimum
                   4230: #                            time of definition(?) of the resources that
                   4231: #                            will match the dump.
                   4232: #                 description - regular expression that is used to filter
                   4233: #                            the dump.  Only keywords matching this regexp
                   4234: #                            will be used.
1.272     raeburn  4235: #                 institutional code - optional supplied code to filter 
                   4236: #                            the dump. Only courses with an institutional code 
                   4237: #                            that match the supplied code will be returned.
1.336     raeburn  4238: #                 owner    - optional supplied username and domain of owner to
                   4239: #                            filter the dump.  Only courses for which the course
                   4240: #                            owner matches the supplied username and/or domain
                   4241: #                            will be returned. Pre-2.2.0 legacy entries from 
                   4242: #                            nohist_courseiddump will only contain usernames.
1.384     raeburn  4243: #                 type     - optional parameter for selection 
1.418     raeburn  4244: #                 regexp_ok - if 1 or -1 allow the supplied institutional code
                   4245: #                            filter to behave as a regular expression:
                   4246: #	                      1 will not exclude the course if the instcode matches the RE 
                   4247: #                            -1 will exclude the course if the instcode matches the RE
1.384     raeburn  4248: #                 rtn_as_hash - whether to return the information available for
                   4249: #                            each matched item as a frozen hash of all 
                   4250: #                            key, value pairs in the item's hash, or as a 
                   4251: #                            colon-separated list of (in order) description,
                   4252: #                            institutional code, and course owner.
1.404     raeburn  4253: #                 selfenrollonly - filter by courses allowing self-enrollment  
                   4254: #                                  now or in the future (selfenrollonly = 1).
                   4255: #                 catfilter - filter by course category, assigned to a course 
                   4256: #                             using manually defined categories (i.e., not
1.407     raeburn  4257: #                             self-cataloging based on on institutional code).   
1.404     raeburn  4258: #                 showhidden - include course in results even if course  
1.407     raeburn  4259: #                              was set to be excluded from course catalog (DC only).
1.404     raeburn  4260: #                 caller -  if set to 'coursecatalog', courses set to be hidden
                   4261: #                           from course catalog will be excluded from results (unless
                   4262: #                           overridden by "showhidden".
1.427     raeburn  4263: #                 cloner - escaped username:domain of course cloner (if picking course to
1.419     raeburn  4264: #                          clone).
                   4265: #                 cc_clone_list - escaped comma separated list of courses for which 
                   4266: #                                 course cloner has active CC role (and so can clone
                   4267: #                                 automatically).
1.427     raeburn  4268: #                 cloneonly - filter by courses for which cloner has rights to clone.
                   4269: #                 createdbefore - include courses for which creation date preceeded this date.
                   4270: #                 createdafter - include courses for which creation date followed this date.
                   4271: #                 creationcontext - include courses created in specified context 
1.404     raeburn  4272: #
1.445     raeburn  4273: #                 domcloner - flag to indicate if user can create CCs in course's domain.
1.505     raeburn  4274: #                             If so, ability to clone course is automatic.
                   4275: #                 hasuniquecode - filter by courses for which a six character unique code has 
                   4276: #                                 been set.
1.445     raeburn  4277: #
1.234     foxr     4278: #     $client  - The socket open on the client.
                   4279: # Returns:
                   4280: #    1     - Continue processing.
                   4281: # Side Effects:
                   4282: #   a reply is written to $client.
                   4283: sub dump_course_id_handler {
                   4284:     my ($cmd, $tail, $client) = @_;
1.494     droeschl 4285: 
                   4286:     my $res = LONCAPA::Lond::dump_course_id_handler($tail);
                   4287:     if ($res =~ /^error:/) {
                   4288:         Failure($client, \$res, "$cmd:$tail");
                   4289:     } else {
                   4290:         Reply($client, \$res, "$cmd:$tail");
                   4291:     }
                   4292: 
                   4293:     return 1;  
                   4294: 
                   4295:     #TODO remove
1.234     foxr     4296:     my $userinput = "$cmd:$tail";
                   4297: 
1.333     raeburn  4298:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
1.404     raeburn  4299:         $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
1.427     raeburn  4300:         $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
1.505     raeburn  4301:         $creationcontext,$domcloner,$hasuniquecode) =split(/:/,$tail);
1.397     raeburn  4302:     my $now = time;
1.419     raeburn  4303:     my ($cloneruname,$clonerudom,%cc_clone);
1.234     foxr     4304:     if (defined($description)) {
                   4305: 	$description=&unescape($description);
                   4306:     } else {
                   4307: 	$description='.';
                   4308:     }
1.266     raeburn  4309:     if (defined($instcodefilter)) {
                   4310:         $instcodefilter=&unescape($instcodefilter);
                   4311:     } else {
                   4312:         $instcodefilter='.';
                   4313:     }
1.336     raeburn  4314:     my ($ownerunamefilter,$ownerdomfilter);
1.266     raeburn  4315:     if (defined($ownerfilter)) {
                   4316:         $ownerfilter=&unescape($ownerfilter);
1.336     raeburn  4317:         if ($ownerfilter ne '.' && defined($ownerfilter)) {
                   4318:             if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
                   4319:                  $ownerunamefilter = $1;
                   4320:                  $ownerdomfilter = $2;
                   4321:             } else {
                   4322:                 $ownerunamefilter = $ownerfilter;
                   4323:                 $ownerdomfilter = '';
                   4324:             }
                   4325:         }
1.266     raeburn  4326:     } else {
                   4327:         $ownerfilter='.';
                   4328:     }
1.336     raeburn  4329: 
1.282     raeburn  4330:     if (defined($coursefilter)) {
                   4331:         $coursefilter=&unescape($coursefilter);
                   4332:     } else {
                   4333:         $coursefilter='.';
                   4334:     }
1.333     raeburn  4335:     if (defined($typefilter)) {
                   4336:         $typefilter=&unescape($typefilter);
                   4337:     } else {
                   4338:         $typefilter='.';
                   4339:     }
1.344     raeburn  4340:     if (defined($regexp_ok)) {
                   4341:         $regexp_ok=&unescape($regexp_ok);
                   4342:     }
1.401     raeburn  4343:     if (defined($catfilter)) {
                   4344:         $catfilter=&unescape($catfilter);
                   4345:     }
1.419     raeburn  4346:     if (defined($cloner)) {
                   4347:         $cloner = &unescape($cloner);
                   4348:         ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/); 
                   4349:     }
                   4350:     if (defined($cc_clone_list)) {
                   4351:         $cc_clone_list = &unescape($cc_clone_list);
                   4352:         my @cc_cloners = split('&',$cc_clone_list);
                   4353:         foreach my $cid (@cc_cloners) {
                   4354:             my ($clonedom,$clonenum) = split(':',$cid);
                   4355:             next if ($clonedom ne $udom); 
                   4356:             $cc_clone{$clonedom.'_'.$clonenum} = 1;
                   4357:         } 
                   4358:     }
1.431     raeburn  4359:     if ($createdbefore ne '') {
1.427     raeburn  4360:         $createdbefore = &unescape($createdbefore);
                   4361:     } else {
                   4362:        $createdbefore = 0;
                   4363:     }
1.431     raeburn  4364:     if ($createdafter ne '') {
1.427     raeburn  4365:         $createdafter = &unescape($createdafter);
                   4366:     } else {
                   4367:         $createdafter = 0;
                   4368:     }
1.431     raeburn  4369:     if ($creationcontext ne '') {
1.427     raeburn  4370:         $creationcontext = &unescape($creationcontext);
                   4371:     } else {
                   4372:         $creationcontext = '.';
                   4373:     }
1.505     raeburn  4374:     unless ($hasuniquecode) {
                   4375:         $hasuniquecode = '.';
                   4376:     }
1.384     raeburn  4377:     my $unpack = 1;
1.485     raeburn  4378:     if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' && 
1.384     raeburn  4379:         $typefilter eq '.') {
                   4380:         $unpack = 0;
                   4381:     }
                   4382:     if (!defined($since)) { $since=0; }
1.234     foxr     4383:     my $qresult='';
                   4384:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4385:     if ($hashref) {
1.384     raeburn  4386: 	while (my ($key,$value) = each(%$hashref)) {
1.397     raeburn  4387:             my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
1.427     raeburn  4388:                 %unesc_val,$selfenroll_end,$selfenroll_types,$created,
                   4389:                 $context);
1.384     raeburn  4390:             $unesc_key = &unescape($key);
                   4391:             if ($unesc_key =~ /^lasttime:/) {
                   4392:                 next;
                   4393:             } else {
                   4394:                 $lasttime_key = &escape('lasttime:'.$unesc_key);
                   4395:             }
                   4396:             if ($hashref->{$lasttime_key} ne '') {
                   4397:                 $lasttime = $hashref->{$lasttime_key};
                   4398:                 next if ($lasttime<$since);
                   4399:             }
1.419     raeburn  4400:             my ($canclone,$valchange);
1.384     raeburn  4401:             my $items = &Apache::lonnet::thaw_unescape($value);
                   4402:             if (ref($items) eq 'HASH') {
1.429     raeburn  4403:                 if ($hashref->{$lasttime_key} eq '') {
1.430     raeburn  4404:                     next if ($since > 1);
1.429     raeburn  4405:                 }
1.384     raeburn  4406:                 $is_hash =  1;
1.445     raeburn  4407:                 if ($domcloner) {
                   4408:                     $canclone = 1;
                   4409:                 } elsif (defined($clonerudom)) {
1.419     raeburn  4410:                     if ($items->{'cloners'}) {
                   4411:                         my @cloneable = split(',',$items->{'cloners'});
                   4412:                         if (@cloneable) {
                   4413:                             if (grep(/^\*$/,@cloneable))  {
                   4414:                                 $canclone = 1;
                   4415:                             } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
                   4416:                                 $canclone = 1;
                   4417:                             } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
                   4418:                                 $canclone = 1;
                   4419:                             }
                   4420:                         }
                   4421:                         unless ($canclone) {
                   4422:                             if ($cloneruname ne '' && $clonerudom ne '') {
                   4423:                                 if ($cc_clone{$unesc_key}) {
                   4424:                                     $canclone = 1;
                   4425:                                     $items->{'cloners'} .= ','.$cloneruname.':'.
                   4426:                                                            $clonerudom;
                   4427:                                     $valchange = 1;
                   4428:                                 }
                   4429:                             }
                   4430:                         }
                   4431:                     } elsif (defined($cloneruname)) {
                   4432:                         if ($cc_clone{$unesc_key}) {
                   4433:                             $canclone = 1;
                   4434:                             $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4435:                             $valchange = 1;
                   4436:                         }
1.437     raeburn  4437:                         unless ($canclone) {
                   4438:                             if ($items->{'owner'} =~ /:/) {
                   4439:                                 if ($items->{'owner'} eq $cloner) {
                   4440:                                     $canclone = 1;
                   4441:                                 }
1.444     raeburn  4442:                             } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
1.437     raeburn  4443:                                 $canclone = 1;
                   4444:                             }
                   4445:                             if ($canclone) {
                   4446:                                 $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4447:                                 $valchange = 1;
                   4448:                             }
                   4449:                         }
1.419     raeburn  4450:                     }
                   4451:                 }
1.384     raeburn  4452:                 if ($unpack || !$rtn_as_hash) {
                   4453:                     $unesc_val{'descr'} = $items->{'description'};
                   4454:                     $unesc_val{'inst_code'} = $items->{'inst_code'};
                   4455:                     $unesc_val{'owner'} = $items->{'owner'};
                   4456:                     $unesc_val{'type'} = $items->{'type'};
1.419     raeburn  4457:                     $unesc_val{'cloners'} = $items->{'cloners'};
1.427     raeburn  4458:                     $unesc_val{'created'} = $items->{'created'};
                   4459:                     $unesc_val{'context'} = $items->{'context'};
1.404     raeburn  4460:                 }
                   4461:                 $selfenroll_types = $items->{'selfenroll_types'};
                   4462:                 $selfenroll_end = $items->{'selfenroll_end_date'};
1.427     raeburn  4463:                 $created = $items->{'created'};
                   4464:                 $context = $items->{'context'};
1.505     raeburn  4465:                 if ($hasuniquecode ne '.') {
                   4466:                     next unless ($items->{'uniquecode'});
                   4467:                 }
1.404     raeburn  4468:                 if ($selfenrollonly) {
                   4469:                     next if (!$selfenroll_types);
                   4470:                     if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
                   4471:                         next;
1.397     raeburn  4472:                     }
1.404     raeburn  4473:                 }
1.427     raeburn  4474:                 if ($creationcontext ne '.') {
                   4475:                     next if (($context ne '') && ($context ne $creationcontext));  
                   4476:                 }
                   4477:                 if ($createdbefore > 0) {
                   4478:                     next if (($created eq '') || ($created > $createdbefore));   
                   4479:                 }
                   4480:                 if ($createdafter > 0) {
                   4481:                     next if (($created eq '') || ($created <= $createdafter)); 
                   4482:                 }
1.404     raeburn  4483:                 if ($catfilter ne '') {
1.406     raeburn  4484:                     next if ($items->{'categories'} eq '');
                   4485:                     my @categories = split('&',$items->{'categories'}); 
1.407     raeburn  4486:                     next if (@categories == 0);
                   4487:                     my @subcats = split('&',$catfilter);
                   4488:                     my $matchcat = 0;
                   4489:                     foreach my $cat (@categories) {
                   4490:                         if (grep(/^\Q$cat\E$/,@subcats)) {
                   4491:                             $matchcat = 1;
                   4492:                             last;
                   4493:                         }
                   4494:                     }
                   4495:                     next if (!$matchcat);
1.404     raeburn  4496:                 }
                   4497:                 if ($caller eq 'coursecatalog') {
1.405     raeburn  4498:                     if ($items->{'hidefromcat'} eq 'yes') {
                   4499:                         next if !$showhidden;
1.401     raeburn  4500:                     }
1.384     raeburn  4501:                 }
1.383     raeburn  4502:             } else {
1.401     raeburn  4503:                 next if ($catfilter ne '');
1.419     raeburn  4504:                 next if ($selfenrollonly);
1.427     raeburn  4505:                 next if ($createdbefore || $createdafter);
                   4506:                 next if ($creationcontext ne '.');
1.419     raeburn  4507:                 if ((defined($clonerudom)) && (defined($cloneruname)))  {
                   4508:                     if ($cc_clone{$unesc_key}) {
                   4509:                         $canclone = 1;
                   4510:                         $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
                   4511:                     }
                   4512:                 }
1.384     raeburn  4513:                 $is_hash =  0;
1.388     raeburn  4514:                 my @courseitems = split(/:/,$value);
1.403     raeburn  4515:                 $lasttime = pop(@courseitems);
1.402     raeburn  4516:                 if ($hashref->{$lasttime_key} eq '') {
                   4517:                     next if ($lasttime<$since);
                   4518:                 }
1.384     raeburn  4519: 	        ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
1.383     raeburn  4520:             }
1.419     raeburn  4521:             if ($cloneonly) {
                   4522:                next unless ($canclone);
                   4523:             }
1.266     raeburn  4524:             my $match = 1;
1.384     raeburn  4525: 	    if ($description ne '.') {
                   4526:                 if (!$is_hash) {
                   4527:                     $unesc_val{'descr'} = &unescape($val{'descr'});
                   4528:                 }
                   4529:                 if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
1.266     raeburn  4530:                     $match = 0;
1.384     raeburn  4531:                 }
1.266     raeburn  4532:             }
1.384     raeburn  4533:             if ($instcodefilter ne '.') {
                   4534:                 if (!$is_hash) {
                   4535:                     $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
                   4536:                 }
1.418     raeburn  4537:                 if ($regexp_ok == 1) {
1.384     raeburn  4538:                     if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
1.344     raeburn  4539:                         $match = 0;
                   4540:                     }
1.418     raeburn  4541:                 } elsif ($regexp_ok == -1) {
                   4542:                     if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
                   4543:                         $match = 0;
                   4544:                     }
1.344     raeburn  4545:                 } else {
1.384     raeburn  4546:                     if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
1.344     raeburn  4547:                         $match = 0;
                   4548:                     }
1.266     raeburn  4549:                 }
1.234     foxr     4550: 	    }
1.384     raeburn  4551:             if ($ownerfilter ne '.') {
                   4552:                 if (!$is_hash) {
                   4553:                     $unesc_val{'owner'} = &unescape($val{'owner'});
                   4554:                 }
1.336     raeburn  4555:                 if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
1.384     raeburn  4556:                     if ($unesc_val{'owner'} =~ /:/) {
                   4557:                         if (eval{$unesc_val{'owner'} !~ 
                   4558:                              /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
1.336     raeburn  4559:                             $match = 0;
                   4560:                         } 
                   4561:                     } else {
1.384     raeburn  4562:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4563:                             $match = 0;
                   4564:                         }
                   4565:                     }
                   4566:                 } elsif ($ownerunamefilter ne '') {
1.384     raeburn  4567:                     if ($unesc_val{'owner'} =~ /:/) {
                   4568:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
1.336     raeburn  4569:                              $match = 0;
                   4570:                         }
                   4571:                     } else {
1.384     raeburn  4572:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4573:                             $match = 0;
                   4574:                         }
                   4575:                     }
                   4576:                 } elsif ($ownerdomfilter ne '') {
1.384     raeburn  4577:                     if ($unesc_val{'owner'} =~ /:/) {
                   4578:                         if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
1.336     raeburn  4579:                              $match = 0;
                   4580:                         }
                   4581:                     } else {
                   4582:                         if ($ownerdomfilter ne $udom) {
                   4583:                             $match = 0;
                   4584:                         }
                   4585:                     }
1.266     raeburn  4586:                 }
                   4587:             }
1.384     raeburn  4588:             if ($coursefilter ne '.') {
                   4589:                 if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
1.282     raeburn  4590:                     $match = 0;
                   4591:                 }
                   4592:             }
1.384     raeburn  4593:             if ($typefilter ne '.') {
                   4594:                 if (!$is_hash) {
                   4595:                     $unesc_val{'type'} = &unescape($val{'type'});
                   4596:                 }
                   4597:                 if ($unesc_val{'type'} eq '') {
1.333     raeburn  4598:                     if ($typefilter ne 'Course') {
                   4599:                         $match = 0;
                   4600:                     }
1.383     raeburn  4601:                 } else {
1.384     raeburn  4602:                     if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
1.333     raeburn  4603:                         $match = 0;
                   4604:                     }
                   4605:                 }
                   4606:             }
1.266     raeburn  4607:             if ($match == 1) {
1.384     raeburn  4608:                 if ($rtn_as_hash) {
                   4609:                     if ($is_hash) {
1.419     raeburn  4610:                         if ($valchange) {
                   4611:                             my $newvalue = &Apache::lonnet::freeze_escape($items);
                   4612:                             $qresult.=$key.'='.$newvalue.'&';
                   4613:                         } else {
                   4614:                             $qresult.=$key.'='.$value.'&';
                   4615:                         }
1.384     raeburn  4616:                     } else {
1.388     raeburn  4617:                         my %rtnhash = ( 'description' => &unescape($val{'descr'}),
                   4618:                                         'inst_code' => &unescape($val{'inst_code'}),
                   4619:                                         'owner'     => &unescape($val{'owner'}),
                   4620:                                         'type'      => &unescape($val{'type'}),
1.419     raeburn  4621:                                         'cloners'   => &unescape($val{'cloners'}),
1.384     raeburn  4622:                                       );
                   4623:                         my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
                   4624:                         $qresult.=$key.'='.$items.'&';
                   4625:                     }
1.383     raeburn  4626:                 } else {
1.384     raeburn  4627:                     if ($is_hash) {
                   4628:                         $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
                   4629:                                     &escape($unesc_val{'inst_code'}).':'.
                   4630:                                     &escape($unesc_val{'owner'}).'&';
                   4631:                     } else {
                   4632:                         $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
                   4633:                                     ':'.$val{'owner'}.'&';
                   4634:                     }
1.383     raeburn  4635:                 }
1.266     raeburn  4636:             }
1.234     foxr     4637: 	}
1.311     albertel 4638: 	if (&untie_domain_hash($hashref)) {
1.234     foxr     4639: 	    chop($qresult);
1.387     albertel 4640: 	    &Reply($client, \$qresult, $userinput);
1.234     foxr     4641: 	} else {
                   4642: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4643: 		    "while attempting courseiddump\n", $userinput);
                   4644: 	}
                   4645:     } else {
                   4646: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4647: 		"while attempting courseiddump\n", $userinput);
                   4648:     }
                   4649:     return 1;
                   4650: }
                   4651: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238     foxr     4652: 
1.438     raeburn  4653: sub course_lastaccess_handler {
                   4654:     my ($cmd, $tail, $client) = @_;
                   4655:     my $userinput = "$cmd:$tail";
                   4656:     my ($cdom,$cnum) = split(':',$tail); 
                   4657:     my (%lastaccess,$qresult);
                   4658:     my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
                   4659:     if ($hashref) {
                   4660:         while (my ($key,$value) = each(%$hashref)) {
                   4661:             my ($unesc_key,$lasttime);
                   4662:             $unesc_key = &unescape($key);
                   4663:             if ($cnum) {
                   4664:                 next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
                   4665:             }
                   4666:             if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
                   4667:                 $lastaccess{$1} = $value;
                   4668:             } else {
                   4669:                 my $items = &Apache::lonnet::thaw_unescape($value);
                   4670:                 if (ref($items) eq 'HASH') {
                   4671:                     unless ($lastaccess{$unesc_key}) {
                   4672:                         $lastaccess{$unesc_key} = '';
                   4673:                     }
                   4674:                 } else {
                   4675:                     my @courseitems = split(':',$value);
                   4676:                     $lastaccess{$unesc_key} = pop(@courseitems);
                   4677:                 }
                   4678:             }
                   4679:         }
                   4680:         foreach my $cid (sort(keys(%lastaccess))) {
                   4681:             $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&'; 
                   4682:         }
                   4683:         if (&untie_domain_hash($hashref)) {
                   4684:             if ($qresult) {
                   4685:                 chop($qresult);
                   4686:             }
                   4687:             &Reply($client, \$qresult, $userinput);
                   4688:         } else {
                   4689:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4690:                     "while attempting lastacourseaccess\n", $userinput);
                   4691:         }
                   4692:     } else {
                   4693:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4694:                 "while attempting lastcourseaccess\n", $userinput);
                   4695:     }
                   4696:     return 1;
                   4697: }
                   4698: &register_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
                   4699: 
1.238     foxr     4700: #
1.348     raeburn  4701: # Puts an unencrypted entry in a namespace db file at the domain level 
                   4702: #
                   4703: # Parameters:
                   4704: #    $cmd      - The command that got us here.
                   4705: #    $tail     - Tail of the command (remaining parameters).
                   4706: #    $client   - File descriptor connected to client.
                   4707: # Returns
                   4708: #     0        - Requested to exit, caller should shut down.
                   4709: #     1        - Continue processing.
                   4710: #  Side effects:
                   4711: #     reply is written to $client.
                   4712: #
                   4713: sub put_domain_handler {
                   4714:     my ($cmd,$tail,$client) = @_;
                   4715: 
                   4716:     my $userinput = "$cmd:$tail";
                   4717: 
                   4718:     my ($udom,$namespace,$what) =split(/:/,$tail,3);
                   4719:     chomp($what);
                   4720:     my @pairs=split(/\&/,$what);
                   4721:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
                   4722:                                    "P", $what);
                   4723:     if ($hashref) {
                   4724:         foreach my $pair (@pairs) {
                   4725:             my ($key,$value)=split(/=/,$pair);
                   4726:             $hashref->{$key}=$value;
                   4727:         }
                   4728:         if (&untie_domain_hash($hashref)) {
                   4729:             &Reply($client, "ok\n", $userinput);
                   4730:         } else {
                   4731:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4732:                      "while attempting putdom\n", $userinput);
                   4733:         }
                   4734:     } else {
                   4735:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4736:                   "while attempting putdom\n", $userinput);
                   4737:     }
                   4738: 
                   4739:     return 1;
                   4740: }
                   4741: &register_handler("putdom", \&put_domain_handler, 0, 1, 0);
                   4742: 
1.517     raeburn  4743: # Updates one or more entries in clickers.db file at the domain level
                   4744: #
                   4745: # Parameters:
                   4746: #    $cmd      - The command that got us here.
                   4747: #    $tail     - Tail of the command (remaining parameters).
                   4748: #                In this case a colon separated list containing:
                   4749: #                (a) the domain for which we are updating the entries,
                   4750: #                (b) the action required -- add or del -- and
                   4751: #                (c) a &-separated list of entries to add or delete.
                   4752: #    $client   - File descriptor connected to client.
                   4753: # Returns
                   4754: #     1        - Continue processing.
                   4755: #     0        - Requested to exit, caller should shut down.
                   4756: #  Side effects:
                   4757: #     reply is written to $client.
                   4758: #
                   4759: 
                   4760: 
                   4761: sub update_clickers {
                   4762:     my ($cmd, $tail, $client)  = @_;
                   4763: 
                   4764:     my $userinput = "$cmd:$tail";
                   4765:     my ($udom,$action,$what) =split(/:/,$tail,3);
                   4766:     chomp($what);
                   4767: 
                   4768:     my $hashref = &tie_domain_hash($udom, "clickers", &GDBM_WRCREAT(),
                   4769:                                  "U","$action:$what");
                   4770: 
                   4771:     if (!$hashref) {
                   4772:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4773:                   "while attempting updateclickers\n", $userinput);
                   4774:         return 1;
                   4775:     }
                   4776: 
                   4777:     my @pairs=split(/\&/,$what);
                   4778:     foreach my $pair (@pairs) {
                   4779:         my ($key,$value)=split(/=/,$pair);
                   4780:         if ($action eq 'add') {
                   4781:             if (exists($hashref->{$key})) {
                   4782:                 my @newvals = split(/,/,&unescape($value));
                   4783:                 my @currvals = split(/,/,&unescape($hashref->{$key}));
                   4784:                 my @merged = sort(keys(%{{map { $_ => 1 } (@newvals,@currvals)}}));
                   4785:                 $hashref->{$key}=&escape(join(',',@merged));
                   4786:             } else {
                   4787:                 $hashref->{$key}=$value;
                   4788:             }
                   4789:         } elsif ($action eq 'del') {
                   4790:             if (exists($hashref->{$key})) {
                   4791:                 my %current;
                   4792:                 map { $current{$_} = 1; } split(/,/,&unescape($hashref->{$key}));
                   4793:                 map { delete($current{$_}); } split(/,/,&unescape($value));
                   4794:                 if (keys(%current)) {
                   4795:                     $hashref->{$key}=&escape(join(',',sort(keys(%current))));
                   4796:                 } else {
                   4797:                     delete($hashref->{$key});
                   4798:                 }
                   4799:             }
                   4800:         }
                   4801:     }
                   4802:     if (&untie_user_hash($hashref)) {
                   4803:         &Reply( $client, "ok\n", $userinput);
                   4804:     } else {
                   4805:         &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   4806:                  "while attempting put\n",
                   4807:                  $userinput);
                   4808:     }
                   4809:     return 1;
                   4810: }
                   4811: &register_handler("updateclickers", \&update_clickers, 0, 1, 0);
                   4812: 
                   4813: 
                   4814: # Deletes one or more entries in a namespace db file at the domain level
                   4815: #
                   4816: # Parameters:
                   4817: #    $cmd      - The command that got us here.
                   4818: #    $tail     - Tail of the command (remaining parameters).
                   4819: #                In this case a colon separated list containing:
                   4820: #                (a) the domain for which we are deleting the entries,
                   4821: #                (b) &-separated list of keys to delete.  
                   4822: #    $client   - File descriptor connected to client.
                   4823: # Returns
                   4824: #     1        - Continue processing.
                   4825: #     0        - Requested to exit, caller should shut down.
                   4826: #  Side effects:
                   4827: #     reply is written to $client.
                   4828: #
                   4829: 
                   4830: sub del_domain_handler {
                   4831:     my ($cmd,$tail,$client) = @_;
                   4832: 
                   4833:     my $userinput = "$cmd:$tail";
                   4834: 
                   4835:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   4836:     chomp($what);
                   4837:     my $hashref = &tie_domain_hash($udom,$namespace,&GDBM_WRCREAT(),
                   4838:                                    "D", $what);
                   4839:     if ($hashref) {
                   4840:         my @keys=split(/\&/,$what);
                   4841:         foreach my $key (@keys) {
                   4842:             delete($hashref->{$key});
                   4843:         }
                   4844:         if (&untie_user_hash($hashref)) {
                   4845:             &Reply($client, "ok\n", $userinput);
                   4846:         } else {
                   4847:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4848:                     "while attempting deldom\n", $userinput);
                   4849:         }
                   4850:     } else {
                   4851:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4852:                  "while attempting deldom\n", $userinput);
                   4853:     }
                   4854:     return 1;
                   4855: }
                   4856: &register_handler("deldom", \&del_domain_handler, 0, 1, 0);
                   4857: 
                   4858: 
1.348     raeburn  4859: # Unencrypted get from the namespace database file at the domain level.
                   4860: # This function retrieves a keyed item from a specific named database in the
                   4861: # domain directory.
                   4862: #
                   4863: # Parameters:
                   4864: #   $cmd             - Command request keyword (get).
                   4865: #   $tail            - Tail of the command.  This is a colon separated list
                   4866: #                      consisting of the domain and the 'namespace' 
                   4867: #                      which selects the gdbm file to do the lookup in,
                   4868: #                      & separated list of keys to lookup.  Note that
                   4869: #                      the values are returned as an & separated list too.
                   4870: #   $client          - File descriptor open on the client.
                   4871: # Returns:
                   4872: #   1       - Continue processing.
                   4873: #   0       - Exit.
                   4874: #  Side effects:
                   4875: #     reply is written to $client.
                   4876: #
                   4877: 
                   4878: sub get_domain_handler {
                   4879:     my ($cmd, $tail, $client) = @_;
                   4880: 
1.461     foxr     4881: 
1.536     raeburn  4882:     my $userinput = "$cmd:$tail";
                   4883: 
                   4884:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   4885:     chomp($what);
                   4886:     if ($namespace =~ /^enc/) {
                   4887:         &Failure( $client, "refused\n", $userinput);
                   4888:     } else {
                   4889:         my @queries=split(/\&/,$what);
                   4890:         my $qresult='';
                   4891:         my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
                   4892:         if ($hashref) {
                   4893:             for (my $i=0;$i<=$#queries;$i++) {
                   4894:                 $qresult.="$hashref->{$queries[$i]}&";
                   4895:             }
                   4896:             if (&untie_domain_hash($hashref)) {
                   4897:                 $qresult=~s/\&$//;
                   4898:                 &Reply($client, \$qresult, $userinput);
                   4899:             } else {
                   4900:                 &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4901:                           "while attempting getdom\n",$userinput);
                   4902:             }
                   4903:         } else {
                   4904:             &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4905:                      "while attempting getdom\n",$userinput);
                   4906:         }
                   4907:     }
                   4908: 
                   4909:     return 1;
                   4910: }
                   4911: &register_handler("getdom", \&get_domain_handler, 0, 1, 0);
                   4912: 
                   4913: sub encrypted_get_domain_handler {
                   4914:     my ($cmd, $tail, $client) = @_;
                   4915: 
                   4916:     my $userinput = "$cmd:$tail";
1.348     raeburn  4917: 
                   4918:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   4919:     chomp($what);
                   4920:     my @queries=split(/\&/,$what);
                   4921:     my $qresult='';
                   4922:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
                   4923:     if ($hashref) {
                   4924:         for (my $i=0;$i<=$#queries;$i++) {
                   4925:             $qresult.="$hashref->{$queries[$i]}&";
                   4926:         }
                   4927:         if (&untie_domain_hash($hashref)) {
                   4928:             $qresult=~s/\&$//;
1.536     raeburn  4929:             if ($cipher) {
                   4930:                 my $cmdlength=length($qresult);
                   4931:                 $qresult.="         ";
                   4932:                 my $encqresult='';
                   4933:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   4934:                     $encqresult.= unpack("H16",
                   4935:                                          $cipher->encrypt(substr($qresult,
                   4936:                                                                  $encidx,
                   4937:                                                                  8)));
                   4938:                 }
                   4939:                 &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   4940:             } else {
                   4941:                 &Failure( $client, "error:no_key\n", $userinput);
                   4942:             }
1.348     raeburn  4943:         } else {
                   4944:             &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
1.536     raeburn  4945:                       "while attempting egetdom\n",$userinput);
1.348     raeburn  4946:         }
                   4947:     } else {
                   4948:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
1.536     raeburn  4949:                  "while attempting egetdom\n",$userinput);
1.348     raeburn  4950:     }
                   4951:     return 1;
                   4952: }
1.536     raeburn  4953: &register_handler("egetdom", \&encrypted_get_domain_handler, 1, 1, 0);
1.348     raeburn  4954: 
1.420     raeburn  4955: #
1.238     foxr     4956: #  Puts an id to a domains id database. 
                   4957: #
                   4958: #  Parameters:
                   4959: #   $cmd     - The command that triggered us.
                   4960: #   $tail    - Remainder of the request other than the command. This is a 
                   4961: #              colon separated list containing:
                   4962: #              $domain  - The domain for which we are writing the id.
                   4963: #              $pairs  - The id info to write... this is and & separated list
                   4964: #                        of keyword=value.
                   4965: #   $client  - Socket open on the client.
                   4966: #  Returns:
                   4967: #    1   - Continue processing.
                   4968: #  Side effects:
                   4969: #     reply is written to $client.
                   4970: #
                   4971: sub put_id_handler {
                   4972:     my ($cmd,$tail,$client) = @_;
                   4973: 
                   4974: 
                   4975:     my $userinput = "$cmd:$tail";
                   4976: 
                   4977:     my ($udom,$what)=split(/:/,$tail);
                   4978:     chomp($what);
                   4979:     my @pairs=split(/\&/,$what);
                   4980:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   4981: 				   "P", $what);
                   4982:     if ($hashref) {
                   4983: 	foreach my $pair (@pairs) {
                   4984: 	    my ($key,$value)=split(/=/,$pair);
                   4985: 	    $hashref->{$key}=$value;
                   4986: 	}
1.311     albertel 4987: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     4988: 	    &Reply($client, "ok\n", $userinput);
                   4989: 	} else {
                   4990: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4991: 		     "while attempting idput\n", $userinput);
                   4992: 	}
                   4993:     } else {
                   4994: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4995: 		  "while attempting idput\n", $userinput);
                   4996:     }
                   4997: 
                   4998:     return 1;
                   4999: }
1.263     albertel 5000: &register_handler("idput", \&put_id_handler, 0, 1, 0);
1.238     foxr     5001: 
                   5002: #
                   5003: #  Retrieves a set of id values from the id database.
                   5004: #  Returns an & separated list of results, one for each requested id to the
                   5005: #  client.
                   5006: #
                   5007: # Parameters:
                   5008: #   $cmd       - Command keyword that caused us to be dispatched.
                   5009: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5010: #               domain - the domain whose id table we dump
                   5011: #               ids      Consists of an & separated list of
                   5012: #                        id keywords whose values will be fetched.
                   5013: #                        nonexisting keywords will have an empty value.
                   5014: #   $client    - Socket open on the client.
                   5015: #
                   5016: # Returns:
                   5017: #    1 - indicating processing should continue.
                   5018: # Side effects:
                   5019: #   An & separated list of results is written to $client.
                   5020: #
                   5021: sub get_id_handler {
                   5022:     my ($cmd, $tail, $client) = @_;
                   5023: 
                   5024:     
                   5025:     my $userinput = "$client:$tail";
                   5026:     
                   5027:     my ($udom,$what)=split(/:/,$tail);
                   5028:     chomp($what);
                   5029:     my @queries=split(/\&/,$what);
                   5030:     my $qresult='';
                   5031:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
                   5032:     if ($hashref) {
                   5033: 	for (my $i=0;$i<=$#queries;$i++) {
                   5034: 	    $qresult.="$hashref->{$queries[$i]}&";
                   5035: 	}
1.311     albertel 5036: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     5037: 	    $qresult=~s/\&$//;
1.387     albertel 5038: 	    &Reply($client, \$qresult, $userinput);
1.238     foxr     5039: 	} else {
                   5040: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5041: 		      "while attempting idget\n",$userinput);
                   5042: 	}
                   5043:     } else {
                   5044: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5045: 		 "while attempting idget\n",$userinput);
                   5046:     }
                   5047:     
                   5048:     return 1;
                   5049: }
1.263     albertel 5050: &register_handler("idget", \&get_id_handler, 0, 1, 0);
1.238     foxr     5051: 
1.501     raeburn  5052: #   Deletes one or more ids in a domain's id database.
                   5053: #
                   5054: #   Parameters:
                   5055: #       $cmd                  - Command keyword (iddel).
                   5056: #       $tail                 - Command tail.  In this case a colon
                   5057: #                               separated list containing:
                   5058: #                               The domain for which we are deleting the id(s).
                   5059: #                               &-separated list of id(s) to delete.
                   5060: #       $client               - File open on client socket.
                   5061: # Returns:
                   5062: #     1   - Continue processing
                   5063: #     0   - Exit server.
                   5064: #     
                   5065: #
                   5066: 
                   5067: sub del_id_handler {
                   5068:     my ($cmd,$tail,$client) = @_;
                   5069: 
                   5070:     my $userinput = "$cmd:$tail";
                   5071: 
                   5072:     my ($udom,$what)=split(/:/,$tail);
                   5073:     chomp($what);
                   5074:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   5075:                                    "D", $what);
                   5076:     if ($hashref) {
                   5077:         my @keys=split(/\&/,$what);
                   5078:         foreach my $key (@keys) {
                   5079:             delete($hashref->{$key});
                   5080:         }
                   5081:         if (&untie_user_hash($hashref)) {
                   5082:             &Reply($client, "ok\n", $userinput);
                   5083:         } else {
                   5084:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5085:                     "while attempting iddel\n", $userinput);
                   5086:         }
                   5087:     } else {
                   5088:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5089:                  "while attempting iddel\n", $userinput);
                   5090:     }
                   5091:     return 1;
                   5092: }
                   5093: &register_handler("iddel", \&del_id_handler, 0, 1, 0);
                   5094: 
1.238     foxr     5095: #
1.299     raeburn  5096: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
                   5097: #
                   5098: # Parameters
                   5099: #   $cmd       - Command keyword that caused us to be dispatched.
                   5100: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5101: #               domain - the domain whose dcmail we are recording
                   5102: #               email    Consists of key=value pair 
                   5103: #                        where key is unique msgid
                   5104: #                        and value is message (in XML)
                   5105: #   $client    - Socket open on the client.
                   5106: #
                   5107: # Returns:
                   5108: #    1 - indicating processing should continue.
                   5109: # Side effects
                   5110: #     reply is written to $client.
                   5111: #
                   5112: sub put_dcmail_handler {
                   5113:     my ($cmd,$tail,$client) = @_;
                   5114:     my $userinput = "$cmd:$tail";
1.463     foxr     5115: 
                   5116: 
1.299     raeburn  5117:     my ($udom,$what)=split(/:/,$tail);
                   5118:     chomp($what);
                   5119:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5120:     if ($hashref) {
                   5121:         my ($key,$value)=split(/=/,$what);
                   5122:         $hashref->{$key}=$value;
                   5123:     }
1.311     albertel 5124:     if (&untie_domain_hash($hashref)) {
1.299     raeburn  5125:         &Reply($client, "ok\n", $userinput);
                   5126:     } else {
                   5127:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5128:                  "while attempting dcmailput\n", $userinput);
                   5129:     }
                   5130:     return 1;
                   5131: }
                   5132: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
                   5133: 
                   5134: #
                   5135: # Retrieves broadcast e-mail from nohist_dcmail database
                   5136: # Returns to client an & separated list of key=value pairs,
                   5137: # where key is msgid and value is message information.
                   5138: #
                   5139: # Parameters
                   5140: #   $cmd       - Command keyword that caused us to be dispatched.
                   5141: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5142: #               domain - the domain whose dcmail table we dump
                   5143: #               startfilter - beginning of time window 
                   5144: #               endfilter - end of time window
                   5145: #               sendersfilter - & separated list of username:domain 
                   5146: #                 for senders to search for.
                   5147: #   $client    - Socket open on the client.
                   5148: #
                   5149: # Returns:
                   5150: #    1 - indicating processing should continue.
                   5151: # Side effects
                   5152: #     reply (& separated list of msgid=messageinfo pairs) is 
                   5153: #     written to $client.
                   5154: #
                   5155: sub dump_dcmail_handler {
                   5156:     my ($cmd, $tail, $client) = @_;
                   5157:                                                                                 
                   5158:     my $userinput = "$cmd:$tail";
                   5159:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
                   5160:     chomp($sendersfilter);
                   5161:     my @senders = ();
                   5162:     if (defined($startfilter)) {
                   5163:         $startfilter=&unescape($startfilter);
                   5164:     } else {
                   5165:         $startfilter='.';
                   5166:     }
                   5167:     if (defined($endfilter)) {
                   5168:         $endfilter=&unescape($endfilter);
                   5169:     } else {
                   5170:         $endfilter='.';
                   5171:     }
                   5172:     if (defined($sendersfilter)) {
                   5173:         $sendersfilter=&unescape($sendersfilter);
1.300     albertel 5174: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
1.299     raeburn  5175:     }
                   5176: 
                   5177:     my $qresult='';
                   5178:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5179:     if ($hashref) {
                   5180:         while (my ($key,$value) = each(%$hashref)) {
                   5181:             my $match = 1;
1.303     albertel 5182:             my ($timestamp,$subj,$uname,$udom) = 
                   5183: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
1.299     raeburn  5184:             $subj = &unescape($subj);
                   5185:             unless ($startfilter eq '.' || !defined($startfilter)) {
                   5186:                 if ($timestamp < $startfilter) {
                   5187:                     $match = 0;
                   5188:                 }
                   5189:             }
                   5190:             unless ($endfilter eq '.' || !defined($endfilter)) {
                   5191:                 if ($timestamp > $endfilter) {
                   5192:                     $match = 0;
                   5193:                 }
                   5194:             }
                   5195:             unless (@senders < 1) {
                   5196:                 unless (grep/^$uname:$udom$/,@senders) {
                   5197:                     $match = 0;
                   5198:                 }
                   5199:             }
                   5200:             if ($match == 1) {
                   5201:                 $qresult.=$key.'='.$value.'&';
                   5202:             }
                   5203:         }
1.311     albertel 5204:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5205:             chop($qresult);
1.387     albertel 5206:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5207:         } else {
                   5208:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5209:                     "while attempting dcmaildump\n", $userinput);
                   5210:         }
                   5211:     } else {
                   5212:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5213:                 "while attempting dcmaildump\n", $userinput);
                   5214:     }
                   5215:     return 1;
                   5216: }
                   5217: 
                   5218: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
                   5219: 
                   5220: #
                   5221: # Puts domain roles in nohist_domainroles database
                   5222: #
                   5223: # Parameters
                   5224: #   $cmd       - Command keyword that caused us to be dispatched.
                   5225: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5226: #               domain - the domain whose roles we are recording  
                   5227: #               role -   Consists of key=value pair
                   5228: #                        where key is unique role
                   5229: #                        and value is start/end date information
                   5230: #   $client    - Socket open on the client.
                   5231: #
                   5232: # Returns:
                   5233: #    1 - indicating processing should continue.
                   5234: # Side effects
                   5235: #     reply is written to $client.
                   5236: #
                   5237: 
                   5238: sub put_domainroles_handler {
                   5239:     my ($cmd,$tail,$client) = @_;
                   5240: 
                   5241:     my $userinput = "$cmd:$tail";
                   5242:     my ($udom,$what)=split(/:/,$tail);
                   5243:     chomp($what);
                   5244:     my @pairs=split(/\&/,$what);
                   5245:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5246:     if ($hashref) {
                   5247:         foreach my $pair (@pairs) {
                   5248:             my ($key,$value)=split(/=/,$pair);
                   5249:             $hashref->{$key}=$value;
                   5250:         }
1.311     albertel 5251:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5252:             &Reply($client, "ok\n", $userinput);
                   5253:         } else {
                   5254:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5255:                      "while attempting domroleput\n", $userinput);
                   5256:         }
                   5257:     } else {
                   5258:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5259:                   "while attempting domroleput\n", $userinput);
                   5260:     }
                   5261:                                                                                   
                   5262:     return 1;
                   5263: }
                   5264: 
                   5265: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
                   5266: 
                   5267: #
                   5268: # Retrieves domain roles from nohist_domainroles database
                   5269: # Returns to client an & separated list of key=value pairs,
                   5270: # where key is role and value is start and end date information.
                   5271: #
                   5272: # Parameters
                   5273: #   $cmd       - Command keyword that caused us to be dispatched.
                   5274: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5275: #               domain - the domain whose domain roles table we dump
                   5276: #   $client    - Socket open on the client.
                   5277: #
                   5278: # Returns:
                   5279: #    1 - indicating processing should continue.
                   5280: # Side effects
                   5281: #     reply (& separated list of role=start/end info pairs) is
                   5282: #     written to $client.
                   5283: #
                   5284: sub dump_domainroles_handler {
                   5285:     my ($cmd, $tail, $client) = @_;
                   5286:                                                                                            
                   5287:     my $userinput = "$cmd:$tail";
                   5288:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
                   5289:     chomp($rolesfilter);
                   5290:     my @roles = ();
                   5291:     if (defined($startfilter)) {
                   5292:         $startfilter=&unescape($startfilter);
                   5293:     } else {
                   5294:         $startfilter='.';
                   5295:     }
                   5296:     if (defined($endfilter)) {
                   5297:         $endfilter=&unescape($endfilter);
                   5298:     } else {
                   5299:         $endfilter='.';
                   5300:     }
                   5301:     if (defined($rolesfilter)) {
                   5302:         $rolesfilter=&unescape($rolesfilter);
1.300     albertel 5303: 	@roles = split(/\&/,$rolesfilter);
1.299     raeburn  5304:     }
1.421     raeburn  5305: 
1.299     raeburn  5306:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5307:     if ($hashref) {
                   5308:         my $qresult = '';
                   5309:         while (my ($key,$value) = each(%$hashref)) {
                   5310:             my $match = 1;
1.421     raeburn  5311:             my ($end,$start) = split(/:/,&unescape($value));
1.299     raeburn  5312:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
1.421     raeburn  5313:             unless (@roles < 1) {
                   5314:                 unless (grep/^\Q$trole\E$/,@roles) {
                   5315:                     $match = 0;
                   5316:                     next;
                   5317:                 }
                   5318:             }
1.299     raeburn  5319:             unless ($startfilter eq '.' || !defined($startfilter)) {
1.415     raeburn  5320:                 if ((defined($start)) && ($start >= $startfilter)) {
1.299     raeburn  5321:                     $match = 0;
1.421     raeburn  5322:                     next;
1.299     raeburn  5323:                 }
                   5324:             }
                   5325:             unless ($endfilter eq '.' || !defined($endfilter)) {
1.421     raeburn  5326:                 if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
1.299     raeburn  5327:                     $match = 0;
1.421     raeburn  5328:                     next;
1.299     raeburn  5329:                 }
                   5330:             }
                   5331:             if ($match == 1) {
                   5332:                 $qresult.=$key.'='.$value.'&';
                   5333:             }
                   5334:         }
1.311     albertel 5335:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5336:             chop($qresult);
1.387     albertel 5337:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5338:         } else {
                   5339:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5340:                     "while attempting domrolesdump\n", $userinput);
                   5341:         }
                   5342:     } else {
                   5343:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5344:                 "while attempting domrolesdump\n", $userinput);
                   5345:     }
                   5346:     return 1;
                   5347: }
                   5348: 
                   5349: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
                   5350: 
                   5351: 
1.238     foxr     5352: #  Process the tmpput command I'm not sure what this does.. Seems to
                   5353: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
                   5354: # where Id is the client's ip concatenated with a sequence number.
                   5355: # The file will contain some value that is passed in.  Is this e.g.
                   5356: # a login token?
                   5357: #
                   5358: # Parameters:
                   5359: #    $cmd     - The command that got us dispatched.
                   5360: #    $tail    - The remainder of the request following $cmd:
                   5361: #               In this case this will be the contents of the file.
                   5362: #    $client  - Socket connected to the client.
                   5363: # Returns:
                   5364: #    1 indicating processing can continue.
                   5365: # Side effects:
                   5366: #   A file is created in the local filesystem.
                   5367: #   A reply is sent to the client.
                   5368: sub tmp_put_handler {
                   5369:     my ($cmd, $what, $client) = @_;
                   5370: 
                   5371:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
                   5372: 
1.347     raeburn  5373:     my ($record,$context) = split(/:/,$what);
                   5374:     if ($context ne '') {
                   5375:         chomp($context);
                   5376:         $context = &unescape($context);
                   5377:     }
                   5378:     my ($id,$store);
1.238     foxr     5379:     $tmpsnum++;
1.454     raeburn  5380:     if (($context eq 'resetpw') || ($context eq 'createaccount')) {
1.347     raeburn  5381:         $id = &md5_hex(&md5_hex(time.{}.rand().$$));
                   5382:     } else {
                   5383:         $id = $$.'_'.$clientip.'_'.$tmpsnum;
                   5384:     }
1.238     foxr     5385:     $id=~s/\W/\_/g;
1.347     raeburn  5386:     $record=~s/\n//g;
1.238     foxr     5387:     my $execdir=$perlvar{'lonDaemons'};
                   5388:     if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
1.347     raeburn  5389: 	print $store $record;
1.238     foxr     5390: 	close $store;
1.387     albertel 5391: 	&Reply($client, \$id, $userinput);
1.238     foxr     5392:     } else {
                   5393: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5394: 		  "while attempting tmpput\n", $userinput);
                   5395:     }
                   5396:     return 1;
                   5397:   
                   5398: }
                   5399: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263     albertel 5400: 
1.238     foxr     5401: #   Processes the tmpget command.  This command returns the contents
                   5402: #  of a temporary resource file(?) created via tmpput.
                   5403: #
                   5404: # Paramters:
                   5405: #    $cmd      - Command that got us dispatched.
                   5406: #    $id       - Tail of the command, contain the id of the resource
                   5407: #                we want to fetch.
                   5408: #    $client   - socket open on the client.
                   5409: # Return:
                   5410: #    1         - Inidcating processing can continue.
                   5411: # Side effects:
                   5412: #   A reply is sent to the client.
                   5413: #
                   5414: sub tmp_get_handler {
                   5415:     my ($cmd, $id, $client) = @_;
                   5416: 
                   5417:     my $userinput = "$cmd:$id"; 
                   5418:     
                   5419: 
                   5420:     $id=~s/\W/\_/g;
                   5421:     my $store;
                   5422:     my $execdir=$perlvar{'lonDaemons'};
                   5423:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
                   5424: 	my $reply=<$store>;
1.387     albertel 5425: 	&Reply( $client, \$reply, $userinput);
1.238     foxr     5426: 	close $store;
                   5427:     } else {
                   5428: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5429: 		  "while attempting tmpget\n", $userinput);
                   5430:     }
                   5431: 
                   5432:     return 1;
                   5433: }
                   5434: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263     albertel 5435: 
1.238     foxr     5436: #
                   5437: #  Process the tmpdel command.  This command deletes a temp resource
                   5438: #  created by the tmpput command.
                   5439: #
                   5440: # Parameters:
                   5441: #   $cmd      - Command that got us here.
                   5442: #   $id       - Id of the temporary resource created.
                   5443: #   $client   - socket open on the client process.
                   5444: #
                   5445: # Returns:
                   5446: #   1     - Indicating processing should continue.
                   5447: # Side Effects:
                   5448: #   A file is deleted
                   5449: #   A reply is sent to the client.
                   5450: sub tmp_del_handler {
                   5451:     my ($cmd, $id, $client) = @_;
                   5452:     
                   5453:     my $userinput= "$cmd:$id";
                   5454:     
                   5455:     chomp($id);
                   5456:     $id=~s/\W/\_/g;
                   5457:     my $execdir=$perlvar{'lonDaemons'};
                   5458:     if (unlink("$execdir/tmp/$id.tmp")) {
                   5459: 	&Reply($client, "ok\n", $userinput);
                   5460:     } else {
                   5461: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
                   5462: 		  "while attempting tmpdel\n", $userinput);
                   5463:     }
                   5464:     
                   5465:     return 1;
                   5466: 
                   5467: }
                   5468: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263     albertel 5469: 
1.238     foxr     5470: #
1.246     foxr     5471: #   Processes the setannounce command.  This command
                   5472: #   creates a file named announce.txt in the top directory of
                   5473: #   the documentn root and sets its contents.  The announce.txt file is
                   5474: #   printed in its entirety at the LonCAPA login page.  Note:
                   5475: #   once the announcement.txt fileis created it cannot be deleted.
                   5476: #   However, setting the contents of the file to empty removes the
                   5477: #   announcement from the login page of loncapa so who cares.
                   5478: #
                   5479: # Parameters:
                   5480: #    $cmd          - The command that got us dispatched.
                   5481: #    $announcement - The text of the announcement.
                   5482: #    $client       - Socket open on the client process.
                   5483: # Retunrns:
                   5484: #   1             - Indicating request processing should continue
                   5485: # Side Effects:
                   5486: #   The file {DocRoot}/announcement.txt is created.
                   5487: #   A reply is sent to $client.
                   5488: #
                   5489: sub set_announce_handler {
                   5490:     my ($cmd, $announcement, $client) = @_;
                   5491:   
                   5492:     my $userinput    = "$cmd:$announcement";
                   5493: 
                   5494:     chomp($announcement);
                   5495:     $announcement=&unescape($announcement);
                   5496:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
                   5497: 				'/announcement.txt')) {
                   5498: 	print $store $announcement;
                   5499: 	close $store;
                   5500: 	&Reply($client, "ok\n", $userinput);
                   5501:     } else {
                   5502: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
                   5503:     }
                   5504: 
                   5505:     return 1;
                   5506: }
                   5507: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263     albertel 5508: 
1.246     foxr     5509: #
                   5510: #  Return the version of the daemon.  This can be used to determine
                   5511: #  the compatibility of cross version installations or, alternatively to
                   5512: #  simply know who's out of date and who isn't.  Note that the version
                   5513: #  is returned concatenated with the tail.
                   5514: # Parameters:
                   5515: #   $cmd        - the request that dispatched to us.
                   5516: #   $tail       - Tail of the request (client's version?).
                   5517: #   $client     - Socket open on the client.
                   5518: #Returns:
                   5519: #   1 - continue processing requests.
                   5520: # Side Effects:
                   5521: #   Replies with version to $client.
                   5522: sub get_version_handler {
                   5523:     my ($cmd, $tail, $client) = @_;
                   5524: 
                   5525:     my $userinput  = $cmd.$tail;
                   5526:     
                   5527:     &Reply($client, &version($userinput)."\n", $userinput);
                   5528: 
                   5529: 
                   5530:     return 1;
                   5531: }
                   5532: &register_handler("version", \&get_version_handler, 0, 1, 0);
1.263     albertel 5533: 
1.246     foxr     5534: #  Set the current host and domain.  This is used to support
                   5535: #  multihomed systems.  Each IP of the system, or even separate daemons
                   5536: #  on the same IP can be treated as handling a separate lonCAPA virtual
                   5537: #  machine.  This command selects the virtual lonCAPA.  The client always
                   5538: #  knows the right one since it is lonc and it is selecting the domain/system
                   5539: #  from the hosts.tab file.
                   5540: # Parameters:
                   5541: #    $cmd      - Command that dispatched us.
                   5542: #    $tail     - Tail of the command (domain/host requested).
                   5543: #    $socket   - Socket open on the client.
                   5544: #
                   5545: # Returns:
                   5546: #     1   - Indicates the program should continue to process requests.
                   5547: # Side-effects:
                   5548: #     The default domain/system context is modified for this daemon.
                   5549: #     a reply is sent to the client.
                   5550: #
                   5551: sub set_virtual_host_handler {
                   5552:     my ($cmd, $tail, $socket) = @_;
                   5553:   
                   5554:     my $userinput  ="$cmd:$tail";
                   5555: 
                   5556:     &Reply($client, &sethost($userinput)."\n", $userinput);
                   5557: 
                   5558: 
                   5559:     return 1;
                   5560: }
1.247     albertel 5561: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246     foxr     5562: 
                   5563: #  Process a request to exit:
                   5564: #   - "bye" is sent to the client.
                   5565: #   - The client socket is shutdown and closed.
                   5566: #   - We indicate to the caller that we should exit.
                   5567: # Formal Parameters:
                   5568: #   $cmd                - The command that got us here.
                   5569: #   $tail               - Tail of the command (empty).
                   5570: #   $client             - Socket open on the tail.
                   5571: # Returns:
                   5572: #   0      - Indicating the program should exit!!
                   5573: #
                   5574: sub exit_handler {
                   5575:     my ($cmd, $tail, $client) = @_;
                   5576: 
                   5577:     my $userinput = "$cmd:$tail";
                   5578: 
                   5579:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
                   5580:     &Reply($client, "bye\n", $userinput);
                   5581:     $client->shutdown(2);        # shutdown the socket forcibly.
                   5582:     $client->close();
                   5583: 
                   5584:     return 0;
                   5585: }
1.248     foxr     5586: &register_handler("exit", \&exit_handler, 0,1,1);
                   5587: &register_handler("init", \&exit_handler, 0,1,1);
                   5588: &register_handler("quit", \&exit_handler, 0,1,1);
                   5589: 
                   5590: #  Determine if auto-enrollment is enabled.
                   5591: #  Note that the original had what I believe to be a defect.
                   5592: #  The original returned 0 if the requestor was not a registerd client.
                   5593: #  It should return "refused".
                   5594: # Formal Parameters:
                   5595: #   $cmd       - The command that invoked us.
                   5596: #   $tail      - The tail of the command (Extra command parameters.
                   5597: #   $client    - The socket open on the client that issued the request.
                   5598: # Returns:
                   5599: #    1         - Indicating processing should continue.
                   5600: #
                   5601: sub enrollment_enabled_handler {
                   5602:     my ($cmd, $tail, $client) = @_;
                   5603:     my $userinput = $cmd.":".$tail; # For logging purposes.
                   5604: 
                   5605:     
1.337     albertel 5606:     my ($cdom) = split(/:/, $tail, 2);   # Domain we're asking about.
                   5607: 
1.248     foxr     5608:     my $outcome  = &localenroll::run($cdom);
1.387     albertel 5609:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5610: 
                   5611:     return 1;
                   5612: }
                   5613: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
                   5614: 
1.417     raeburn  5615: #
1.423     raeburn  5616: #   Validate an institutional code used for a LON-CAPA course.          
1.417     raeburn  5617: #
                   5618: # Formal Parameters:
                   5619: #   $cmd          - The command request that got us dispatched.
                   5620: #   $tail         - The tail of the command.  In this case,
                   5621: #                   this is a colon separated set of words that will be split
                   5622: #                   into:
1.424     raeburn  5623: #                        $dom      - The domain for which the check of 
                   5624: #                                    institutional course code will occur.
                   5625: #
                   5626: #                        $instcode - The institutional code for the course
                   5627: #                                    being requested, or validated for rights
                   5628: #                                    to request.
                   5629: #
                   5630: #                        $owner    - The course requestor (who will be the
                   5631: #                                    course owner, in the form username:domain
                   5632: #
1.417     raeburn  5633: #   $client       - Socket open on the client.
                   5634: # Returns:
                   5635: #    1           - Indicating processing should continue.
                   5636: #
                   5637: sub validate_instcode_handler {
                   5638:     my ($cmd, $tail, $client) = @_;
                   5639:     my $userinput = "$cmd:$tail";
1.423     raeburn  5640:     my ($dom,$instcode,$owner) = split(/:/, $tail);
1.422     raeburn  5641:     $instcode = &unescape($instcode);
                   5642:     $owner = &unescape($owner);
1.498     raeburn  5643:     my ($outcome,$description,$credits) = 
1.426     raeburn  5644:         &localenroll::validate_instcode($dom,$instcode,$owner);
1.498     raeburn  5645:     my $result = &escape($outcome).'&'.&escape($description).'&'.
                   5646:                  &escape($credits);
1.426     raeburn  5647:     &Reply($client, \$result, $userinput);
1.417     raeburn  5648: 
                   5649:     return 1;
                   5650: }
                   5651: &register_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
                   5652: 
1.248     foxr     5653: #   Get the official sections for which auto-enrollment is possible.
                   5654: #   Since the admin people won't know about 'unofficial sections' 
                   5655: #   we cannot auto-enroll on them.
                   5656: # Formal Parameters:
                   5657: #    $cmd     - The command request that got us dispatched here.
                   5658: #    $tail    - The remainder of the request.  In our case this
                   5659: #               will be split into:
                   5660: #               $coursecode   - The course name from the admin point of view.
                   5661: #               $cdom         - The course's domain(?).
                   5662: #    $client  - Socket open on the client.
                   5663: # Returns:
                   5664: #    1    - Indiciting processing should continue.
                   5665: #
                   5666: sub get_sections_handler {
                   5667:     my ($cmd, $tail, $client) = @_;
                   5668:     my $userinput = "$cmd:$tail";
                   5669: 
                   5670:     my ($coursecode, $cdom) = split(/:/, $tail);
                   5671:     my @secs = &localenroll::get_sections($coursecode,$cdom);
                   5672:     my $seclist = &escape(join(':',@secs));
                   5673: 
1.387     albertel 5674:     &Reply($client, \$seclist, $userinput);
1.248     foxr     5675:     
                   5676: 
                   5677:     return 1;
                   5678: }
                   5679: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
                   5680: 
                   5681: #   Validate the owner of a new course section.  
                   5682: #
                   5683: # Formal Parameters:
                   5684: #   $cmd      - Command that got us dispatched.
                   5685: #   $tail     - the remainder of the command.  For us this consists of a
                   5686: #               colon separated string containing:
                   5687: #                  $inst    - Course Id from the institutions point of view.
                   5688: #                  $owner   - Proposed owner of the course.
                   5689: #                  $cdom    - Domain of the course (from the institutions
                   5690: #                             point of view?)..
                   5691: #   $client   - Socket open on the client.
                   5692: #
                   5693: # Returns:
                   5694: #   1        - Processing should continue.
                   5695: #
                   5696: sub validate_course_owner_handler {
                   5697:     my ($cmd, $tail, $client)  = @_;
                   5698:     my $userinput = "$cmd:$tail";
1.470     raeburn  5699:     my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
                   5700:     
1.336     raeburn  5701:     $owner = &unescape($owner);
1.470     raeburn  5702:     $coowners = &unescape($coowners);
                   5703:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
1.387     albertel 5704:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5705: 
                   5706: 
                   5707: 
                   5708:     return 1;
                   5709: }
                   5710: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263     albertel 5711: 
1.248     foxr     5712: #
                   5713: #   Validate a course section in the official schedule of classes
                   5714: #   from the institutions point of view (part of autoenrollment).
                   5715: #
                   5716: # Formal Parameters:
                   5717: #   $cmd          - The command request that got us dispatched.
                   5718: #   $tail         - The tail of the command.  In this case,
                   5719: #                   this is a colon separated set of words that will be split
                   5720: #                   into:
                   5721: #                        $inst_course_id - The course/section id from the
                   5722: #                                          institutions point of view.
                   5723: #                        $cdom           - The domain from the institutions
                   5724: #                                          point of view.
                   5725: #   $client       - Socket open on the client.
                   5726: # Returns:
                   5727: #    1           - Indicating processing should continue.
                   5728: #
                   5729: sub validate_course_section_handler {
                   5730:     my ($cmd, $tail, $client) = @_;
                   5731:     my $userinput = "$cmd:$tail";
                   5732:     my ($inst_course_id, $cdom) = split(/:/, $tail);
                   5733: 
                   5734:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
1.387     albertel 5735:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5736: 
                   5737: 
                   5738:     return 1;
                   5739: }
                   5740: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
                   5741: 
                   5742: #
1.340     raeburn  5743: #   Validate course owner's access to enrollment data for specific class section. 
                   5744: #   
                   5745: #
                   5746: # Formal Parameters:
                   5747: #    $cmd     - The command request that got us dispatched.
                   5748: #    $tail    - The tail of the command.   In this case this is a colon separated
1.542     raeburn  5749: #               set of values that will be split into:
1.340     raeburn  5750: #               $inst_class  - Institutional code for the specific class section   
1.542     raeburn  5751: #               $ownerlist   - An escaped comma-separated list of username:domain 
                   5752: #                              of the course owner, and co-owner(s).
1.340     raeburn  5753: #               $cdom        - The domain of the course from the institution's
                   5754: #                              point of view.
                   5755: #    $client  - The socket open on the client.
                   5756: # Returns:
                   5757: #    1 - continue processing.
                   5758: #
                   5759: 
                   5760: sub validate_class_access_handler {
                   5761:     my ($cmd, $tail, $client) = @_;
                   5762:     my $userinput = "$cmd:$tail";
1.383     raeburn  5763:     my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
1.392     raeburn  5764:     my $owners = &unescape($ownerlist);
1.341     albertel 5765:     my $outcome;
                   5766:     eval {
                   5767: 	local($SIG{__DIE__})='DEFAULT';
1.392     raeburn  5768: 	$outcome=&localenroll::check_section($inst_class,$owners,$cdom);
1.341     albertel 5769:     };
1.387     albertel 5770:     &Reply($client,\$outcome, $userinput);
1.340     raeburn  5771: 
                   5772:     return 1;
                   5773: }
                   5774: &register_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
                   5775: 
                   5776: #
1.542     raeburn  5777: #   Validate course owner or co-owners(s) access to enrollment data for all sections
                   5778: #   and crosslistings for a particular course.
                   5779: #
                   5780: #
                   5781: # Formal Parameters:
                   5782: #    $cmd     - The command request that got us dispatched.
                   5783: #    $tail    - The tail of the command.   In this case this is a colon separated
                   5784: #               set of values that will be split into:
                   5785: #               $ownerlist   - An escaped comma-separated list of username:domain
                   5786: #                              of the course owner, and co-owner(s).
                   5787: #               $cdom        - The domain of the course from the institution's
                   5788: #                              point of view.
                   5789: #               $classes     - Frozen hash of institutional course sections and
                   5790: #                              crosslistings.
                   5791: #    $client  - The socket open on the client.
                   5792: # Returns:
                   5793: #    1 - continue processing.
                   5794: #
                   5795: 
                   5796: sub validate_classes_handler {
                   5797:     my ($cmd, $tail, $client) = @_;
                   5798:     my $userinput = "$cmd:$tail";
                   5799:     my ($ownerlist,$cdom,$classes) = split(/:/, $tail);
                   5800:     my $classesref = &Apache::lonnet::thaw_unescape($classes);
                   5801:     my $owners = &unescape($ownerlist);
                   5802:     my $result;
                   5803:     eval {
                   5804:         local($SIG{__DIE__})='DEFAULT';
                   5805:         my %validations;
                   5806:         my $response = &localenroll::check_instclasses($owners,$cdom,$classesref,
                   5807:                                                        \%validations);
                   5808:         if ($response eq 'ok') {
                   5809:             foreach my $key (keys(%validations)) {
                   5810:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   5811:             }
                   5812:             $result =~ s/\&$//;
                   5813:         } else {
                   5814:             $result = 'error';
                   5815:         }
                   5816:     };
                   5817:     if (!$@) {
                   5818:         &Reply($client, \$result, $userinput);
                   5819:     } else {
                   5820:         &Failure($client,"unknown_cmd\n",$userinput);
                   5821:     }
                   5822:     return 1;
                   5823: }
                   5824: &register_handler("autovalidateinstclasses", \&validate_classes_handler, 0, 1, 0);
                   5825: 
                   5826: #
1.340     raeburn  5827: #   Create a password for a new LON-CAPA user added by auto-enrollment.
                   5828: #   Only used for case where authentication method for new user is localauth
1.248     foxr     5829: #
                   5830: # Formal Parameters:
                   5831: #    $cmd     - The command request that got us dispatched.
                   5832: #    $tail    - The tail of the command.   In this case this is a colon separated
                   5833: #               set of words that will be split into:
1.340     raeburn  5834: #               $authparam - An authentication parameter (localauth parameter).
1.248     foxr     5835: #               $cdom      - The domain of the course from the institution's
                   5836: #                            point of view.
                   5837: #    $client  - The socket open on the client.
                   5838: # Returns:
                   5839: #    1 - continue processing.
                   5840: #
                   5841: sub create_auto_enroll_password_handler {
                   5842:     my ($cmd, $tail, $client) = @_;
                   5843:     my $userinput = "$cmd:$tail";
                   5844: 
                   5845:     my ($authparam, $cdom) = split(/:/, $userinput);
                   5846: 
                   5847:     my ($create_passwd,$authchk);
                   5848:     ($authparam,
                   5849:      $create_passwd,
                   5850:      $authchk) = &localenroll::create_password($authparam,$cdom);
                   5851: 
                   5852:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
                   5853: 	   $userinput);
                   5854: 
                   5855: 
                   5856:     return 1;
                   5857: }
                   5858: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
                   5859: 		  0, 1, 0);
                   5860: 
1.522     raeburn  5861: sub auto_export_grades_handler {
                   5862:     my ($cmd, $tail, $client) = @_;
                   5863:     my $userinput = "$cmd:$tail";
                   5864:     my ($cdom,$cnum,$info,$data) = split(/:/,$tail);
                   5865:     my $inforef = &Apache::lonnet::thaw_unescape($info);
                   5866:     my $dataref = &Apache::lonnet::thaw_unescape($data);
                   5867:     my ($outcome,$result);;
                   5868:     eval {
                   5869:         local($SIG{__DIE__})='DEFAULT';
                   5870:         my %rtnhash;
                   5871:         $outcome=&localenroll::export_grades($cdom,$cnum,$inforef,$dataref,\%rtnhash);
                   5872:         if ($outcome eq 'ok') {
                   5873:             foreach my $key (keys(%rtnhash)) {
                   5874:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   5875:             }
                   5876:             $result =~ s/\&$//;
                   5877:         }
                   5878:     };
                   5879:     if (!$@) {
                   5880:         if ($outcome eq 'ok') {
                   5881:             if ($cipher) {
                   5882:                 my $cmdlength=length($result);
                   5883:                 $result.="         ";
                   5884:                 my $encresult='';
                   5885:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   5886:                     $encresult.= unpack("H16",
                   5887:                                         $cipher->encrypt(substr($result,
                   5888:                                                                 $encidx,
                   5889:                                                                 8)));
                   5890:                 }
                   5891:                 &Reply( $client, "enc:$cmdlength:$encresult\n", $userinput);
                   5892:             } else {
                   5893:                 &Failure( $client, "error:no_key\n", $userinput);
                   5894:             }
                   5895:         } else {
                   5896:             &Reply($client, "$outcome\n", $userinput);
                   5897:         }
                   5898:     } else {
                   5899:         &Failure($client,"export_error\n",$userinput);
                   5900:     }
                   5901:     return 1;
                   5902: }
                   5903: &register_handler("autoexportgrades", \&auto_export_grades_handler,
1.536     raeburn  5904:                   1, 1, 0);
1.522     raeburn  5905: 
1.248     foxr     5906: #   Retrieve and remove temporary files created by/during autoenrollment.
                   5907: #
                   5908: # Formal Parameters:
                   5909: #    $cmd      - The command that got us dispatched.
                   5910: #    $tail     - The tail of the command.  In our case this is a colon 
                   5911: #                separated list that will be split into:
1.526     raeburn  5912: #                $filename - The name of the file to retrieve.
1.248     foxr     5913: #                            The filename is given as a path relative to
                   5914: #                            the LonCAPA temp file directory.
                   5915: #    $client   - Socket open on the client.
                   5916: #
                   5917: # Returns:
                   5918: #   1     - Continue processing.
                   5919: sub retrieve_auto_file_handler {
                   5920:     my ($cmd, $tail, $client)    = @_;
                   5921:     my $userinput                = "cmd:$tail";
                   5922: 
                   5923:     my ($filename)   = split(/:/, $tail);
                   5924: 
                   5925:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
1.521     raeburn  5926: 
                   5927:     if ($filename =~m{/\.\./}) {
                   5928:         &Failure($client, "refused\n", $userinput);
1.526     raeburn  5929:     } elsif ($filename !~ /^$LONCAPA::match_domain\_$LONCAPA::match_courseid\_.+_classlist\.xml$/) {
                   5930:         &Failure($client, "refused\n", $userinput);
1.521     raeburn  5931:     } elsif ( (-e $source) && ($filename ne '') ) {
1.248     foxr     5932: 	my $reply = '';
                   5933: 	if (open(my $fh,$source)) {
                   5934: 	    while (<$fh>) {
                   5935: 		chomp($_);
                   5936: 		$_ =~ s/^\s+//g;
                   5937: 		$_ =~ s/\s+$//g;
                   5938: 		$reply .= $_;
                   5939: 	    }
                   5940: 	    close($fh);
                   5941: 	    &Reply($client, &escape($reply)."\n", $userinput);
                   5942: 
                   5943: #   Does this have to be uncommented??!?  (RF).
                   5944: #
                   5945: #                                unlink($source);
                   5946: 	} else {
                   5947: 	    &Failure($client, "error\n", $userinput);
                   5948: 	}
                   5949:     } else {
                   5950: 	&Failure($client, "error\n", $userinput);
                   5951:     }
                   5952:     
                   5953: 
                   5954:     return 1;
                   5955: }
                   5956: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
                   5957: 
1.423     raeburn  5958: sub crsreq_checks_handler {
                   5959:     my ($cmd, $tail, $client) = @_;
                   5960:     my $userinput = "$cmd:$tail";
                   5961:     my $dom = $tail;
                   5962:     my $result;
1.519     raeburn  5963:     my @reqtypes = ('official','unofficial','community','textbook','placement');
1.423     raeburn  5964:     eval {
                   5965:         local($SIG{__DIE__})='DEFAULT';
                   5966:         my %validations;
1.424     raeburn  5967:         my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
                   5968:                                                    \%validations);
1.423     raeburn  5969:         if ($response eq 'ok') { 
                   5970:             foreach my $key (keys(%validations)) {
                   5971:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   5972:             }
                   5973:             $result =~ s/\&$//;
                   5974:         } else {
                   5975:             $result = 'error';
                   5976:         }
                   5977:     };
                   5978:     if (!$@) {
                   5979:         &Reply($client, \$result, $userinput);
                   5980:     } else {
                   5981:         &Failure($client,"unknown_cmd\n",$userinput);
                   5982:     }
                   5983:     return 1;
                   5984: }
                   5985: &register_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
                   5986: 
                   5987: sub validate_crsreq_handler {
                   5988:     my ($cmd, $tail, $client) = @_;
                   5989:     my $userinput = "$cmd:$tail";
1.508     raeburn  5990:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
1.423     raeburn  5991:     $instcode = &unescape($instcode);
                   5992:     $owner = &unescape($owner);
                   5993:     $crstype = &unescape($crstype);
                   5994:     $inststatuslist = &unescape($inststatuslist);
                   5995:     $instcode = &unescape($instcode);
                   5996:     $instseclist = &unescape($instseclist);
1.508     raeburn  5997:     my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
1.423     raeburn  5998:     my $outcome;
                   5999:     eval {
                   6000:         local($SIG{__DIE__})='DEFAULT';
                   6001:         $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
                   6002:                                                  $inststatuslist,$instcode,
1.508     raeburn  6003:                                                  $instseclist,$custominfo);
1.423     raeburn  6004:     };
                   6005:     if (!$@) {
                   6006:         &Reply($client, \$outcome, $userinput);
                   6007:     } else {
                   6008:         &Failure($client,"unknown_cmd\n",$userinput);
                   6009:     }
                   6010:     return 1;
                   6011: }
                   6012: &register_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
                   6013: 
1.506     raeburn  6014: sub crsreq_update_handler {
                   6015:     my ($cmd, $tail, $client) = @_;
                   6016:     my $userinput = "$cmd:$tail";
1.509     raeburn  6017:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
                   6018:         $accessstart,$accessend,$infohashref) =
1.506     raeburn  6019:         split(/:/, $tail);
                   6020:     $crstype = &unescape($crstype);
                   6021:     $action = &unescape($action);
                   6022:     $ownername = &unescape($ownername);
                   6023:     $ownerdomain = &unescape($ownerdomain);
                   6024:     $fullname = &unescape($fullname);
                   6025:     $title = &unescape($title);
                   6026:     $code = &unescape($code);
1.509     raeburn  6027:     $accessstart = &unescape($accessstart);
                   6028:     $accessend = &unescape($accessend);
1.506     raeburn  6029:     my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
                   6030:     my ($result,$outcome);
                   6031:     eval {
                   6032:         local($SIG{__DIE__})='DEFAULT';
                   6033:         my %rtnhash;
                   6034:         $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
                   6035:                                                 $ownername,$ownerdomain,$fullname,
1.509     raeburn  6036:                                                 $title,$code,$accessstart,$accessend,
                   6037:                                                 $incoming,\%rtnhash);
1.506     raeburn  6038:         if ($outcome eq 'ok') {
1.515     raeburn  6039:             my @posskeys = qw(createdweb createdmsg createdcustomized createdactions queuedweb queuedmsg formitems reviewweb validationjs onload javascript);
1.506     raeburn  6040:             foreach my $key (keys(%rtnhash)) {
                   6041:                 if (grep(/^\Q$key\E/,@posskeys)) {
                   6042:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   6043:                 }
                   6044:             }
                   6045:             $result =~ s/\&$//;
                   6046:         }
                   6047:     };
                   6048:     if (!$@) {
                   6049:         if ($outcome eq 'ok') {
                   6050:             &Reply($client, \$result, $userinput);
                   6051:         } else {
                   6052:             &Reply($client, "format_error\n", $userinput);
                   6053:         }
                   6054:     } else {
                   6055:         &Failure($client,"unknown_cmd\n",$userinput);
                   6056:     }
                   6057:     return 1;
                   6058: }
                   6059: &register_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
                   6060: 
1.248     foxr     6061: #
                   6062: #   Read and retrieve institutional code format (for support form).
                   6063: # Formal Parameters:
                   6064: #    $cmd        - Command that dispatched us.
                   6065: #    $tail       - Tail of the command.  In this case it conatins 
                   6066: #                  the course domain and the coursename.
                   6067: #    $client     - Socket open on the client.
                   6068: # Returns:
                   6069: #    1     - Continue processing.
                   6070: #
                   6071: sub get_institutional_code_format_handler {
                   6072:     my ($cmd, $tail, $client)   = @_;
                   6073:     my $userinput               = "$cmd:$tail";
                   6074: 
                   6075:     my $reply;
                   6076:     my($cdom,$course) = split(/:/,$tail);
                   6077:     my @pairs = split/\&/,$course;
                   6078:     my %instcodes = ();
                   6079:     my %codes = ();
                   6080:     my @codetitles = ();
                   6081:     my %cat_titles = ();
                   6082:     my %cat_order = ();
                   6083:     foreach (@pairs) {
                   6084: 	my ($key,$value) = split/=/,$_;
                   6085: 	$instcodes{&unescape($key)} = &unescape($value);
                   6086:     }
                   6087:     my $formatreply = &localenroll::instcode_format($cdom,
                   6088: 						    \%instcodes,
                   6089: 						    \%codes,
                   6090: 						    \@codetitles,
                   6091: 						    \%cat_titles,
                   6092: 						    \%cat_order);
                   6093:     if ($formatreply eq 'ok') {
1.365     albertel 6094: 	my $codes_str = &Apache::lonnet::hash2str(%codes);
                   6095: 	my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
                   6096: 	my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
                   6097: 	my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
1.248     foxr     6098: 	&Reply($client,
                   6099: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
                   6100: 	       .$cat_order_str."\n",
                   6101: 	       $userinput);
                   6102:     } else {
                   6103: 	# this else branch added by RF since if not ok, lonc will
                   6104: 	# hang waiting on reply until timeout.
                   6105: 	#
                   6106: 	&Reply($client, "format_error\n", $userinput);
                   6107:     }
                   6108:     
                   6109:     return 1;
                   6110: }
1.265     albertel 6111: &register_handler("autoinstcodeformat",
                   6112: 		  \&get_institutional_code_format_handler,0,1,0);
1.246     foxr     6113: 
1.345     raeburn  6114: sub get_institutional_defaults_handler {
                   6115:     my ($cmd, $tail, $client)   = @_;
                   6116:     my $userinput               = "$cmd:$tail";
                   6117: 
                   6118:     my $dom = $tail;
                   6119:     my %defaults_hash;
                   6120:     my @code_order;
                   6121:     my $outcome;
                   6122:     eval {
                   6123:         local($SIG{__DIE__})='DEFAULT';
                   6124:         $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
                   6125:                                                    \@code_order);
                   6126:     };
                   6127:     if (!$@) {
                   6128:         if ($outcome eq 'ok') {
                   6129:             my $result='';
                   6130:             while (my ($key,$value) = each(%defaults_hash)) {
                   6131:                 $result.=&escape($key).'='.&escape($value).'&';
                   6132:             }
                   6133:             $result .= 'code_order='.&escape(join('&',@code_order));
1.387     albertel 6134:             &Reply($client,\$result,$userinput);
1.345     raeburn  6135:         } else {
                   6136:             &Reply($client,"error\n", $userinput);
                   6137:         }
                   6138:     } else {
                   6139:         &Failure($client,"unknown_cmd\n",$userinput);
                   6140:     }
                   6141: }
                   6142: &register_handler("autoinstcodedefaults",
                   6143:                   \&get_institutional_defaults_handler,0,1,0);
                   6144: 
1.416     raeburn  6145: sub get_possible_instcodes_handler {
                   6146:     my ($cmd, $tail, $client)   = @_;
                   6147:     my $userinput               = "$cmd:$tail";
                   6148: 
                   6149:     my $reply;
                   6150:     my $cdom = $tail;
1.417     raeburn  6151:     my (@codetitles,%cat_titles,%cat_order,@code_order);
1.416     raeburn  6152:     my $formatreply = &localenroll::possible_instcodes($cdom,
                   6153:                                                        \@codetitles,
                   6154:                                                        \%cat_titles,
1.417     raeburn  6155:                                                        \%cat_order,
                   6156:                                                        \@code_order);
1.416     raeburn  6157:     if ($formatreply eq 'ok') {
                   6158:         my $result = join('&',map {&escape($_);} (@codetitles)).':';
1.417     raeburn  6159:         $result .= join('&',map {&escape($_);} (@code_order)).':';
1.416     raeburn  6160:         foreach my $key (keys(%cat_titles)) {
                   6161:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
                   6162:         }
                   6163:         $result =~ s/\&$//;
                   6164:         $result .= ':';
                   6165:         foreach my $key (keys(%cat_order)) {
                   6166:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
                   6167:         }
                   6168:         $result =~ s/\&$//;
                   6169:         &Reply($client,\$result,$userinput);
                   6170:     } else {
                   6171:         &Reply($client, "format_error\n", $userinput);
                   6172:     }
                   6173:     return 1;
                   6174: }
                   6175: &register_handler("autopossibleinstcodes",
                   6176:                   \&get_possible_instcodes_handler,0,1,0);
                   6177: 
1.381     raeburn  6178: sub get_institutional_user_rules {
                   6179:     my ($cmd, $tail, $client)   = @_;
                   6180:     my $userinput               = "$cmd:$tail";
                   6181:     my $dom = &unescape($tail);
                   6182:     my (%rules_hash,@rules_order);
                   6183:     my $outcome;
                   6184:     eval {
                   6185:         local($SIG{__DIE__})='DEFAULT';
                   6186:         $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
                   6187:     };
                   6188:     if (!$@) {
                   6189:         if ($outcome eq 'ok') {
                   6190:             my $result;
                   6191:             foreach my $key (keys(%rules_hash)) {
                   6192:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6193:             }
                   6194:             $result =~ s/\&$//;
                   6195:             $result .= ':';
                   6196:             if (@rules_order > 0) {
                   6197:                 foreach my $item (@rules_order) {
                   6198:                     $result .= &escape($item).'&';
                   6199:                 }
                   6200:             }
                   6201:             $result =~ s/\&$//;
1.387     albertel 6202:             &Reply($client,\$result,$userinput);
1.381     raeburn  6203:         } else {
                   6204:             &Reply($client,"error\n", $userinput);
                   6205:         }
                   6206:     } else {
                   6207:         &Failure($client,"unknown_cmd\n",$userinput);
                   6208:     }
                   6209: }
                   6210: &register_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
                   6211: 
1.389     raeburn  6212: sub get_institutional_id_rules {
                   6213:     my ($cmd, $tail, $client)   = @_;
                   6214:     my $userinput               = "$cmd:$tail";
                   6215:     my $dom = &unescape($tail);
                   6216:     my (%rules_hash,@rules_order);
                   6217:     my $outcome;
                   6218:     eval {
                   6219:         local($SIG{__DIE__})='DEFAULT';
                   6220:         $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
                   6221:     };
                   6222:     if (!$@) {
                   6223:         if ($outcome eq 'ok') {
                   6224:             my $result;
                   6225:             foreach my $key (keys(%rules_hash)) {
                   6226:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6227:             }
                   6228:             $result =~ s/\&$//;
                   6229:             $result .= ':';
                   6230:             if (@rules_order > 0) {
                   6231:                 foreach my $item (@rules_order) {
                   6232:                     $result .= &escape($item).'&';
                   6233:                 }
                   6234:             }
                   6235:             $result =~ s/\&$//;
                   6236:             &Reply($client,\$result,$userinput);
                   6237:         } else {
                   6238:             &Reply($client,"error\n", $userinput);
                   6239:         }
                   6240:     } else {
                   6241:         &Failure($client,"unknown_cmd\n",$userinput);
                   6242:     }
                   6243: }
                   6244: &register_handler("instidrules",\&get_institutional_id_rules,0,1,0);
                   6245: 
1.397     raeburn  6246: sub get_institutional_selfcreate_rules {
1.396     raeburn  6247:     my ($cmd, $tail, $client)   = @_;
                   6248:     my $userinput               = "$cmd:$tail";
                   6249:     my $dom = &unescape($tail);
                   6250:     my (%rules_hash,@rules_order);
                   6251:     my $outcome;
                   6252:     eval {
                   6253:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6254:         $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
1.396     raeburn  6255:     };
                   6256:     if (!$@) {
                   6257:         if ($outcome eq 'ok') {
                   6258:             my $result;
                   6259:             foreach my $key (keys(%rules_hash)) {
                   6260:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6261:             }
                   6262:             $result =~ s/\&$//;
                   6263:             $result .= ':';
                   6264:             if (@rules_order > 0) {
                   6265:                 foreach my $item (@rules_order) {
                   6266:                     $result .= &escape($item).'&';
                   6267:                 }
                   6268:             }
                   6269:             $result =~ s/\&$//;
                   6270:             &Reply($client,\$result,$userinput);
                   6271:         } else {
                   6272:             &Reply($client,"error\n", $userinput);
                   6273:         }
                   6274:     } else {
                   6275:         &Failure($client,"unknown_cmd\n",$userinput);
                   6276:     }
                   6277: }
1.397     raeburn  6278: &register_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
1.396     raeburn  6279: 
1.381     raeburn  6280: 
                   6281: sub institutional_username_check {
                   6282:     my ($cmd, $tail, $client)   = @_;
                   6283:     my $userinput               = "$cmd:$tail";
                   6284:     my %rulecheck;
                   6285:     my $outcome;
                   6286:     my ($udom,$uname,@rules) = split(/:/,$tail);
                   6287:     $udom = &unescape($udom);
                   6288:     $uname = &unescape($uname);
                   6289:     @rules = map {&unescape($_);} (@rules);
                   6290:     eval {
                   6291:         local($SIG{__DIE__})='DEFAULT';
                   6292:         $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
                   6293:     };
                   6294:     if (!$@) {
                   6295:         if ($outcome eq 'ok') {
                   6296:             my $result='';
                   6297:             foreach my $key (keys(%rulecheck)) {
                   6298:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6299:             }
1.387     albertel 6300:             &Reply($client,\$result,$userinput);
1.381     raeburn  6301:         } else {
                   6302:             &Reply($client,"error\n", $userinput);
                   6303:         }
                   6304:     } else {
                   6305:         &Failure($client,"unknown_cmd\n",$userinput);
                   6306:     }
                   6307: }
                   6308: &register_handler("instrulecheck",\&institutional_username_check,0,1,0);
                   6309: 
1.389     raeburn  6310: sub institutional_id_check {
                   6311:     my ($cmd, $tail, $client)   = @_;
                   6312:     my $userinput               = "$cmd:$tail";
                   6313:     my %rulecheck;
                   6314:     my $outcome;
                   6315:     my ($udom,$id,@rules) = split(/:/,$tail);
                   6316:     $udom = &unescape($udom);
                   6317:     $id = &unescape($id);
                   6318:     @rules = map {&unescape($_);} (@rules);
                   6319:     eval {
                   6320:         local($SIG{__DIE__})='DEFAULT';
                   6321:         $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
                   6322:     };
                   6323:     if (!$@) {
                   6324:         if ($outcome eq 'ok') {
                   6325:             my $result='';
                   6326:             foreach my $key (keys(%rulecheck)) {
                   6327:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6328:             }
                   6329:             &Reply($client,\$result,$userinput);
                   6330:         } else {
                   6331:             &Reply($client,"error\n", $userinput);
                   6332:         }
                   6333:     } else {
                   6334:         &Failure($client,"unknown_cmd\n",$userinput);
                   6335:     }
                   6336: }
                   6337: &register_handler("instidrulecheck",\&institutional_id_check,0,1,0);
1.345     raeburn  6338: 
1.397     raeburn  6339: sub institutional_selfcreate_check {
1.396     raeburn  6340:     my ($cmd, $tail, $client)   = @_;
                   6341:     my $userinput               = "$cmd:$tail";
                   6342:     my %rulecheck;
                   6343:     my $outcome;
                   6344:     my ($udom,$email,@rules) = split(/:/,$tail);
                   6345:     $udom = &unescape($udom);
                   6346:     $email = &unescape($email);
                   6347:     @rules = map {&unescape($_);} (@rules);
                   6348:     eval {
                   6349:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6350:         $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
1.396     raeburn  6351:     };
                   6352:     if (!$@) {
                   6353:         if ($outcome eq 'ok') {
                   6354:             my $result='';
                   6355:             foreach my $key (keys(%rulecheck)) {
                   6356:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6357:             }
                   6358:             &Reply($client,\$result,$userinput);
                   6359:         } else {
                   6360:             &Reply($client,"error\n", $userinput);
                   6361:         }
                   6362:     } else {
                   6363:         &Failure($client,"unknown_cmd\n",$userinput);
                   6364:     }
                   6365: }
1.397     raeburn  6366: &register_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
1.396     raeburn  6367: 
1.317     raeburn  6368: # Get domain specific conditions for import of student photographs to a course
                   6369: #
                   6370: # Retrieves information from photo_permission subroutine in localenroll.
                   6371: # Returns outcome (ok) if no processing errors, and whether course owner is 
                   6372: # required to accept conditions of use (yes/no).
                   6373: #
                   6374: #    
                   6375: sub photo_permission_handler {
                   6376:     my ($cmd, $tail, $client)   = @_;
                   6377:     my $userinput               = "$cmd:$tail";
                   6378:     my $cdom = $tail;
                   6379:     my ($perm_reqd,$conditions);
1.320     albertel 6380:     my $outcome;
                   6381:     eval {
                   6382: 	local($SIG{__DIE__})='DEFAULT';
                   6383: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
                   6384: 						  \$conditions);
                   6385:     };
                   6386:     if (!$@) {
                   6387: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
                   6388: 	       $userinput);
                   6389:     } else {
                   6390: 	&Failure($client,"unknown_cmd\n",$userinput);
                   6391:     }
                   6392:     return 1;
1.317     raeburn  6393: }
                   6394: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
                   6395: 
                   6396: #
                   6397: # Checks if student photo is available for a user in the domain, in the user's
                   6398: # directory (in /userfiles/internal/studentphoto.jpg).
                   6399: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
                   6400: # the student's photo.   
                   6401: 
                   6402: sub photo_check_handler {
                   6403:     my ($cmd, $tail, $client)   = @_;
                   6404:     my $userinput               = "$cmd:$tail";
                   6405:     my ($udom,$uname,$pid) = split(/:/,$tail);
                   6406:     $udom = &unescape($udom);
                   6407:     $uname = &unescape($uname);
                   6408:     $pid = &unescape($pid);
                   6409:     my $path=&propath($udom,$uname).'/userfiles/internal/';
                   6410:     if (!-e $path) {
                   6411:         &mkpath($path);
                   6412:     }
                   6413:     my $response;
                   6414:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
                   6415:     $result .= ':'.$response;
                   6416:     &Reply($client, &escape($result)."\n",$userinput);
1.320     albertel 6417:     return 1;
1.317     raeburn  6418: }
                   6419: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
                   6420: 
                   6421: #
                   6422: # Retrieve information from localenroll about whether to provide a button     
                   6423: # for users who have enbled import of student photos to initiate an 
                   6424: # update of photo files for registered students. Also include 
                   6425: # comment to display alongside button.  
                   6426: 
                   6427: sub photo_choice_handler {
                   6428:     my ($cmd, $tail, $client) = @_;
                   6429:     my $userinput             = "$cmd:$tail";
                   6430:     my $cdom                  = &unescape($tail);
1.320     albertel 6431:     my ($update,$comment);
                   6432:     eval {
                   6433: 	local($SIG{__DIE__})='DEFAULT';
                   6434: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
                   6435:     };
                   6436:     if (!$@) {
                   6437: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
                   6438:     } else {
                   6439: 	&Failure($client,"unknown_cmd\n",$userinput);
                   6440:     }
                   6441:     return 1;
1.317     raeburn  6442: }
                   6443: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
                   6444: 
1.265     albertel 6445: #
                   6446: # Gets a student's photo to exist (in the correct image type) in the user's 
                   6447: # directory.
                   6448: # Formal Parameters:
                   6449: #    $cmd     - The command request that got us dispatched.
                   6450: #    $tail    - A colon separated set of words that will be split into:
                   6451: #               $domain - student's domain
                   6452: #               $uname  - student username
                   6453: #               $type   - image type desired
                   6454: #    $client  - The socket open on the client.
                   6455: # Returns:
                   6456: #    1 - continue processing.
1.317     raeburn  6457: 
1.265     albertel 6458: sub student_photo_handler {
                   6459:     my ($cmd, $tail, $client) = @_;
1.317     raeburn  6460:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
1.265     albertel 6461: 
1.317     raeburn  6462:     my $path=&propath($domain,$uname). '/userfiles/internal/';
                   6463:     my $filename = 'studentphoto.'.$ext;
                   6464:     if ($type eq 'thumbnail') {
                   6465:         $filename = 'studentphoto_tn.'.$ext;
                   6466:     }
                   6467:     if (-e $path.$filename) {
1.265     albertel 6468: 	&Reply($client,"ok\n","$cmd:$tail");
                   6469: 	return 1;
                   6470:     }
                   6471:     &mkpath($path);
1.317     raeburn  6472:     my $file;
                   6473:     if ($type eq 'thumbnail') {
1.320     albertel 6474: 	eval {
                   6475: 	    local($SIG{__DIE__})='DEFAULT';
                   6476: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
                   6477: 	};
1.317     raeburn  6478:     } else {
                   6479:         $file=&localstudentphoto::fetch($domain,$uname);
                   6480:     }
1.265     albertel 6481:     if (!$file) {
                   6482: 	&Failure($client,"unavailable\n","$cmd:$tail");
                   6483: 	return 1;
                   6484:     }
1.317     raeburn  6485:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
                   6486:     if (-e $path.$filename) {
1.265     albertel 6487: 	&Reply($client,"ok\n","$cmd:$tail");
                   6488: 	return 1;
                   6489:     }
                   6490:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
                   6491:     return 1;
                   6492: }
                   6493: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246     foxr     6494: 
1.361     raeburn  6495: sub inst_usertypes_handler {
                   6496:     my ($cmd, $domain, $client) = @_;
                   6497:     my $res;
                   6498:     my $userinput = $cmd.":".$domain; # For logging purposes.
1.370     albertel 6499:     my (%typeshash,@order,$result);
                   6500:     eval {
                   6501: 	local($SIG{__DIE__})='DEFAULT';
                   6502: 	$result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
                   6503:     };
                   6504:     if ($result eq 'ok') {
1.361     raeburn  6505:         if (keys(%typeshash) > 0) {
                   6506:             foreach my $key (keys(%typeshash)) {
                   6507:                 $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
                   6508:             }
                   6509:         }
                   6510:         $res=~s/\&$//;
                   6511:         $res .= ':';
                   6512:         if (@order > 0) {
                   6513:             foreach my $item (@order) {
                   6514:                 $res .= &escape($item).'&';
                   6515:             }
                   6516:         }
                   6517:         $res=~s/\&$//;
                   6518:     }
1.387     albertel 6519:     &Reply($client, \$res, $userinput);
1.361     raeburn  6520:     return 1;
                   6521: }
                   6522: &register_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
                   6523: 
1.264     albertel 6524: # mkpath makes all directories for a file, expects an absolute path with a
                   6525: # file or a trailing / if just a dir is passed
                   6526: # returns 1 on success 0 on failure
                   6527: sub mkpath {
                   6528:     my ($file)=@_;
                   6529:     my @parts=split(/\//,$file,-1);
                   6530:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
                   6531:     for (my $i=3;$i<= ($#parts-1);$i++) {
1.265     albertel 6532: 	$now.='/'.$parts[$i]; 
1.264     albertel 6533: 	if (!-e $now) {
                   6534: 	    if  (!mkdir($now,0770)) { return 0; }
                   6535: 	}
                   6536:     }
                   6537:     return 1;
                   6538: }
                   6539: 
1.207     foxr     6540: #---------------------------------------------------------------
                   6541: #
                   6542: #   Getting, decoding and dispatching requests:
                   6543: #
                   6544: #
                   6545: #   Get a Request:
                   6546: #   Gets a Request message from the client.  The transaction
                   6547: #   is defined as a 'line' of text.  We remove the new line
                   6548: #   from the text line.  
1.226     foxr     6549: #
1.211     albertel 6550: sub get_request {
1.207     foxr     6551:     my $input = <$client>;
                   6552:     chomp($input);
1.226     foxr     6553: 
1.234     foxr     6554:     &Debug("get_request: Request = $input\n");
1.207     foxr     6555: 
                   6556:     &status('Processing '.$clientname.':'.$input);
                   6557: 
                   6558:     return $input;
                   6559: }
1.212     foxr     6560: #---------------------------------------------------------------
                   6561: #
                   6562: #  Process a request.  This sub should shrink as each action
                   6563: #  gets farmed out into a separat sub that is registered 
                   6564: #  with the dispatch hash.  
                   6565: #
                   6566: # Parameters:
                   6567: #    user_input   - The request received from the client (lonc).
1.525     raeburn  6568: #
1.212     foxr     6569: # Returns:
                   6570: #    true to keep processing, false if caller should exit.
                   6571: #
                   6572: sub process_request {
1.525     raeburn  6573:     my ($userinput) = @_; # Easier for now to break style than to
                   6574:                           # fix all the userinput -> user_input.
1.212     foxr     6575:     my $wasenc    = 0;		# True if request was encrypted.
                   6576: # ------------------------------------------------------------ See if encrypted
1.322     albertel 6577:     # for command
                   6578:     # sethost:<server>
                   6579:     # <command>:<args>
                   6580:     #   we just send it to the processor
                   6581:     # for
                   6582:     # sethost:<server>:<command>:<args>
                   6583:     #  we do the implict set host and then do the command
                   6584:     if ($userinput =~ /^sethost:/) {
                   6585: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
                   6586: 	if (defined($userinput)) {
                   6587: 	    &sethost("$cmd:$newid");
                   6588: 	} else {
                   6589: 	    $userinput = "$cmd:$newid";
                   6590: 	}
                   6591:     }
                   6592: 
1.212     foxr     6593:     if ($userinput =~ /^enc/) {
                   6594: 	$userinput = decipher($userinput);
                   6595: 	$wasenc=1;
                   6596: 	if(!$userinput) {	# Cipher not defined.
1.251     foxr     6597: 	    &Failure($client, "error: Encrypted data without negotated key\n");
1.212     foxr     6598: 	    return 0;
                   6599: 	}
                   6600:     }
                   6601:     Debug("process_request: $userinput\n");
                   6602:     
1.213     foxr     6603:     #  
                   6604:     #   The 'correct way' to add a command to lond is now to
                   6605:     #   write a sub to execute it and Add it to the command dispatch
                   6606:     #   hash via a call to register_handler..  The comments to that
                   6607:     #   sub should give you enough to go on to show how to do this
                   6608:     #   along with the examples that are building up as this code
                   6609:     #   is getting refactored.   Until all branches of the
                   6610:     #   if/elseif monster below have been factored out into
                   6611:     #   separate procesor subs, if the dispatch hash is missing
                   6612:     #   the command keyword, we will fall through to the remainder
                   6613:     #   of the if/else chain below in order to keep this thing in 
                   6614:     #   working order throughout the transmogrification.
                   6615: 
                   6616:     my ($command, $tail) = split(/:/, $userinput, 2);
                   6617:     chomp($command);
                   6618:     chomp($tail);
                   6619:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
1.214     foxr     6620:     $command =~ s/(\r)//;	# And this too for parameterless commands.
                   6621:     if(!$tail) {
                   6622: 	$tail ="";		# defined but blank.
                   6623:     }
1.213     foxr     6624: 
                   6625:     &Debug("Command received: $command, encoded = $wasenc");
                   6626: 
                   6627:     if(defined $Dispatcher{$command}) {
                   6628: 
                   6629: 	my $dispatch_info = $Dispatcher{$command};
                   6630: 	my $handler       = $$dispatch_info[0];
                   6631: 	my $need_encode   = $$dispatch_info[1];
                   6632: 	my $client_types  = $$dispatch_info[2];
                   6633: 	Debug("Matched dispatch hash: mustencode: $need_encode "
                   6634: 	      ."ClientType $client_types");
                   6635:       
                   6636: 	#  Validate the request:
                   6637:       
                   6638: 	my $ok = 1;
                   6639: 	my $requesterprivs = 0;
                   6640: 	if(&isClient()) {
                   6641: 	    $requesterprivs |= $CLIENT_OK;
                   6642: 	}
                   6643: 	if(&isManager()) {
                   6644: 	    $requesterprivs |= $MANAGER_OK;
                   6645: 	}
                   6646: 	if($need_encode && (!$wasenc)) {
                   6647: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
                   6648: 	    $ok = 0;
                   6649: 	}
                   6650: 	if(($client_types & $requesterprivs) == 0) {
                   6651: 	    Debug("Client not privileged to do this operation");
                   6652: 	    $ok = 0;
                   6653: 	}
1.525     raeburn  6654:         if ($ok) {
1.535     raeburn  6655:             my $realcommand = $command;
                   6656:             if ($command eq 'querysend') {
                   6657:                 my ($query,$rest)=split(/\:/,$tail,2);
                   6658:                 $query=~s/\n*$//g;
                   6659:                 my @possqueries = 
                   6660:                     qw(userlog courselog fetchenrollment institutionalphotos usersearch instdirsearch getinstuser getmultinstusers);
                   6661:                 if (grep(/^\Q$query\E$/,@possqueries)) {
                   6662:                     $command .= '_'.$query;
                   6663:                 } elsif ($query eq 'prepare activity log') {
                   6664:                     $command .= '_activitylog';
                   6665:                 }
                   6666:             }
1.525     raeburn  6667:             if (ref($trust{$command}) eq 'HASH') {
                   6668:                 my $donechecks;
                   6669:                 if ($trust{$command}{'anywhere'}) {
                   6670:                    $donechecks = 1;
                   6671:                 } elsif ($trust{$command}{'manageronly'}) {
                   6672:                     unless (&isManager()) {
                   6673:                         $ok = 0;
                   6674:                     }
                   6675:                     $donechecks = 1;
                   6676:                 } elsif ($trust{$command}{'institutiononly'}) {
                   6677:                     unless ($clientsameinst) {
                   6678:                         $ok = 0;
                   6679:                     }
                   6680:                     $donechecks = 1;
                   6681:                 } elsif ($clientsameinst) {
                   6682:                     $donechecks = 1;
                   6683:                 }
                   6684:                 unless ($donechecks) {
                   6685:                     foreach my $rule (keys(%{$trust{$command}})) {
                   6686:                         next if ($rule eq 'remote');
                   6687:                         if ($trust{$command}{$rule}) {
                   6688:                             if ($clientprohibited{$rule}) {
                   6689:                                 $ok = 0;
                   6690:                             } else {
                   6691:                                 $ok = 1;
                   6692:                                 $donechecks = 1;
                   6693:                                 last;
                   6694:                             }
                   6695:                         }
                   6696:                     }
                   6697:                 }
                   6698:                 unless ($donechecks) {
                   6699:                     if ($trust{$command}{'remote'}) {
                   6700:                         if ($clientremoteok) {
                   6701:                             $ok = 1;
                   6702:                         } else {
                   6703:                             $ok = 0;
                   6704:                         } 
                   6705:                     }
                   6706:                 }
                   6707:             }
1.535     raeburn  6708:             $command = $realcommand;
1.525     raeburn  6709:         }
1.213     foxr     6710: 
                   6711: 	if($ok) {
                   6712: 	    Debug("Dispatching to handler $command $tail");
                   6713: 	    my $keep_going = &$handler($command, $tail, $client);
                   6714: 	    return $keep_going;
                   6715: 	} else {
                   6716: 	    Debug("Refusing to dispatch because client did not match requirements");
                   6717: 	    Failure($client, "refused\n", $userinput);
                   6718: 	    return 1;
                   6719: 	}
1.525     raeburn  6720:     }
1.213     foxr     6721: 
1.262     foxr     6722:     print $client "unknown_cmd\n";
1.212     foxr     6723: # -------------------------------------------------------------------- complete
                   6724:     Debug("process_request - returning 1");
                   6725:     return 1;
                   6726: }
1.207     foxr     6727: #
                   6728: #   Decipher encoded traffic
                   6729: #  Parameters:
                   6730: #     input      - Encoded data.
                   6731: #  Returns:
                   6732: #     Decoded data or undef if encryption key was not yet negotiated.
                   6733: #  Implicit input:
                   6734: #     cipher  - This global holds the negotiated encryption key.
                   6735: #
1.211     albertel 6736: sub decipher {
1.207     foxr     6737:     my ($input)  = @_;
                   6738:     my $output = '';
1.212     foxr     6739:     
                   6740:     
1.207     foxr     6741:     if($cipher) {
                   6742: 	my($enc, $enclength, $encinput) = split(/:/, $input);
                   6743: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
                   6744: 	    $output .= 
                   6745: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
                   6746: 	}
                   6747: 	return substr($output, 0, $enclength);
                   6748:     } else {
                   6749: 	return undef;
                   6750:     }
                   6751: }
                   6752: 
                   6753: #
                   6754: #   Register a command processor.  This function is invoked to register a sub
                   6755: #   to process a request.  Once registered, the ProcessRequest sub can automatically
                   6756: #   dispatch requests to an appropriate sub, and do the top level validity checking
                   6757: #   as well:
                   6758: #    - Is the keyword recognized.
                   6759: #    - Is the proper client type attempting the request.
                   6760: #    - Is the request encrypted if it has to be.
                   6761: #   Parameters:
                   6762: #    $request_name         - Name of the request being registered.
                   6763: #                           This is the command request that will match
                   6764: #                           against the hash keywords to lookup the information
                   6765: #                           associated with the dispatch information.
                   6766: #    $procedure           - Reference to a sub to call to process the request.
                   6767: #                           All subs get called as follows:
                   6768: #                             Procedure($cmd, $tail, $replyfd, $key)
                   6769: #                             $cmd    - the actual keyword that invoked us.
                   6770: #                             $tail   - the tail of the request that invoked us.
                   6771: #                             $replyfd- File descriptor connected to the client
                   6772: #    $must_encode          - True if the request must be encoded to be good.
                   6773: #    $client_ok            - True if it's ok for a client to request this.
                   6774: #    $manager_ok           - True if it's ok for a manager to request this.
                   6775: # Side effects:
                   6776: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
                   6777: #      - On failure, the program will die as it's a bad internal bug to try to 
                   6778: #        register a duplicate command handler.
                   6779: #
1.211     albertel 6780: sub register_handler {
1.212     foxr     6781:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
1.207     foxr     6782: 
                   6783:     #  Don't allow duplication#
                   6784:    
                   6785:     if (defined $Dispatcher{$request_name}) {
                   6786: 	die "Attempting to define a duplicate request handler for $request_name\n";
                   6787:     }
                   6788:     #   Build the client type mask:
                   6789:     
                   6790:     my $client_type_mask = 0;
                   6791:     if($client_ok) {
                   6792: 	$client_type_mask  |= $CLIENT_OK;
                   6793:     }
                   6794:     if($manager_ok) {
                   6795: 	$client_type_mask  |= $MANAGER_OK;
                   6796:     }
                   6797:    
                   6798:     #  Enter the hash:
                   6799:       
                   6800:     my @entry = ($procedure, $must_encode, $client_type_mask);
                   6801:    
                   6802:     $Dispatcher{$request_name} = \@entry;
                   6803:    
                   6804: }
                   6805: 
                   6806: 
                   6807: #------------------------------------------------------------------
                   6808: 
                   6809: 
                   6810: 
                   6811: 
1.141     foxr     6812: #
1.96      foxr     6813: #  Convert an error return code from lcpasswd to a string value.
                   6814: #
                   6815: sub lcpasswdstrerror {
                   6816:     my $ErrorCode = shift;
1.97      foxr     6817:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     6818: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   6819:     } else {
1.98      foxr     6820: 	return $passwderrors[$ErrorCode];
1.96      foxr     6821:     }
                   6822: }
                   6823: 
1.23      harris41 6824: # grabs exception and records it to log before exiting
                   6825: sub catchexception {
1.27      albertel 6826:     my ($error)=@_;
1.25      www      6827:     $SIG{'QUIT'}='DEFAULT';
                   6828:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 6829:     &status("Catching exception");
1.190     albertel 6830:     &logthis("<font color='red'>CRITICAL: "
1.373     albertel 6831:      ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
1.27      albertel 6832:      ."a crash with this error msg->[$error]</font>");
1.57      www      6833:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 6834:     if ($client) { print $client "error: $error\n"; }
1.59      www      6835:     $server->close();
1.27      albertel 6836:     die($error);
1.23      harris41 6837: }
1.63      www      6838: sub timeout {
1.165     albertel 6839:     &status("Handling Timeout");
1.190     albertel 6840:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63      www      6841:     &catchexception('Timeout');
                   6842: }
1.22      harris41 6843: # -------------------------------- Set signal handlers to record abnormal exits
                   6844: 
1.226     foxr     6845: 
1.22      harris41 6846: $SIG{'QUIT'}=\&catchexception;
                   6847: $SIG{__DIE__}=\&catchexception;
                   6848: 
1.81      matthew  6849: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 6850: &status("Read loncapa.conf and loncapa_apache.conf");
                   6851: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     6852: %perlvar=%{$perlvarref};
1.80      harris41 6853: undef $perlvarref;
1.19      www      6854: 
1.35      harris41 6855: # ----------------------------- Make sure this process is running from user=www
                   6856: my $wwwid=getpwnam('www');
                   6857: if ($wwwid!=$<) {
1.134     albertel 6858:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   6859:    my $subj="LON: $currenthostid User ID mismatch";
1.37      harris41 6860:    system("echo 'User ID mismatch.  lond must be run as user www.' |\
1.35      harris41 6861:  mailto $emailto -s '$subj' > /dev/null");
                   6862:    exit 1;
                   6863: }
                   6864: 
1.19      www      6865: # --------------------------------------------- Check if other instance running
                   6866: 
                   6867: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   6868: 
                   6869: if (-e $pidfile) {
                   6870:    my $lfh=IO::File->new("$pidfile");
                   6871:    my $pide=<$lfh>;
                   6872:    chomp($pide);
1.29      harris41 6873:    if (kill 0 => $pide) { die "already running"; }
1.19      www      6874: }
1.1       albertel 6875: 
                   6876: # ------------------------------------------------------------- Read hosts file
                   6877: 
                   6878: 
                   6879: 
                   6880: # establish SERVER socket, bind and listen.
                   6881: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   6882:                                 Type      => SOCK_STREAM,
                   6883:                                 Proto     => 'tcp',
1.469     foxr     6884:                                 ReuseAddr     => 1,
1.1       albertel 6885:                                 Listen    => 10 )
1.29      harris41 6886:   or die "making socket: $@\n";
1.1       albertel 6887: 
                   6888: # --------------------------------------------------------- Do global variables
                   6889: 
                   6890: # global variables
                   6891: 
1.134     albertel 6892: my %children               = ();       # keys are current child process IDs
1.1       albertel 6893: 
                   6894: sub REAPER {                        # takes care of dead children
                   6895:     $SIG{CHLD} = \&REAPER;
1.165     albertel 6896:     &status("Handling child death");
1.178     foxr     6897:     my $pid;
                   6898:     do {
                   6899: 	$pid = waitpid(-1,&WNOHANG());
                   6900: 	if (defined($children{$pid})) {
                   6901: 	    &logthis("Child $pid died");
                   6902: 	    delete($children{$pid});
1.183     albertel 6903: 	} elsif ($pid > 0) {
1.178     foxr     6904: 	    &logthis("Unknown Child $pid died");
                   6905: 	}
                   6906:     } while ( $pid > 0 );
                   6907:     foreach my $child (keys(%children)) {
                   6908: 	$pid = waitpid($child,&WNOHANG());
                   6909: 	if ($pid > 0) {
                   6910: 	    &logthis("Child $child - $pid looks like we missed it's death");
                   6911: 	    delete($children{$pid});
                   6912: 	}
1.176     albertel 6913:     }
1.165     albertel 6914:     &status("Finished Handling child death");
1.1       albertel 6915: }
                   6916: 
                   6917: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 6918:     &status("Killing children (INT)");
1.1       albertel 6919:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   6920:     kill 'INT' => keys %children;
1.59      www      6921:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 6922:     my $execdir=$perlvar{'lonDaemons'};
                   6923:     unlink("$execdir/logs/lond.pid");
1.190     albertel 6924:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165     albertel 6925:     &status("Done killing children");
1.1       albertel 6926:     exit;                           # clean up with dignity
                   6927: }
                   6928: 
                   6929: sub HUPSMAN {                      # signal handler for SIGHUP
                   6930:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 6931:     &status("Killing children for restart (HUP)");
1.1       albertel 6932:     kill 'INT' => keys %children;
1.59      www      6933:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190     albertel 6934:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134     albertel 6935:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 6936:     unlink("$execdir/logs/lond.pid");
1.165     albertel 6937:     &status("Restarting self (HUP)");
1.1       albertel 6938:     exec("$execdir/lond");         # here we go again
                   6939: }
                   6940: 
1.144     foxr     6941: #
1.148     foxr     6942: #  Reload the Apache daemon's state.
1.150     foxr     6943: #  This is done by invoking /home/httpd/perl/apachereload
                   6944: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     6945: #
                   6946: sub ReloadApache {
1.473     raeburn  6947: # --------------------------- Handle case of another apachereload process (locking)
1.474     raeburn  6948:     if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
                   6949:         my $execdir = $perlvar{'lonDaemons'};
                   6950:         my $script  = $execdir."/apachereload";
                   6951:         system($script);
                   6952:         unlink('/tmp/lock_apachereload'); #  Remove the lock file.
                   6953:     }
1.148     foxr     6954: }
                   6955: 
                   6956: #
1.144     foxr     6957: #   Called in response to a USR2 signal.
                   6958: #   - Reread hosts.tab
                   6959: #   - All children connected to hosts that were removed from hosts.tab
                   6960: #     are killed via SIGINT
                   6961: #   - All children connected to previously existing hosts are sent SIGUSR1
                   6962: #   - Our internal hosts hash is updated to reflect the new contents of
                   6963: #     hosts.tab causing connections from hosts added to hosts.tab to
                   6964: #     now be honored.
                   6965: #
                   6966: sub UpdateHosts {
1.165     albertel 6967:     &status("Reload hosts.tab");
1.147     foxr     6968:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     6969:     #
                   6970:     #  The %children hash has the set of IP's we currently have children
                   6971:     #  on.  These need to be matched against records in the hosts.tab
                   6972:     #  Any ip's no longer in the table get killed off they correspond to
                   6973:     #  either dropped or changed hosts.  Note that the re-read of the table
                   6974:     #  will take care of new and changed hosts as connections come into being.
                   6975: 
1.371     albertel 6976:     &Apache::lonnet::reset_hosts_info();
1.532     raeburn  6977:     my %active;
1.148     foxr     6978: 
1.368     albertel 6979:     foreach my $child (keys(%children)) {
1.148     foxr     6980: 	my $childip = $children{$child};
1.374     albertel 6981: 	if ($childip ne '127.0.0.1'
                   6982: 	    && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
1.149     foxr     6983: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   6984: 		    ." $child for ip $childip </font>");
1.148     foxr     6985: 	    kill('INT', $child);
1.149     foxr     6986: 	} else {
1.532     raeburn  6987:             $active{$child} = $childip;
1.149     foxr     6988: 	    logthis('<font color="green"> keeping child for ip '
                   6989: 		    ." $childip (pid=$child) </font>");
1.148     foxr     6990: 	}
                   6991:     }
1.532     raeburn  6992: 
                   6993:     my %oldconf = %secureconf;
                   6994:     my %connchange;
                   6995:     if (lonssl::Read_Connect_Config(\%secureconf,\%perlvar) eq 'ok') {
                   6996:         logthis('<font color="blue"> Reloaded SSL connection rules </font>');
                   6997:     } else {
                   6998:         logthis('<font color="yellow"> Failed to reload SSL connection rules </font>');
                   6999:     }
                   7000:     if ((ref($oldconf{'connfrom'}) eq 'HASH') && (ref($secureconf{'connfrom'}) eq 'HASH')) {
                   7001:         foreach my $type ('dom','intdom','other') {
                   7002:             if ((($oldconf{'connfrom'}{$type} eq 'no') && ($secureconf{'connfrom'}{$type} eq 'req')) ||
                   7003:                 (($oldconf{'connfrom'}{$type} eq 'req') && ($secureconf{'connfrom'}{$type} eq 'no'))) {
                   7004:                 $connchange{$type} = 1;
                   7005:             }
                   7006:         }
                   7007:     }
                   7008:     if (keys(%connchange)) {
                   7009:         foreach my $child (keys(%active)) {
                   7010:             my $childip = $active{$child};
                   7011:             if ($childip ne '127.0.0.1') {
                   7012:                 my $childhostname  = gethostbyaddr(Socket::inet_aton($childip),AF_INET);
                   7013:                 if ($childhostname ne '') {
                   7014:                     my $childlonhost = &Apache::lonnet::get_server_homeID($childhostname);
                   7015:                     my ($samedom,$sameinst) = &set_client_info($childlonhost);
                   7016:                     if ($samedom) {
                   7017:                         if ($connchange{'dom'}) {
                   7018:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7019:                                    ." $child for ip $childip </font>");
                   7020:                             kill('INT', $child);
                   7021:                         }
                   7022:                     } elsif ($sameinst) {
                   7023:                         if ($connchange{'intdom'}) {
                   7024:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7025:                                    ." $child for ip $childip </font>");
                   7026:                            kill('INT', $child);
                   7027:                         }
                   7028:                     } else {
                   7029:                         if ($connchange{'other'}) {
                   7030:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7031:                                    ." $child for ip $childip </font>");
                   7032:                             kill('INT', $child);
                   7033:                         }
                   7034:                     }
                   7035:                 }
                   7036:             }
                   7037:         }
                   7038:     }
1.148     foxr     7039:     ReloadApache;
1.165     albertel 7040:     &status("Finished reloading hosts.tab");
1.144     foxr     7041: }
                   7042: 
1.57      www      7043: sub checkchildren {
1.165     albertel 7044:     &status("Checking on the children (sending signals)");
1.57      www      7045:     &initnewstatus();
                   7046:     &logstatus();
                   7047:     &logthis('Going to check on the children');
1.134     albertel 7048:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 7049:     foreach (sort keys %children) {
1.221     albertel 7050: 	#sleep 1;
1.57      www      7051:         unless (kill 'USR1' => $_) {
                   7052: 	    &logthis ('Child '.$_.' is dead');
                   7053:             &logstatus($$.' is dead');
1.221     albertel 7054: 	    delete($children{$_});
1.57      www      7055:         } 
1.61      harris41 7056:     }
1.63      www      7057:     sleep 5;
1.212     foxr     7058:     $SIG{ALRM} = sub { Debug("timeout"); 
                   7059: 		       die "timeout";  };
1.113     albertel 7060:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 7061:     &status("Checking on the children (waiting for reports)");
1.63      www      7062:     foreach (sort keys %children) {
                   7063:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 7064:           eval {
                   7065:             alarm(300);
1.63      www      7066: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 7067: 	    kill 9 => $_;
1.131     albertel 7068: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   7069: 	    #$subj="LON: $currenthostid killed lond process $_";
                   7070: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   7071: 	    #$execdir=$perlvar{'lonDaemons'};
                   7072: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221     albertel 7073: 	    delete($children{$_});
1.113     albertel 7074: 	    alarm(0);
                   7075: 	  }
1.63      www      7076:         }
                   7077:     }
1.113     albertel 7078:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 7079:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 7080:     &status("Finished checking children");
1.221     albertel 7081:     &logthis('Finished Checking children');
1.57      www      7082: }
                   7083: 
1.1       albertel 7084: # --------------------------------------------------------------------- Logging
                   7085: 
                   7086: sub logthis {
                   7087:     my $message=shift;
                   7088:     my $execdir=$perlvar{'lonDaemons'};
                   7089:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   7090:     my $now=time;
                   7091:     my $local=localtime($now);
1.58      www      7092:     $lastlog=$local.': '.$message;
1.1       albertel 7093:     print $fh "$local ($$): $message\n";
                   7094: }
                   7095: 
1.77      foxr     7096: # ------------------------- Conditional log if $DEBUG true.
                   7097: sub Debug {
                   7098:     my $message = shift;
                   7099:     if($DEBUG) {
                   7100: 	&logthis($message);
                   7101:     }
                   7102: }
1.161     foxr     7103: 
                   7104: #
                   7105: #   Sub to do replies to client.. this gives a hook for some
                   7106: #   debug tracing too:
                   7107: #  Parameters:
                   7108: #     fd      - File open on client.
                   7109: #     reply   - Text to send to client.
                   7110: #     request - Original request from client.
                   7111: #
1.490     droeschl 7112: #NOTE $reply must be terminated by exactly *one* \n. If $reply is a reference
                   7113: #this is done automatically ($$reply must not contain any \n in this case). 
                   7114: #If $reply is a string the caller has to ensure this.
1.161     foxr     7115: sub Reply {
1.192     foxr     7116:     my ($fd, $reply, $request) = @_;
1.387     albertel 7117:     if (ref($reply)) {
                   7118: 	print $fd $$reply;
                   7119: 	print $fd "\n";
                   7120: 	if ($DEBUG) { Debug("Request was $request  Reply was $$reply"); }
                   7121:     } else {
                   7122: 	print $fd $reply;
                   7123: 	if ($DEBUG) { Debug("Request was $request  Reply was $reply"); }
                   7124:     }
1.212     foxr     7125:     $Transactions++;
                   7126: }
                   7127: 
                   7128: 
                   7129: #
                   7130: #    Sub to report a failure.
                   7131: #    This function:
                   7132: #     -   Increments the failure statistic counters.
                   7133: #     -   Invokes Reply to send the error message to the client.
                   7134: # Parameters:
                   7135: #    fd       - File descriptor open on the client
                   7136: #    reply    - Reply text to emit.
                   7137: #    request  - The original request message (used by Reply
                   7138: #               to debug if that's enabled.
                   7139: # Implicit outputs:
                   7140: #    $Failures- The number of failures is incremented.
                   7141: #    Reply (invoked here) sends a message to the 
                   7142: #    client:
                   7143: #
                   7144: sub Failure {
                   7145:     my $fd      = shift;
                   7146:     my $reply   = shift;
                   7147:     my $request = shift;
                   7148:    
                   7149:     $Failures++;
                   7150:     Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     7151: }
1.57      www      7152: # ------------------------------------------------------------------ Log status
                   7153: 
                   7154: sub logstatus {
1.178     foxr     7155:     &status("Doing logging");
                   7156:     my $docdir=$perlvar{'lonDocRoot'};
                   7157:     {
                   7158: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200     matthew  7159:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178     foxr     7160:         $fh->close();
                   7161:     }
1.221     albertel 7162:     &status("Finished $$.txt");
                   7163:     {
                   7164: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
                   7165: 	flock(LOG,LOCK_EX);
                   7166: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
                   7167: 	    .$status."\t".$lastlog."\t $keymode\n";
1.275     albertel 7168: 	flock(LOG,LOCK_UN);
1.221     albertel 7169: 	close(LOG);
                   7170:     }
1.178     foxr     7171:     &status("Finished logging");
1.57      www      7172: }
                   7173: 
                   7174: sub initnewstatus {
                   7175:     my $docdir=$perlvar{'lonDocRoot'};
                   7176:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
1.460     foxr     7177:     my $now=time();
1.57      www      7178:     my $local=localtime($now);
                   7179:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      7180:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 7181:     while (my $filename=readdir(DIR)) {
1.64      www      7182:         unlink("$docdir/lon-status/londchld/$filename");
                   7183:     }
                   7184:     closedir(DIR);
1.57      www      7185: }
                   7186: 
                   7187: # -------------------------------------------------------------- Status setting
                   7188: 
                   7189: sub status {
                   7190:     my $what=shift;
                   7191:     my $now=time;
                   7192:     my $local=localtime($now);
1.178     foxr     7193:     $status=$local.': '.$what;
                   7194:     $0='lond: '.$what.' '.$local;
1.57      www      7195: }
1.11      www      7196: 
1.13      www      7197: # -------------------------------------------------------------- Talk to lonsql
                   7198: 
1.234     foxr     7199: sub sql_reply {
1.12      harris41 7200:     my ($cmd)=@_;
1.234     foxr     7201:     my $answer=&sub_sql_reply($cmd);
                   7202:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12      harris41 7203:     return $answer;
                   7204: }
                   7205: 
1.234     foxr     7206: sub sub_sql_reply {
1.12      harris41 7207:     my ($cmd)=@_;
                   7208:     my $unixsock="mysqlsock";
                   7209:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   7210:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   7211:                                       Type    => SOCK_STREAM,
                   7212:                                       Timeout => 10)
                   7213:        or return "con_lost";
1.319     www      7214:     print $sclient "$cmd:$currentdomainid\n";
1.12      harris41 7215:     my $answer=<$sclient>;
                   7216:     chomp($answer);
                   7217:     if (!$answer) { $answer="con_lost"; }
                   7218:     return $answer;
                   7219: }
                   7220: 
1.1       albertel 7221: # --------------------------------------- Is this the home server of an author?
1.11      www      7222: 
1.1       albertel 7223: sub ishome {
                   7224:     my $author=shift;
                   7225:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   7226:     my ($udom,$uname)=split(/\//,$author);
                   7227:     my $proname=propath($udom,$uname);
                   7228:     if (-e $proname) {
                   7229: 	return 'owner';
                   7230:     } else {
                   7231:         return 'not_owner';
                   7232:     }
                   7233: }
                   7234: 
                   7235: # ======================================================= Continue main program
                   7236: # ---------------------------------------------------- Fork once and dissociate
                   7237: 
1.134     albertel 7238: my $fpid=fork;
1.1       albertel 7239: exit if $fpid;
1.29      harris41 7240: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 7241: 
1.29      harris41 7242: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 7243: 
                   7244: # ------------------------------------------------------- Write our PID on disk
                   7245: 
1.134     albertel 7246: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 7247: open (PIDSAVE,">$execdir/logs/lond.pid");
                   7248: print PIDSAVE "$$\n";
                   7249: close(PIDSAVE);
1.190     albertel 7250: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57      www      7251: &status('Starting');
1.1       albertel 7252: 
1.106     foxr     7253: 
1.1       albertel 7254: 
                   7255: # ----------------------------------------------------- Install signal handlers
                   7256: 
1.57      www      7257: 
1.1       albertel 7258: $SIG{CHLD} = \&REAPER;
                   7259: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   7260: $SIG{HUP}  = \&HUPSMAN;
1.57      www      7261: $SIG{USR1} = \&checkchildren;
1.144     foxr     7262: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     7263: 
1.148     foxr     7264: #  Read the host hashes:
1.368     albertel 7265: &Apache::lonnet::load_hosts_tab();
1.447     raeburn  7266: my %iphost = &Apache::lonnet::get_iphost(1);
1.106     foxr     7267: 
1.480     raeburn  7268: $dist=`$perlvar{'lonDaemons'}/distprobe`;
1.286     albertel 7269: 
1.471     raeburn  7270: my $arch = `uname -i`;
1.475     raeburn  7271: chomp($arch);
1.471     raeburn  7272: if ($arch eq 'unknown') {
                   7273:     $arch = `uname -m`;
1.475     raeburn  7274:     chomp($arch);
1.471     raeburn  7275: }
                   7276: 
1.532     raeburn  7277: unless (lonssl::Read_Connect_Config(\%secureconf,\%perlvar) eq 'ok') {
                   7278:     &logthis('<font color="blue">No connectionrules table. Will fallback to loncapa.conf</font>');
                   7279: }
                   7280: 
1.106     foxr     7281: # --------------------------------------------------------------
                   7282: #   Accept connections.  When a connection comes in, it is validated
                   7283: #   and if good, a child process is created to process transactions
                   7284: #   along the connection.
                   7285: 
1.1       albertel 7286: while (1) {
1.165     albertel 7287:     &status('Starting accept');
1.106     foxr     7288:     $client = $server->accept() or next;
1.165     albertel 7289:     &status('Accepted '.$client.' off to spawn');
1.386     albertel 7290:     make_new_child($client);
1.165     albertel 7291:     &status('Finished spawning');
1.1       albertel 7292: }
                   7293: 
1.212     foxr     7294: sub make_new_child {
                   7295:     my $pid;
                   7296: #    my $cipher;     # Now global
                   7297:     my $sigset;
1.178     foxr     7298: 
1.212     foxr     7299:     $client = shift;
                   7300:     &status('Starting new child '.$client);
                   7301:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   7302: 	     ")</font>");    
                   7303:     # block signal for fork
                   7304:     $sigset = POSIX::SigSet->new(SIGINT);
                   7305:     sigprocmask(SIG_BLOCK, $sigset)
                   7306:         or die "Can't block SIGINT for fork: $!\n";
1.178     foxr     7307: 
1.212     foxr     7308:     die "fork: $!" unless defined ($pid = fork);
1.178     foxr     7309: 
1.212     foxr     7310:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   7311: 	                               # connection liveness.
1.178     foxr     7312: 
1.212     foxr     7313:     #
                   7314:     #  Figure out who we're talking to so we can record the peer in 
                   7315:     #  the pid hash.
                   7316:     #
                   7317:     my $caller = getpeername($client);
                   7318:     my ($port,$iaddr);
                   7319:     if (defined($caller) && length($caller) > 0) {
                   7320: 	($port,$iaddr)=unpack_sockaddr_in($caller);
                   7321:     } else {
                   7322: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
                   7323:     }
                   7324:     if (defined($iaddr)) {
                   7325: 	$clientip  = inet_ntoa($iaddr);
                   7326: 	Debug("Connected with $clientip");
                   7327:     } else {
                   7328: 	&logthis("Unable to determine clientip");
                   7329: 	$clientip='Unavailable';
                   7330:     }
                   7331:     
                   7332:     if ($pid) {
                   7333:         # Parent records the child's birth and returns.
                   7334:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7335:             or die "Can't unblock SIGINT for fork: $!\n";
                   7336:         $children{$pid} = $clientip;
                   7337:         &status('Started child '.$pid);
1.462     foxr     7338: 	close($client);
1.212     foxr     7339:         return;
                   7340:     } else {
                   7341:         # Child can *not* return from this subroutine.
                   7342:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                   7343:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   7344:                                 #don't get intercepted
                   7345:         $SIG{USR1}= \&logstatus;
                   7346:         $SIG{ALRM}= \&timeout;
1.468     foxr     7347: 	#
                   7348: 	# Block sigpipe as it gets thrownon socket disconnect and we want to 
                   7349: 	# deal with that as a read faiure instead.
                   7350: 	#
                   7351: 	my $blockset = POSIX::SigSet->new(SIGPIPE);
                   7352: 	sigprocmask(SIG_BLOCK, $blockset);
                   7353: 
1.212     foxr     7354:         $lastlog='Forked ';
                   7355:         $status='Forked';
1.178     foxr     7356: 
1.212     foxr     7357:         # unblock signals
                   7358:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7359:             or die "Can't unblock SIGINT for fork: $!\n";
1.178     foxr     7360: 
1.212     foxr     7361: #        my $tmpsnum=0;            # Now global
                   7362: #---------------------------------------------------- kerberos 5 initialization
                   7363:         &Authen::Krb5::init_context();
1.511     raeburn  7364: 
                   7365:         my $no_ets;
1.514     raeburn  7366:         if ($dist =~ /^(?:centos|rhes|scientific)(\d+)$/) {
1.511     raeburn  7367:             if ($1 >= 7) {
                   7368:                 $no_ets = 1;
                   7369:             }
                   7370:         } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
                   7371:             if (($1 eq '9.3') || ($1 >= 12.2)) {
                   7372:                 $no_ets = 1; 
                   7373:             }
1.514     raeburn  7374:         } elsif ($dist =~ /^sles(\d+)$/) {
                   7375:             if ($1 > 11) {
                   7376:                 $no_ets = 1;
                   7377:             }
1.511     raeburn  7378:         } elsif ($dist =~ /^fedora(\d+)$/) {
                   7379:             if ($1 < 7) {
                   7380:                 $no_ets = 1;
                   7381:             }
                   7382:         }
                   7383:         unless ($no_ets) {
1.286     albertel 7384: 	    &Authen::Krb5::init_ets();
                   7385: 	}
1.209     albertel 7386: 
1.212     foxr     7387: 	&status('Accepted connection');
                   7388: # =============================================================================
                   7389:             # do something with the connection
                   7390: # -----------------------------------------------------------------------------
                   7391: 	# see if we know client and 'check' for spoof IP by ineffective challenge
1.178     foxr     7392: 
1.278     albertel 7393: 	my $outsideip=$clientip;
                   7394: 	if ($clientip eq '127.0.0.1') {
1.368     albertel 7395: 	    $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
1.278     albertel 7396: 	}
1.412     foxr     7397: 	&ReadManagerTable();
1.368     albertel 7398: 	my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
1.278     albertel 7399: 	my $ismanager=($managers{$outsideip}    ne undef);
1.432     raeburn  7400: 	$clientname  = "[unknown]";
1.212     foxr     7401: 	if($clientrec) {	# Establish client type.
                   7402: 	    $ConnectionType = "client";
1.368     albertel 7403: 	    $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
1.212     foxr     7404: 	    if($ismanager) {
                   7405: 		$ConnectionType = "both";
                   7406: 	    }
                   7407: 	} else {
                   7408: 	    $ConnectionType = "manager";
1.278     albertel 7409: 	    $clientname = $managers{$outsideip};
1.212     foxr     7410: 	}
1.532     raeburn  7411: 	my ($clientok,$clientinfoset);
1.178     foxr     7412: 
1.212     foxr     7413: 	if ($clientrec || $ismanager) {
                   7414: 	    &status("Waiting for init from $clientip $clientname");
                   7415: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   7416: 		     $clientip.
                   7417: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   7418: 	    &status("Connecting $clientip  ($clientname))"); 
                   7419: 	    my $remotereq=<$client>;
                   7420: 	    chomp($remotereq);
                   7421: 	    Debug("Got init: $remotereq");
1.337     albertel 7422: 
1.212     foxr     7423: 	    if ($remotereq =~ /^init/) {
                   7424: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   7425: 		#
                   7426: 		#  If the remote is attempting a local init... give that a try:
                   7427: 		#
1.432     raeburn  7428: 		(my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
1.492     droeschl 7429:         # For LON-CAPA 2.9, the  client session will have sent its LON-CAPA
                   7430:         # version when initiating the connection. For LON-CAPA 2.8 and older,
                   7431:         # the version is retrieved from the global %loncaparevs in lonnet.pm.            
1.494     droeschl 7432:         # $clientversion contains path to keyfile if $inittype eq 'local'
                   7433:         # it's overridden below in this case
1.492     droeschl 7434:         $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
1.209     albertel 7435: 
1.212     foxr     7436: 		# If the connection type is ssl, but I didn't get my
                   7437: 		# certificate files yet, then I'll drop  back to 
                   7438: 		# insecure (if allowed).
1.532     raeburn  7439: 
                   7440:                 if ($inittype eq "ssl") {
                   7441:                     my $context;
                   7442:                     if ($clientsamedom) {
                   7443:                         $context = 'dom';
                   7444:                         if ($secureconf{'connfrom'}{'dom'} eq 'no') {
                   7445:                             $inittype = "";
                   7446:                         }
                   7447:                     } elsif ($clientsameinst) {
                   7448:                         $context = 'intdom';
                   7449:                         if ($secureconf{'connfrom'}{'intdom'} eq 'no') {
                   7450:                             $inittype = "";
                   7451:                         }
                   7452:                     } else {
                   7453:                         $context = 'other';
                   7454:                         if ($secureconf{'connfrom'}{'other'} eq 'no') {
                   7455:                             $inittype = "";
                   7456:                         }
                   7457:                     }
                   7458:                     if ($inittype eq '') {
                   7459:                         &logthis("<font color=\"blue\"> Domain config set "
                   7460:                                 ."to no ssl for $clientname (context: $context)"
                   7461:                                 ." -- trying insecure auth</font>");
                   7462:                     }
                   7463:                 }
                   7464: 
1.212     foxr     7465: 		if($inittype eq "ssl") {
                   7466: 		    my ($ca, $cert) = lonssl::CertificateFile;
                   7467: 		    my $kfile       = lonssl::KeyFile;
                   7468: 		    if((!$ca)   || 
                   7469: 		       (!$cert) || 
                   7470: 		       (!$kfile)) {
                   7471: 			$inittype = ""; # This forces insecure attempt.
                   7472: 			&logthis("<font color=\"blue\"> Certificates not "
                   7473: 				 ."installed -- trying insecure auth</font>");
1.224     foxr     7474: 		    } else {	# SSL certificates are in place so
1.212     foxr     7475: 		    }		# Leave the inittype alone.
                   7476: 		}
                   7477: 
                   7478: 		if($inittype eq "local") {
1.432     raeburn  7479:                     $clientversion = $perlvar{'lonVersion'};
1.212     foxr     7480: 		    my $key = LocalConnection($client, $remotereq);
                   7481: 		    if($key) {
                   7482: 			Debug("Got local key $key");
                   7483: 			$clientok     = 1;
                   7484: 			my $cipherkey = pack("H32", $key);
                   7485: 			$cipher       = new IDEA($cipherkey);
                   7486: 			print $client "ok:local\n";
1.442     www      7487: 			&logthis('<font color="green">'
1.212     foxr     7488: 				 . "Successful local authentication </font>");
                   7489: 			$keymode = "local"
1.178     foxr     7490: 		    } else {
1.212     foxr     7491: 			Debug("Failed to get local key");
                   7492: 			$clientok = 0;
                   7493: 			shutdown($client, 3);
                   7494: 			close $client;
1.178     foxr     7495: 		    }
1.212     foxr     7496: 		} elsif ($inittype eq "ssl") {
1.532     raeburn  7497: 		    my $key = SSLConnection($client,$clientname);
1.212     foxr     7498: 		    if ($key) {
                   7499: 			$clientok = 1;
                   7500: 			my $cipherkey = pack("H32", $key);
                   7501: 			$cipher       = new IDEA($cipherkey);
                   7502: 			&logthis('<font color="green">'
                   7503: 				 ."Successfull ssl authentication with $clientname </font>");
                   7504: 			$keymode = "ssl";
                   7505: 	     
1.178     foxr     7506: 		    } else {
1.212     foxr     7507: 			$clientok = 0;
                   7508: 			close $client;
1.178     foxr     7509: 		    }
1.212     foxr     7510: 	   
                   7511: 		} else {
1.532     raeburn  7512:                     $clientinfoset = &set_client_info();
1.212     foxr     7513: 		    my $ok = InsecureConnection($client);
                   7514: 		    if($ok) {
                   7515: 			$clientok = 1;
                   7516: 			&logthis('<font color="green">'
                   7517: 				 ."Successful insecure authentication with $clientname </font>");
                   7518: 			print $client "ok\n";
                   7519: 			$keymode = "insecure";
1.178     foxr     7520: 		    } else {
1.212     foxr     7521: 			&logthis('<font color="yellow">'
                   7522: 				  ."Attempted insecure connection disallowed </font>");
                   7523: 			close $client;
                   7524: 			$clientok = 0;
1.178     foxr     7525: 		    }
                   7526: 		}
1.212     foxr     7527: 	    } else {
                   7528: 		&logthis(
                   7529: 			 "<font color='blue'>WARNING: "
                   7530: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   7531: 		&status('No init '.$clientip);
                   7532: 	    }
                   7533: 	} else {
                   7534: 	    &logthis(
                   7535: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
                   7536: 	    &status('Hung up on '.$clientip);
                   7537: 	}
                   7538:  
                   7539: 	if ($clientok) {
                   7540: # ---------------- New known client connecting, could mean machine online again
1.368     albertel 7541: 	    if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip 
1.367     albertel 7542: 		&& $clientip ne '127.0.0.1') {
1.375     albertel 7543: 		&Apache::lonnet::reconlonc($clientname);
1.212     foxr     7544: 	    }
                   7545: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
                   7546: 	    &status('Will listen to '.$clientname);
                   7547: # ------------------------------------------------------------ Process requests
                   7548: 	    my $keep_going = 1;
                   7549: 	    my $user_input;
1.532     raeburn  7550:             unless ($clientinfoset) {
                   7551:                 $clientinfoset = &set_client_info();
1.525     raeburn  7552:             }
                   7553:             $clientremoteok = 0;
                   7554:             unless ($clientsameinst) {
                   7555:                 $clientremoteok = 1;
                   7556:                 my $defdom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   7557:                 %clientprohibited = &get_prohibited($defdom);
                   7558:                 if ($clientintdom) {
                   7559:                     my $remsessconf = &get_usersession_config($defdom,'remotesession');
                   7560:                     if (ref($remsessconf) eq 'HASH') {
                   7561:                         if (ref($remsessconf->{'remote'}) eq 'HASH') {
                   7562:                             if (ref($remsessconf->{'remote'}->{'excludedomain'}) eq 'ARRAY') {
                   7563:                                 if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'excludedomain'}})) {
                   7564:                                     $clientremoteok = 0;
                   7565:                                 }
                   7566:                             }
                   7567:                             if (ref($remsessconf->{'remote'}->{'includedomain'}) eq 'ARRAY') {
                   7568:                                 if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'includedomain'}})) {
                   7569:                                     $clientremoteok = 1;
                   7570:                                 } else {
                   7571:                                     $clientremoteok = 0;
                   7572:                                 }
                   7573:                             }
                   7574:                         }
                   7575:                     }
                   7576:                 }
                   7577:             }
1.212     foxr     7578: 	    while(($user_input = get_request) && $keep_going) {
                   7579: 		alarm(120);
                   7580: 		Debug("Main: Got $user_input\n");
                   7581: 		$keep_going = &process_request($user_input);
1.178     foxr     7582: 		alarm(0);
1.212     foxr     7583: 		&status('Listening to '.$clientname." ($keymode)");	   
1.161     foxr     7584: 	    }
1.212     foxr     7585: 
1.59      www      7586: # --------------------------------------------- client unknown or fishy, refuse
1.212     foxr     7587: 	}  else {
1.161     foxr     7588: 	    print $client "refused\n";
                   7589: 	    $client->close();
1.190     albertel 7590: 	    &logthis("<font color='blue'>WARNING: "
1.161     foxr     7591: 		     ."Rejected client $clientip, closing connection</font>");
                   7592: 	}
1.525     raeburn  7593:     }
1.161     foxr     7594:     
1.1       albertel 7595: # =============================================================================
1.161     foxr     7596:     
1.190     albertel 7597:     &logthis("<font color='red'>CRITICAL: "
1.161     foxr     7598: 	     ."Disconnect from $clientip ($clientname)</font>");    
                   7599:     
                   7600:     
                   7601:     # this exit is VERY important, otherwise the child will become
                   7602:     # a producer of more and more children, forking yourself into
                   7603:     # process death.
                   7604:     exit;
1.106     foxr     7605:     
1.78      foxr     7606: }
1.532     raeburn  7607: 
                   7608: #
                   7609: #  Used to determine if a particular client is from the same domain
                   7610: #  as the current server, or from the same internet domain.
                   7611: #
                   7612: #  Optional input -- the client to check for domain and internet domain.
                   7613: #  If not specified, defaults to the package variable: $clientname
                   7614: #
                   7615: #  If called in array context will not set package variables, but will
                   7616: #  instead return an array of two values - (a) true if client is in the
                   7617: #  same domain as the server, and (b) true if client is in the same internet
                   7618: #  domain.
                   7619: #
                   7620: #  If called in scalar context, sets package variables for current client:
                   7621: #
                   7622: #  $clienthomedom  - LonCAPA domain of homeID for client.
                   7623: #  $clientsamedom  - LonCAPA domain same for this host and client.
                   7624: #  $clientintdom   - LonCAPA "internet domain" for client.
                   7625: #  $clientsameinst - LonCAPA "internet domain" same for this host & client.
                   7626: #
                   7627: #  returns 1 to indicate package variables have been set for current client.
                   7628: #
                   7629: 
                   7630: sub set_client_info {
                   7631:     my ($lonhost) = @_;
                   7632:     $lonhost ||= $clientname;
                   7633:     my $clienthost = &Apache::lonnet::hostname($lonhost);
                   7634:     my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
                   7635:     my $homedom = &Apache::lonnet::host_domain($clientserverhomeID);
                   7636:     my $samedom = 0;
                   7637:     if ($perlvar{'lonDefDom'} eq $homedom) {
                   7638:         $samedom = 1;
                   7639:     }
                   7640:     my $intdom = &Apache::lonnet::internet_dom($clientserverhomeID);
                   7641:     my $sameinst = 0;
                   7642:     if ($intdom ne '') {
                   7643:         my $internet_names = &Apache::lonnet::get_internet_names($currenthostid);
                   7644:         if (ref($internet_names) eq 'ARRAY') {
                   7645:             if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   7646:                 $sameinst = 1;
                   7647:             }
                   7648:         }
                   7649:     }
                   7650:     if (wantarray) {
                   7651:         return ($samedom,$sameinst);
                   7652:     } else {
                   7653:         $clienthomedom = $homedom;
                   7654:         $clientsamedom = $samedom;
                   7655:         $clientintdom = $intdom;
                   7656:         $clientsameinst = $sameinst;
                   7657:         return 1;
                   7658:     }
                   7659: }
                   7660: 
1.261     foxr     7661: #
                   7662: #   Determine if a user is an author for the indicated domain.
                   7663: #
                   7664: # Parameters:
                   7665: #    domain          - domain to check in .
                   7666: #    user            - Name of user to check.
                   7667: #
                   7668: # Return:
                   7669: #     1             - User is an author for domain.
                   7670: #     0             - User is not an author for domain.
                   7671: sub is_author {
                   7672:     my ($domain, $user) = @_;
                   7673: 
                   7674:     &Debug("is_author: $user @ $domain");
                   7675: 
                   7676:     my $hashref = &tie_user_hash($domain, $user, "roles",
                   7677: 				 &GDBM_READER());
                   7678: 
                   7679:     #  Author role should show up as a key /domain/_au
1.78      foxr     7680: 
1.321     albertel 7681:     my $value;
1.487     foxr     7682:     if ($hashref) {
1.78      foxr     7683: 
1.487     foxr     7684: 	my $key    = "/$domain/_au";
                   7685: 	if (defined($hashref)) {
                   7686: 	    $value = $hashref->{$key};
                   7687: 	    if(!untie_user_hash($hashref)) {
                   7688: 		return 'error: ' .  ($!+0)." untie (GDBM) Failed";
                   7689: 	    }
                   7690: 	}
                   7691: 	
                   7692: 	if(defined($value)) {
                   7693: 	    &Debug("$user @ $domain is an author");
                   7694: 	}
                   7695:     } else {
                   7696: 	return 'error: '.($!+0)." tie (GDBM) Failed";
1.261     foxr     7697:     }
                   7698: 
                   7699:     return defined($value);
                   7700: }
1.78      foxr     7701: #
                   7702: #   Checks to see if the input roleput request was to set
1.482     www      7703: # an author role.  If so, creates construction space 
1.78      foxr     7704: # Parameters:
                   7705: #    request   - The request sent to the rolesput subchunk.
                   7706: #                We're looking for  /domain/_au
                   7707: #    domain    - The domain in which the user is having roles doctored.
                   7708: #    user      - Name of the user for which the role is being put.
                   7709: #    authtype  - The authentication type associated with the user.
                   7710: #
1.289     albertel 7711: sub manage_permissions {
1.192     foxr     7712:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     7713:     # See if the request is of the form /$domain/_au
1.289     albertel 7714:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.484     raeburn  7715:         my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
1.482     www      7716:         unless (-e $path) {        
                   7717:            mkdir($path);
                   7718:         }
                   7719:         unless (-e $path.'/'.$user) {
                   7720:            mkdir($path.'/'.$user);
                   7721:         }
1.78      foxr     7722:     }
                   7723: }
1.222     foxr     7724: 
                   7725: 
                   7726: #
                   7727: #  Return the full path of a user password file, whether it exists or not.
                   7728: # Parameters:
                   7729: #   domain     - Domain in which the password file lives.
                   7730: #   user       - name of the user.
                   7731: # Returns:
                   7732: #    Full passwd path:
                   7733: #
                   7734: sub password_path {
                   7735:     my ($domain, $user) = @_;
1.264     albertel 7736:     return &propath($domain, $user).'/passwd';
1.222     foxr     7737: }
                   7738: 
                   7739: #   Password Filename
                   7740: #   Returns the path to a passwd file given domain and user... only if
                   7741: #  it exists.
                   7742: # Parameters:
                   7743: #   domain    - Domain in which to search.
                   7744: #   user      - username.
                   7745: # Returns:
                   7746: #   - If the password file exists returns its path.
                   7747: #   - If the password file does not exist, returns undefined.
                   7748: #
                   7749: sub password_filename {
                   7750:     my ($domain, $user) = @_;
                   7751: 
                   7752:     Debug ("PasswordFilename called: dom = $domain user = $user");
                   7753: 
                   7754:     my $path  = &password_path($domain, $user);
                   7755:     Debug("PasswordFilename got path: $path");
                   7756:     if(-e $path) {
                   7757: 	return $path;
                   7758:     } else {
                   7759: 	return undef;
                   7760:     }
                   7761: }
                   7762: 
                   7763: #
                   7764: #   Rewrite the contents of the user's passwd file.
                   7765: #  Parameters:
                   7766: #    domain    - domain of the user.
                   7767: #    name      - User's name.
                   7768: #    contents  - New contents of the file.
1.533     raeburn  7769: #    saveold   - (optional). If true save old file in a passwd.bak file.
1.222     foxr     7770: # Returns:
                   7771: #   0    - Failed.
                   7772: #   1    - Success.
                   7773: #
                   7774: sub rewrite_password_file {
1.533     raeburn  7775:     my ($domain, $user, $contents, $saveold) = @_;
1.222     foxr     7776: 
                   7777:     my $file = &password_filename($domain, $user);
                   7778:     if (defined $file) {
1.533     raeburn  7779:         if ($saveold) {
                   7780:             my $bakfile = $file.'.bak';
                   7781:             if (CopyFile($file,$bakfile)) {
                   7782:                 chmod(0400,$bakfile);
                   7783:                 &logthis("Old password saved in passwd.bak for internally authenticated user: $user:$domain");
                   7784:             } else {
                   7785:                 &logthis("Failed to save old password in passwd.bak for internally authenticated user: $user:$domain");
                   7786:             }
                   7787:         }
1.222     foxr     7788: 	my $pf = IO::File->new(">$file");
                   7789: 	if($pf) {
                   7790: 	    print $pf "$contents\n";
                   7791: 	    return 1;
                   7792: 	} else {
                   7793: 	    return 0;
                   7794: 	}
                   7795:     } else {
                   7796: 	return 0;
                   7797:     }
                   7798: 
                   7799: }
                   7800: 
1.78      foxr     7801: #
1.222     foxr     7802: #   get_auth_type - Determines the authorization type of a user in a domain.
1.78      foxr     7803: 
                   7804: #     Returns the authorization type or nouser if there is no such user.
                   7805: #
1.436     raeburn  7806: sub get_auth_type {
1.192     foxr     7807:     my ($domain, $user)  = @_;
1.78      foxr     7808: 
1.222     foxr     7809:     Debug("get_auth_type( $domain, $user ) \n");
1.78      foxr     7810:     my $proname    = &propath($domain, $user); 
                   7811:     my $passwdfile = "$proname/passwd";
                   7812:     if( -e $passwdfile ) {
                   7813: 	my $pf = IO::File->new($passwdfile);
                   7814: 	my $realpassword = <$pf>;
                   7815: 	chomp($realpassword);
1.79      foxr     7816: 	Debug("Password info = $realpassword\n");
1.78      foxr     7817: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     7818: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.259     raeburn  7819: 	return "$authtype:$contentpwd";     
1.224     foxr     7820:     } else {
1.79      foxr     7821: 	Debug("Returning nouser");
1.78      foxr     7822: 	return "nouser";
                   7823:     }
1.1       albertel 7824: }
                   7825: 
1.220     foxr     7826: #
                   7827: #  Validate a user given their domain, name and password.  This utility
                   7828: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
                   7829: #  to validate the login credentials of a user.
                   7830: # Parameters:
                   7831: #    $domain    - The domain being logged into (this is required due to
                   7832: #                 the capability for multihomed systems.
                   7833: #    $user      - The name of the user being validated.
                   7834: #    $password  - The user's propoposed password.
                   7835: #
                   7836: # Returns:
                   7837: #     1        - The domain,user,pasword triplet corresponds to a valid
                   7838: #                user.
                   7839: #     0        - The domain,user,password triplet is not a valid user.
                   7840: #
                   7841: sub validate_user {
1.396     raeburn  7842:     my ($domain, $user, $password, $checkdefauth) = @_;
1.220     foxr     7843: 
                   7844:     # Why negative ~pi you may well ask?  Well this function is about
                   7845:     # authentication, and therefore very important to get right.
                   7846:     # I've initialized the flag that determines whether or not I've 
                   7847:     # validated correctly to a value it's not supposed to get.
                   7848:     # At the end of this function. I'll ensure that it's not still that
                   7849:     # value so we don't just wind up returning some accidental value
                   7850:     # as a result of executing an unforseen code path that
1.249     foxr     7851:     # did not set $validated.  At the end of valid execution paths,
                   7852:     # validated shoule be 1 for success or 0 for failuer.
1.220     foxr     7853: 
                   7854:     my $validated = -3.14159;
                   7855: 
                   7856:     #  How we authenticate is determined by the type of authentication
                   7857:     #  the user has been assigned.  If the authentication type is
                   7858:     #  "nouser", the user does not exist so we will return 0.
                   7859: 
1.222     foxr     7860:     my $contents = &get_auth_type($domain, $user);
1.220     foxr     7861:     my ($howpwd, $contentpwd) = split(/:/, $contents);
                   7862: 
                   7863:     my $null = pack("C",0);	# Used by kerberos auth types.
                   7864: 
1.395     raeburn  7865:     if ($howpwd eq 'nouser') {
1.396     raeburn  7866:         if ($checkdefauth) {
                   7867:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   7868:             if ($domdefaults{'auth_def'} eq 'localauth') {
                   7869:                 $howpwd = $domdefaults{'auth_def'};
                   7870:                 $contentpwd = $domdefaults{'auth_arg_def'};
                   7871:             } elsif ((($domdefaults{'auth_def'} eq 'krb4') || 
                   7872:                       ($domdefaults{'auth_def'} eq 'krb5')) &&
                   7873:                      ($domdefaults{'auth_arg_def'} ne '')) {
                   7874:                 $howpwd = $domdefaults{'auth_def'};
                   7875:                 $contentpwd = $domdefaults{'auth_arg_def'}; 
                   7876:             }
1.395     raeburn  7877:         }
1.533     raeburn  7878:     }
1.220     foxr     7879:     if ($howpwd ne 'nouser') {
                   7880: 	if($howpwd eq "internal") { # Encrypted is in local password file.
1.518     raeburn  7881:             if (length($contentpwd) == 13) {
                   7882:                 $validated = (crypt($password,$contentpwd) eq $contentpwd);
                   7883:                 if ($validated) {
1.533     raeburn  7884:                     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   7885:                     if ($domdefaults{'intauth_switch'}) {
                   7886:                         my $ncpass = &hash_passwd($domain,$password);
                   7887:                         my $saveold;
                   7888:                         if ($domdefaults{'intauth_switch'} == 2) {
                   7889:                             $saveold = 1;
                   7890:                         }
                   7891:                         if (&rewrite_password_file($domain,$user,"$howpwd:$ncpass",$saveold)) {
                   7892:                             &update_passwd_history($user,$domain,$howpwd,'conversion');
                   7893:                             &logthis("Validated password hashed with bcrypt for $user:$domain");
                   7894:                         }
1.518     raeburn  7895:                     }
                   7896:                 }
                   7897:             } else {
1.533     raeburn  7898:                 $validated = &check_internal_passwd($password,$contentpwd,$domain,$user);
1.518     raeburn  7899:             }
1.220     foxr     7900: 	}
                   7901: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
                   7902: 	    $contentpwd = (getpwnam($user))[1];
                   7903: 	    if($contentpwd) {
                   7904: 		if($contentpwd eq 'x') { # Shadow password file...
                   7905: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
                   7906: 		    open PWAUTH,  "|$pwauth_path" or
                   7907: 			die "Cannot invoke authentication";
                   7908: 		    print PWAUTH "$user\n$password\n";
                   7909: 		    close PWAUTH;
                   7910: 		    $validated = ! $?;
                   7911: 
                   7912: 		} else { 	         # Passwords in /etc/passwd. 
                   7913: 		    $validated = (crypt($password,
                   7914: 					$contentpwd) eq $contentpwd);
                   7915: 		}
                   7916: 	    } else {
                   7917: 		$validated = 0;
                   7918: 	    }
1.439     raeburn  7919: 	} elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
                   7920:             my $checkwithkrb5 = 0;
                   7921:             if ($dist =~/^fedora(\d+)$/) {
                   7922:                 if ($1 > 11) {
                   7923:                     $checkwithkrb5 = 1;
                   7924:                 }
                   7925:             } elsif ($dist =~ /^suse([\d.]+)$/) {
                   7926:                 if ($1 > 11.1) {
                   7927:                     $checkwithkrb5 = 1; 
                   7928:                 }
                   7929:             }
                   7930:             if ($checkwithkrb5) {
                   7931:                 $validated = &krb5_authen($password,$null,$user,$contentpwd);
                   7932:             } else {
                   7933:                 $validated = &krb4_authen($password,$null,$user,$contentpwd);
                   7934:             }
1.224     foxr     7935: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.439     raeburn  7936:             $validated = &krb5_authen($password,$null,$user,$contentpwd);
1.224     foxr     7937: 	} elsif ($howpwd eq "localauth") { 
1.220     foxr     7938: 	    #  Authenticate via installation specific authentcation method:
                   7939: 	    $validated = &localauth::localauth($user, 
                   7940: 					       $password, 
1.353     albertel 7941: 					       $contentpwd,
                   7942: 					       $domain);
1.358     albertel 7943: 	    if ($validated < 0) {
1.357     albertel 7944: 		&logthis("localauth for $contentpwd $user:$domain returned a $validated");
                   7945: 		$validated = 0;
                   7946: 	    }
1.224     foxr     7947: 	} else {			# Unrecognized auth is also bad.
1.220     foxr     7948: 	    $validated = 0;
                   7949: 	}
                   7950:     } else {
                   7951: 	$validated = 0;
                   7952:     }
                   7953:     #
                   7954:     #  $validated has the correct stat of the authentication:
                   7955:     #
                   7956: 
                   7957:     unless ($validated != -3.14159) {
1.249     foxr     7958: 	#  I >really really< want to know if this happens.
                   7959: 	#  since it indicates that user authentication is badly
                   7960: 	#  broken in some code path.
                   7961:         #
                   7962: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220     foxr     7963:     }
                   7964:     return $validated;
                   7965: }
                   7966: 
1.518     raeburn  7967: sub check_internal_passwd {
1.533     raeburn  7968:     my ($plainpass,$stored,$domain,$user) = @_;
1.518     raeburn  7969:     my (undef,$method,@rest) = split(/!/,$stored);
1.533     raeburn  7970:     if ($method eq 'bcrypt') {
1.518     raeburn  7971:         my $result = &hash_passwd($domain,$plainpass,@rest);
                   7972:         if ($result ne $stored) {
                   7973:             return 0;
                   7974:         }
1.533     raeburn  7975:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   7976:         if ($domdefaults{'intauth_check'}) {
                   7977:             # Upgrade to a larger number of rounds if necessary
                   7978:             my $defaultcost = $domdefaults{'intauth_cost'};
                   7979:             if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   7980:                 $defaultcost = 10;
                   7981:             }
                   7982:             if (int($rest[0])<int($defaultcost)) {
                   7983:                 if ($domdefaults{'intauth_check'} == 1) { 
                   7984:                     my $ncpass = &hash_passwd($domain,$plainpass);
                   7985:                     if (&rewrite_password_file($domain,$user,"internal:$ncpass")) {
                   7986:                         &update_passwd_history($user,$domain,'internal','update cost');
                   7987:                         &logthis("Validated password hashed with bcrypt for $user:$domain");
                   7988:                     }
                   7989:                     return 1;
                   7990:                 } elsif ($domdefaults{'intauth_check'} == 2) {
                   7991:                     return 0;
                   7992:                 }
                   7993:             }
                   7994:         } else {
                   7995:             return 1;
1.518     raeburn  7996:         }
                   7997:     }
                   7998:     return 0;
                   7999: }
                   8000: 
                   8001: sub get_last_authchg {
                   8002:     my ($domain,$user) = @_;
                   8003:     my $lastmod;
                   8004:     my $logname = &propath($domain,$user).'/passwd.log';
                   8005:     if (-e "$logname") {
                   8006:         $lastmod = (stat("$logname"))[9];
                   8007:     }
                   8008:     return $lastmod;
                   8009: }
                   8010: 
1.439     raeburn  8011: sub krb4_authen {
                   8012:     my ($password,$null,$user,$contentpwd) = @_;
                   8013:     my $validated = 0;
                   8014:     if (!($password =~ /$null/) ) {  # Null password not allowed.
                   8015:         eval {
                   8016:             require Authen::Krb4;
                   8017:         };
                   8018:         if (!$@) {
                   8019:             my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
                   8020:                                                        "",
                   8021:                                                        $contentpwd,,
                   8022:                                                        'krbtgt',
                   8023:                                                        $contentpwd,
                   8024:                                                        1,
                   8025:                                                        $password);
                   8026:             if(!$k4error) {
                   8027:                 $validated = 1;
                   8028:             } else {
                   8029:                 $validated = 0;
                   8030:                 &logthis('krb4: '.$user.', '.$contentpwd.', '.
                   8031:                           &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   8032:             }
                   8033:         } else {
                   8034:             $validated = krb5_authen($password,$null,$user,$contentpwd);
                   8035:         }
                   8036:     }
                   8037:     return $validated;
                   8038: }
                   8039: 
                   8040: sub krb5_authen {
                   8041:     my ($password,$null,$user,$contentpwd) = @_;
                   8042:     my $validated = 0;
                   8043:     if(!($password =~ /$null/)) { # Null password not allowed.
                   8044:         my $krbclient = &Authen::Krb5::parse_name($user.'@'
                   8045:                                                   .$contentpwd);
                   8046:         my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
                   8047:         my $krbserver  = &Authen::Krb5::parse_name($krbservice);
                   8048:         my $credentials= &Authen::Krb5::cc_default();
                   8049:         $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
                   8050:                                                             .$contentpwd));
                   8051:         my $krbreturn;
                   8052:         if (exists(&Authen::Krb5::get_init_creds_password)) {
                   8053:             $krbreturn =
                   8054:                 &Authen::Krb5::get_init_creds_password($krbclient,$password,
                   8055:                                                           $krbservice);
                   8056:             $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
                   8057:         } else {
                   8058:             $krbreturn  =
                   8059:                 &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
                   8060:                                                          $password,$credentials);
                   8061:             $validated = ($krbreturn == 1);
                   8062:         }
                   8063:         if (!$validated) {
                   8064:             &logthis('krb5: '.$user.', '.$contentpwd.', '.
                   8065:                      &Authen::Krb5::error());
                   8066:         }
                   8067:     }
                   8068:     return $validated;
                   8069: }
1.220     foxr     8070: 
1.84      albertel 8071: sub addline {
                   8072:     my ($fname,$hostid,$ip,$newline)=@_;
                   8073:     my $contents;
                   8074:     my $found=0;
1.355     albertel 8075:     my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
1.134     albertel 8076:     my $sh;
1.84      albertel 8077:     if ($sh=IO::File->new("$fname.subscription")) {
                   8078: 	while (my $subline=<$sh>) {
                   8079: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   8080: 	}
                   8081: 	$sh->close();
                   8082:     }
                   8083:     $sh=IO::File->new(">$fname.subscription");
                   8084:     if ($contents) { print $sh $contents; }
                   8085:     if ($newline) { print $sh $newline; }
                   8086:     $sh->close();
                   8087:     return $found;
1.86      www      8088: }
                   8089: 
1.234     foxr     8090: sub get_chat {
1.324     raeburn  8091:     my ($cdom,$cname,$udom,$uname,$group)=@_;
1.310     albertel 8092: 
1.87      www      8093:     my @entries=();
1.324     raeburn  8094:     my $namespace = 'nohist_chatroom';
                   8095:     my $namespace_inroom = 'nohist_inchatroom';
1.335     albertel 8096:     if ($group ne '') {
1.324     raeburn  8097:         $namespace .= '_'.$group;
                   8098:         $namespace_inroom .= '_'.$group;
                   8099:     }
                   8100:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8101: 				 &GDBM_READER());
                   8102:     if ($hashref) {
                   8103: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.311     albertel 8104: 	&untie_user_hash($hashref);
1.123     www      8105:     }
1.124     www      8106:     my @participants=();
1.134     albertel 8107:     my $cutoff=time-60;
1.324     raeburn  8108:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
1.310     albertel 8109: 			      &GDBM_WRCREAT());
                   8110:     if ($hashref) {
                   8111:         $hashref->{$uname.':'.$udom}=time;
                   8112:         foreach my $user (sort(keys(%$hashref))) {
                   8113: 	    if ($hashref->{$user}>$cutoff) {
                   8114: 		push(@participants, 'active_participant:'.$user);
1.123     www      8115:             }
                   8116:         }
1.311     albertel 8117:         &untie_user_hash($hashref);
1.86      www      8118:     }
1.124     www      8119:     return (@participants,@entries);
1.86      www      8120: }
                   8121: 
1.234     foxr     8122: sub chat_add {
1.324     raeburn  8123:     my ($cdom,$cname,$newchat,$group)=@_;
1.88      albertel 8124:     my @entries=();
1.142     www      8125:     my $time=time;
1.324     raeburn  8126:     my $namespace = 'nohist_chatroom';
                   8127:     my $logfile = 'chatroom.log';
1.335     albertel 8128:     if ($group ne '') {
1.324     raeburn  8129:         $namespace .= '_'.$group;
                   8130:         $logfile = 'chatroom_'.$group.'.log';
                   8131:     }
                   8132:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8133: 				 &GDBM_WRCREAT());
                   8134:     if ($hashref) {
                   8135: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.88      albertel 8136: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   8137: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   8138: 	my $newid=$time.'_000000';
                   8139: 	if ($thentime==$time) {
                   8140: 	    $idnum=~s/^0+//;
                   8141: 	    $idnum++;
                   8142: 	    $idnum=substr('000000'.$idnum,-6,6);
                   8143: 	    $newid=$time.'_'.$idnum;
                   8144: 	}
1.310     albertel 8145: 	$hashref->{$newid}=$newchat;
1.88      albertel 8146: 	my $expired=$time-3600;
1.310     albertel 8147: 	foreach my $comment (keys(%$hashref)) {
                   8148: 	    my ($thistime) = ($comment=~/(\d+)\_/);
1.88      albertel 8149: 	    if ($thistime<$expired) {
1.310     albertel 8150: 		delete $hashref->{$comment};
1.88      albertel 8151: 	    }
                   8152: 	}
1.310     albertel 8153: 	{
                   8154: 	    my $proname=&propath($cdom,$cname);
1.324     raeburn  8155: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
1.310     albertel 8156: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
                   8157: 	    }
                   8158: 	    close(CHATLOG);
1.142     www      8159: 	}
1.311     albertel 8160: 	&untie_user_hash($hashref);
1.86      www      8161:     }
1.84      albertel 8162: }
                   8163: 
                   8164: sub unsub {
                   8165:     my ($fname,$clientip)=@_;
                   8166:     my $result;
1.188     foxr     8167:     my $unsubs = 0;		# Number of successful unsubscribes:
                   8168: 
                   8169: 
                   8170:     # An old way subscriptions were handled was to have a 
                   8171:     # subscription marker file:
                   8172: 
                   8173:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     8174:     if (unlink("$fname.$clientname")) {
1.188     foxr     8175: 	$unsubs++;		# Successful unsub via marker file.
                   8176:     } 
                   8177: 
                   8178:     # The more modern way to do it is to have a subscription list
                   8179:     # file:
                   8180: 
1.84      albertel 8181:     if (-e "$fname.subscription") {
1.161     foxr     8182: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     8183: 	if ($found) { 
                   8184: 	    $unsubs++;
                   8185: 	}
                   8186:     } 
                   8187: 
                   8188:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   8189:     #  resource we can return ok:
                   8190: 
                   8191:     if($unsubs) {
                   8192: 	$result = "ok\n";
1.84      albertel 8193:     } else {
1.188     foxr     8194: 	$result = "not_subscribed\n";
1.84      albertel 8195:     }
1.188     foxr     8196: 
1.84      albertel 8197:     return $result;
                   8198: }
                   8199: 
1.101     www      8200: sub currentversion {
                   8201:     my $fname=shift;
                   8202:     my $version=-1;
                   8203:     my $ulsdir='';
                   8204:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   8205:        $ulsdir=$1;
                   8206:     }
1.114     albertel 8207:     my ($fnamere1,$fnamere2);
                   8208:     # remove version if already specified
1.101     www      8209:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 8210:     # get the bits that go before and after the version number
                   8211:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   8212: 	$fnamere1=$1;
                   8213: 	$fnamere2='.'.$2;
                   8214:     }
1.101     www      8215:     if (-e $fname) { $version=1; }
                   8216:     if (-e $ulsdir) {
1.134     albertel 8217: 	if(-d $ulsdir) {
                   8218: 	    if (opendir(LSDIR,$ulsdir)) {
                   8219: 		my $ulsfn;
                   8220: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      8221: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 8222: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   8223: 		    unless (-l $thisfile) {
1.160     www      8224: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 8225: 			    if ($1>$version) { $version=$1; }
                   8226: 			}
                   8227: 		    }
                   8228: 		}
                   8229: 		closedir(LSDIR);
                   8230: 		$version++;
                   8231: 	    }
                   8232: 	}
                   8233:     }
                   8234:     return $version;
1.101     www      8235: }
                   8236: 
                   8237: sub thisversion {
                   8238:     my $fname=shift;
                   8239:     my $version=-1;
                   8240:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   8241: 	$version=$1;
                   8242:     }
                   8243:     return $version;
                   8244: }
                   8245: 
1.84      albertel 8246: sub subscribe {
                   8247:     my ($userinput,$clientip)=@_;
                   8248:     my $result;
1.293     albertel 8249:     my ($cmd,$fname)=split(/:/,$userinput,2);
1.84      albertel 8250:     my $ownership=&ishome($fname);
                   8251:     if ($ownership eq 'owner') {
1.101     www      8252: # explitly asking for the current version?
                   8253:         unless (-e $fname) {
                   8254:             my $currentversion=&currentversion($fname);
                   8255: 	    if (&thisversion($fname)==$currentversion) {
                   8256:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   8257: 		    my $root=$1;
                   8258:                     my $extension=$2;
                   8259:                     symlink($root.'.'.$extension,
                   8260:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      8261:                     unless ($extension=~/\.meta$/) {
                   8262:                        symlink($root.'.'.$extension.'.meta',
                   8263:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   8264: 		    }
1.101     www      8265:                 }
                   8266:             }
                   8267:         }
1.84      albertel 8268: 	if (-e $fname) {
                   8269: 	    if (-d $fname) {
                   8270: 		$result="directory\n";
                   8271: 	    } else {
1.161     foxr     8272: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 8273: 		my $now=time;
1.161     foxr     8274: 		my $found=&addline($fname,$clientname,$clientip,
                   8275: 				   "$clientname:$clientip:$now\n");
1.84      albertel 8276: 		if ($found) { $result="$fname\n"; }
                   8277: 		# if they were subscribed to only meta data, delete that
                   8278:                 # subscription, when you subscribe to a file you also get
                   8279:                 # the metadata
                   8280: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   8281: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
1.476     raeburn  8282:                 my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
                   8283:                 $protocol = 'http' if ($protocol ne 'https');
                   8284: 		$fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
1.84      albertel 8285: 		$result="$fname\n";
                   8286: 	    }
                   8287: 	} else {
                   8288: 	    $result="not_found\n";
                   8289: 	}
                   8290:     } else {
                   8291: 	$result="rejected\n";
                   8292:     }
                   8293:     return $result;
                   8294: }
1.287     foxr     8295: #  Change the passwd of a unix user.  The caller must have
                   8296: #  first verified that the user is a loncapa user.
                   8297: #
                   8298: # Parameters:
                   8299: #    user      - Unix user name to change.
                   8300: #    pass      - New password for the user.
                   8301: # Returns:
                   8302: #    ok    - if success
                   8303: #    other - Some meaningfule error message string.
                   8304: # NOTE:
                   8305: #    invokes a setuid script to change the passwd.
                   8306: sub change_unix_password {
                   8307:     my ($user, $pass) = @_;
                   8308: 
                   8309:     &Debug("change_unix_password");
                   8310:     my $execdir=$perlvar{'lonDaemons'};
                   8311:     &Debug("Opening lcpasswd pipeline");
                   8312:     my $pf = IO::File->new("|$execdir/lcpasswd > "
                   8313: 			   ."$perlvar{'lonDaemons'}"
                   8314: 			   ."/logs/lcpasswd.log");
                   8315:     print $pf "$user\n$pass\n$pass\n";
                   8316:     close $pf;
                   8317:     my $err = $?;
                   8318:     return ($err < @passwderrors) ? $passwderrors[$err] : 
                   8319: 	"pwchange_falure - unknown error";
                   8320: 
                   8321:     
                   8322: }
                   8323: 
1.91      albertel 8324: 
                   8325: sub make_passwd_file {
1.518     raeburn  8326:     my ($uname,$udom,$umode,$npass,$passfilename,$action)=@_;
1.390     raeburn  8327:     my $result="ok";
1.91      albertel 8328:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   8329: 	{
                   8330: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8331: 	    if ($pf) {
                   8332: 		print $pf "$umode:$npass\n";
1.518     raeburn  8333:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     8334: 	    } else {
                   8335: 		$result = "pass_file_failed_error";
                   8336: 	    }
1.91      albertel 8337: 	}
                   8338:     } elsif ($umode eq 'internal') {
1.518     raeburn  8339:         my $ncpass = &hash_passwd($udom,$npass);
1.91      albertel 8340: 	{
                   8341: 	    &Debug("Creating internal auth");
                   8342: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8343: 	    if($pf) {
1.518     raeburn  8344: 		print $pf "internal:$ncpass\n";
                   8345:                 &update_passwd_history($uname,$udom,$umode,$action); 
1.261     foxr     8346: 	    } else {
                   8347: 		$result = "pass_file_failed_error";
                   8348: 	    }
1.91      albertel 8349: 	}
                   8350:     } elsif ($umode eq 'localauth') {
                   8351: 	{
                   8352: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8353: 	    if($pf) {
                   8354: 		print $pf "localauth:$npass\n";
1.524     raeburn  8355:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     8356: 	    } else {
                   8357: 		$result = "pass_file_failed_error";
                   8358: 	    }
1.91      albertel 8359: 	}
                   8360:     } elsif ($umode eq 'unix') {
1.502     raeburn  8361: 	&logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
                   8362: 	$result="no_new_unix_accounts";
1.91      albertel 8363:     } elsif ($umode eq 'none') {
                   8364: 	{
1.223     foxr     8365: 	    my $pf = IO::File->new("> $passfilename");
1.261     foxr     8366: 	    if($pf) {
                   8367: 		print $pf "none:\n";
                   8368: 	    } else {
                   8369: 		$result = "pass_file_failed_error";
                   8370: 	    }
1.91      albertel 8371: 	}
1.543   ! raeburn  8372:     } elsif ($umode eq 'lti') {
        !          8373:         my $pf = IO::File->new(">$passfilename");
        !          8374:         if($pf) {
        !          8375:             print $pf "lti:\n";
        !          8376:             &update_passwd_history($uname,$udom,$umode,$action);
        !          8377:         } else {
        !          8378:             $result = "pass_file_failed_error";
        !          8379:         }
1.91      albertel 8380:     } else {
1.390     raeburn  8381: 	$result="auth_mode_error";
1.91      albertel 8382:     }
                   8383:     return $result;
1.121     albertel 8384: }
                   8385: 
1.265     albertel 8386: sub convert_photo {
                   8387:     my ($start,$dest)=@_;
                   8388:     system("convert $start $dest");
                   8389: }
                   8390: 
1.121     albertel 8391: sub sethost {
                   8392:     my ($remotereq) = @_;
                   8393:     my (undef,$hostid)=split(/:/,$remotereq);
1.322     albertel 8394:     # ignore sethost if we are already correct
                   8395:     if ($hostid eq $currenthostid) {
                   8396: 	return 'ok';
                   8397:     }
                   8398: 
1.121     albertel 8399:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
1.368     albertel 8400:     if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'}) 
                   8401: 	eq &Apache::lonnet::get_host_ip($hostid)) {
1.200     matthew  8402: 	$currenthostid  =$hostid;
1.369     albertel 8403: 	$currentdomainid=&Apache::lonnet::host_domain($hostid);
1.443     www      8404: #	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
1.121     albertel 8405:     } else {
                   8406: 	&logthis("Requested host id $hostid not an alias of ".
                   8407: 		 $perlvar{'lonHostID'}." refusing connection");
                   8408: 	return 'unable_to_set';
                   8409:     }
                   8410:     return 'ok';
                   8411: }
                   8412: 
                   8413: sub version {
                   8414:     my ($userinput)=@_;
                   8415:     $remoteVERSION=(split(/:/,$userinput))[1];
                   8416:     return "version:$VERSION";
1.127     albertel 8417: }
1.178     foxr     8418: 
1.447     raeburn  8419: sub get_usersession_config {
                   8420:     my ($dom,$name) = @_;
                   8421:     my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8422:     if (defined($cached)) {
                   8423:         return $usersessionconf;
                   8424:     } else {
                   8425:         my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
1.525     raeburn  8426:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
                   8427:         return $domconfig{'usersessions'};
1.447     raeburn  8428:     }
                   8429:     return;
                   8430: }
1.200     matthew  8431: 
1.534     raeburn  8432: sub get_usersearch_config {
                   8433:     my ($dom,$name) = @_;
                   8434:     my ($usersearchconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8435:     if (defined($cached)) {
                   8436:         return $usersearchconf;
                   8437:     } else {
                   8438:         my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$dom);
                   8439:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'directorysrch'},600);
                   8440:         return $domconfig{'directorysrch'};
                   8441:     }
                   8442:     return;
                   8443: }
                   8444: 
1.525     raeburn  8445: sub get_prohibited {
                   8446:     my ($dom) = @_;
                   8447:     my $name = 'trust';
                   8448:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8449:     unless (defined($cached)) {
                   8450:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$dom);
                   8451:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'trust'},3600);
                   8452:         $trustconfig = $domconfig{'trust'};
                   8453:     }
                   8454:     my %prohibited;
                   8455:     if (ref($trustconfig)) {
                   8456:         foreach my $prefix (keys(%{$trustconfig})) {
                   8457:             if (ref($trustconfig->{$prefix}) eq 'HASH') {
                   8458:                 my $reject;
                   8459:                 if (ref($trustconfig->{$prefix}->{'exc'}) eq 'ARRAY') {
                   8460:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'exc'}})) {
                   8461:                         $reject = 1;
                   8462:                     }
                   8463:                 }
                   8464:                 if (ref($trustconfig->{$prefix}->{'inc'}) eq 'ARRAY') {
                   8465:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'inc'}})) {
                   8466:                         $reject = 0;
                   8467:                     } else {
                   8468:                         $reject = 1;
                   8469:                     }
                   8470:                 }
                   8471:                 if ($reject) {
                   8472:                     $prohibited{$prefix} = 1;
                   8473:                 }
                   8474:             }
                   8475:         }
                   8476:     }
                   8477:     return %prohibited;
                   8478: }
1.450     raeburn  8479: 
1.471     raeburn  8480: sub distro_and_arch {
                   8481:     return $dist.':'.$arch;
                   8482: }
                   8483: 
1.61      harris41 8484: # ----------------------------------- POD (plain old documentation, CPAN style)
                   8485: 
                   8486: =head1 NAME
                   8487: 
                   8488: lond - "LON Daemon" Server (port "LOND" 5663)
                   8489: 
                   8490: =head1 SYNOPSIS
                   8491: 
1.74      harris41 8492: Usage: B<lond>
                   8493: 
                   8494: Should only be run as user=www.  This is a command-line script which
                   8495: is invoked by B<loncron>.  There is no expectation that a typical user
                   8496: will manually start B<lond> from the command-line.  (In other words,
                   8497: DO NOT START B<lond> YOURSELF.)
1.61      harris41 8498: 
                   8499: =head1 DESCRIPTION
                   8500: 
1.74      harris41 8501: There are two characteristics associated with the running of B<lond>,
                   8502: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   8503: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   8504: subscriptions, etc).  These are described in two large
                   8505: sections below.
                   8506: 
                   8507: B<PROCESS MANAGEMENT>
                   8508: 
1.61      harris41 8509: Preforker - server who forks first. Runs as a daemon. HUPs.
                   8510: Uses IDEA encryption
                   8511: 
1.74      harris41 8512: B<lond> forks off children processes that correspond to the other servers
                   8513: in the network.  Management of these processes can be done at the
                   8514: parent process level or the child process level.
                   8515: 
                   8516: B<logs/lond.log> is the location of log messages.
                   8517: 
                   8518: The process management is now explained in terms of linux shell commands,
                   8519: subroutines internal to this code, and signal assignments:
                   8520: 
                   8521: =over 4
                   8522: 
                   8523: =item *
                   8524: 
                   8525: PID is stored in B<logs/lond.pid>
                   8526: 
                   8527: This is the process id number of the parent B<lond> process.
                   8528: 
                   8529: =item *
                   8530: 
                   8531: SIGTERM and SIGINT
                   8532: 
                   8533: Parent signal assignment:
                   8534:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   8535: 
                   8536: Child signal assignment:
                   8537:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   8538: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   8539:  to restart a new child.)
                   8540: 
                   8541: Command-line invocations:
                   8542:  B<kill> B<-s> SIGTERM I<PID>
                   8543:  B<kill> B<-s> SIGINT I<PID>
                   8544: 
                   8545: Subroutine B<HUNTSMAN>:
                   8546:  This is only invoked for the B<lond> parent I<PID>.
                   8547: This kills all the children, and then the parent.
                   8548: The B<lonc.pid> file is cleared.
                   8549: 
                   8550: =item *
                   8551: 
                   8552: SIGHUP
                   8553: 
                   8554: Current bug:
                   8555:  This signal can only be processed the first time
                   8556: on the parent process.  Subsequent SIGHUP signals
                   8557: have no effect.
                   8558: 
                   8559: Parent signal assignment:
                   8560:  $SIG{HUP}  = \&HUPSMAN;
                   8561: 
                   8562: Child signal assignment:
                   8563:  none (nothing happens)
                   8564: 
                   8565: Command-line invocations:
                   8566:  B<kill> B<-s> SIGHUP I<PID>
                   8567: 
                   8568: Subroutine B<HUPSMAN>:
                   8569:  This is only invoked for the B<lond> parent I<PID>,
                   8570: This kills all the children, and then the parent.
                   8571: The B<lond.pid> file is cleared.
                   8572: 
                   8573: =item *
                   8574: 
                   8575: SIGUSR1
                   8576: 
                   8577: Parent signal assignment:
                   8578:  $SIG{USR1} = \&USRMAN;
                   8579: 
                   8580: Child signal assignment:
                   8581:  $SIG{USR1}= \&logstatus;
                   8582: 
                   8583: Command-line invocations:
                   8584:  B<kill> B<-s> SIGUSR1 I<PID>
                   8585: 
                   8586: Subroutine B<USRMAN>:
                   8587:  When invoked for the B<lond> parent I<PID>,
                   8588: SIGUSR1 is sent to all the children, and the status of
                   8589: each connection is logged.
1.144     foxr     8590: 
                   8591: =item *
                   8592: 
                   8593: SIGUSR2
                   8594: 
                   8595: Parent Signal assignment:
                   8596:     $SIG{USR2} = \&UpdateHosts
                   8597: 
                   8598: Child signal assignment:
                   8599:     NONE
                   8600: 
1.74      harris41 8601: 
                   8602: =item *
                   8603: 
                   8604: SIGCHLD
                   8605: 
                   8606: Parent signal assignment:
                   8607:  $SIG{CHLD} = \&REAPER;
                   8608: 
                   8609: Child signal assignment:
                   8610:  none
                   8611: 
                   8612: Command-line invocations:
                   8613:  B<kill> B<-s> SIGCHLD I<PID>
                   8614: 
                   8615: Subroutine B<REAPER>:
                   8616:  This is only invoked for the B<lond> parent I<PID>.
                   8617: Information pertaining to the child is removed.
                   8618: The socket port is cleaned up.
                   8619: 
                   8620: =back
                   8621: 
                   8622: B<SERVER-SIDE ACTIVITIES>
                   8623: 
                   8624: Server-side information can be accepted in an encrypted or non-encrypted
                   8625: method.
                   8626: 
                   8627: =over 4
                   8628: 
                   8629: =item ping
                   8630: 
                   8631: Query a client in the hosts.tab table; "Are you there?"
                   8632: 
                   8633: =item pong
                   8634: 
                   8635: Respond to a ping query.
                   8636: 
                   8637: =item ekey
                   8638: 
                   8639: Read in encrypted key, make cipher.  Respond with a buildkey.
                   8640: 
                   8641: =item load
                   8642: 
                   8643: Respond with CPU load based on a computation upon /proc/loadavg.
                   8644: 
                   8645: =item currentauth
                   8646: 
                   8647: Reply with current authentication information (only over an
                   8648: encrypted channel).
                   8649: 
                   8650: =item auth
                   8651: 
                   8652: Only over an encrypted channel, reply as to whether a user's
                   8653: authentication information can be validated.
                   8654: 
                   8655: =item passwd
                   8656: 
                   8657: Allow for a password to be set.
                   8658: 
                   8659: =item makeuser
                   8660: 
                   8661: Make a user.
                   8662: 
1.517     raeburn  8663: =item changeuserauth
1.74      harris41 8664: 
                   8665: Allow for authentication mechanism and password to be changed.
                   8666: 
                   8667: =item home
1.61      harris41 8668: 
1.74      harris41 8669: Respond to a question "are you the home for a given user?"
                   8670: 
                   8671: =item update
                   8672: 
                   8673: Update contents of a subscribed resource.
                   8674: 
                   8675: =item unsubscribe
                   8676: 
                   8677: The server is unsubscribing from a resource.
                   8678: 
                   8679: =item subscribe
                   8680: 
                   8681: The server is subscribing to a resource.
                   8682: 
                   8683: =item log
                   8684: 
                   8685: Place in B<logs/lond.log>
                   8686: 
                   8687: =item put
                   8688: 
                   8689: stores hash in namespace
                   8690: 
1.496     raeburn  8691: =item rolesput
1.74      harris41 8692: 
                   8693: put a role into a user's environment
                   8694: 
                   8695: =item get
                   8696: 
                   8697: returns hash with keys from array
                   8698: reference filled in from namespace
                   8699: 
                   8700: =item eget
                   8701: 
                   8702: returns hash with keys from array
                   8703: reference filled in from namesp (encrypts the return communication)
                   8704: 
                   8705: =item rolesget
                   8706: 
                   8707: get a role from a user's environment
                   8708: 
                   8709: =item del
                   8710: 
                   8711: deletes keys out of array from namespace
                   8712: 
                   8713: =item keys
                   8714: 
                   8715: returns namespace keys
                   8716: 
                   8717: =item dump
                   8718: 
                   8719: dumps the complete (or key matching regexp) namespace into a hash
                   8720: 
                   8721: =item store
                   8722: 
                   8723: stores hash permanently
                   8724: for this url; hashref needs to be given and should be a \%hashname; the
                   8725: remaining args aren't required and if they aren't passed or are '' they will
                   8726: be derived from the ENV
                   8727: 
                   8728: =item restore
                   8729: 
                   8730: returns a hash for a given url
                   8731: 
                   8732: =item querysend
                   8733: 
                   8734: Tells client about the lonsql process that has been launched in response
                   8735: to a sent query.
                   8736: 
                   8737: =item queryreply
                   8738: 
                   8739: Accept information from lonsql and make appropriate storage in temporary
                   8740: file space.
                   8741: 
                   8742: =item idput
                   8743: 
                   8744: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   8745: for each student, defined perhaps by the institutional Registrar.)
                   8746: 
                   8747: =item idget
                   8748: 
                   8749: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   8750: for each student, defined perhaps by the institutional Registrar.)
                   8751: 
1.517     raeburn  8752: =item iddel
                   8753: 
                   8754: Deletes one or more ids in a domain's id database.
                   8755: 
1.74      harris41 8756: =item tmpput
                   8757: 
                   8758: Accept and store information in temporary space.
                   8759: 
                   8760: =item tmpget
                   8761: 
                   8762: Send along temporarily stored information.
                   8763: 
                   8764: =item ls
                   8765: 
                   8766: List part of a user's directory.
                   8767: 
1.135     foxr     8768: =item pushtable
                   8769: 
                   8770: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   8771: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   8772: must be restored manually in case of a problem with the new table file.
                   8773: pushtable requires that the request be encrypted and validated via
                   8774: ValidateManager.  The form of the command is:
                   8775: enc:pushtable tablename <tablecontents> \n
                   8776: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   8777: cleartext newline.
                   8778: 
1.74      harris41 8779: =item Hanging up (exit or init)
                   8780: 
                   8781: What to do when a client tells the server that they (the client)
                   8782: are leaving the network.
                   8783: 
                   8784: =item unknown command
                   8785: 
                   8786: If B<lond> is sent an unknown command (not in the list above),
                   8787: it replys to the client "unknown_cmd".
1.135     foxr     8788: 
1.74      harris41 8789: 
                   8790: =item UNKNOWN CLIENT
                   8791: 
                   8792: If the anti-spoofing algorithm cannot verify the client,
                   8793: the client is rejected (with a "refused" message sent
                   8794: to the client, and the connection is closed.
                   8795: 
                   8796: =back
1.61      harris41 8797: 
                   8798: =head1 PREREQUISITES
                   8799: 
                   8800: IO::Socket
                   8801: IO::File
                   8802: Apache::File
                   8803: POSIX
                   8804: Crypt::IDEA
                   8805: GDBM_File
                   8806: Authen::Krb4
1.91      albertel 8807: Authen::Krb5
1.61      harris41 8808: 
                   8809: =head1 COREQUISITES
                   8810: 
1.490     droeschl 8811: none
                   8812: 
1.61      harris41 8813: =head1 OSNAMES
                   8814: 
                   8815: linux
                   8816: 
                   8817: =head1 SCRIPT CATEGORIES
                   8818: 
                   8819: Server/Process
                   8820: 
                   8821: =cut
1.409     foxr     8822: 
                   8823: 
                   8824: =pod
                   8825: 
                   8826: =head1 LOG MESSAGES
                   8827: 
                   8828: The messages below can be emitted in the lond log.  This log is located
                   8829: in ~httpd/perl/logs/lond.log  Many log messages have HTML encapsulation
                   8830: to provide coloring if examined from inside a web page. Some do not.
                   8831: Where color is used, the colors are; Red for sometihhng to get excited
                   8832: about and to follow up on. Yellow for something to keep an eye on to
                   8833: be sure it does not get worse, Green,and Blue for informational items.
                   8834: 
                   8835: In the discussions below, sometimes reference is made to ~httpd
                   8836: when describing file locations.  There isn't really an httpd 
                   8837: user, however there is an httpd directory that gets installed in the
                   8838: place that user home directories go.  On linux, this is usually
                   8839: (always?) /home/httpd.
                   8840: 
                   8841: 
                   8842: Some messages are colorless.  These are usually (not always)
                   8843: Green/Blue color level messages.
                   8844: 
                   8845: =over 2
                   8846: 
                   8847: =item (Red)  LocalConnection rejecting non local: <ip> ne 127.0.0.1
                   8848: 
                   8849: A local connection negotiation was attempted by
                   8850: a host whose IP address was not 127.0.0.1.
                   8851: The socket is closed and the child will exit.
                   8852: lond has three ways to establish an encyrption
                   8853: key with a client:
                   8854: 
                   8855: =over 2
                   8856: 
                   8857: =item local 
                   8858: 
                   8859: The key is written and read from a file.
                   8860: This is only valid for connections from localhost.
                   8861: 
                   8862: =item insecure 
                   8863: 
                   8864: The key is generated by the server and
                   8865: transmitted to the client.
                   8866: 
                   8867: =item  ssl (secure)
                   8868: 
                   8869: An ssl connection is negotiated with the client,
                   8870: the key is generated by the server and sent to the 
                   8871: client across this ssl connection before the
                   8872: ssl connectionis terminated and clear text
                   8873: transmission resumes.
                   8874: 
                   8875: =back
                   8876: 
                   8877: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
                   8878: 
                   8879: The client is local but has not sent an initialization
                   8880: string that is the literal "init:local"  The connection
                   8881: is closed and the child exits.
                   8882: 
                   8883: =item Red CRITICAL Can't get key file <error>        
                   8884: 
                   8885: SSL key negotiation is being attempted but the call to
                   8886: lonssl::KeyFile  failed.  This usually means that the
                   8887: configuration file is not correctly defining or protecting
                   8888: the directories/files lonCertificateDirectory or
                   8889: lonnetPrivateKey
                   8890: <error> is a string that describes the reason that
                   8891: the key file could not be located.
                   8892: 
                   8893: =item (Red) CRITICAL  Can't get certificates <error>  
                   8894: 
                   8895: SSL key negotiation failed because we were not able to retrives our certificate
                   8896: or the CA's certificate in the call to lonssl::CertificateFile
                   8897: <error> is the textual reason this failed.  Usual reasons:
                   8898: 
                   8899: =over 2
1.490     droeschl 8900: 
1.409     foxr     8901: =item Apache config file for loncapa  incorrect:
1.490     droeschl 8902: 
1.409     foxr     8903: one of the variables 
                   8904: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
                   8905: undefined or incorrect
                   8906: 
                   8907: =item Permission error:
                   8908: 
                   8909: The directory pointed to by lonCertificateDirectory is not readable by lond
                   8910: 
                   8911: =item Permission error:
                   8912: 
                   8913: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
                   8914: 
                   8915: =item Installation error:                         
                   8916: 
                   8917: Either the certificate authority file or the certificate have not
                   8918: been installed in lonCertificateDirectory.
                   8919: 
                   8920: =item (Red) CRITICAL SSL Socket promotion failed:  <err> 
                   8921: 
                   8922: The promotion of the connection from plaintext to SSL failed
                   8923: <err> is the reason for the failure.  There are two
                   8924: system calls involved in the promotion (one of which failed), 
                   8925: a dup to produce
                   8926: a second fd on the raw socket over which the encrypted data
                   8927: will flow and IO::SOcket::SSL->new_from_fd which creates
                   8928: the SSL connection on the duped fd.
                   8929: 
                   8930: =item (Blue)   WARNING client did not respond to challenge 
                   8931: 
                   8932: This occurs on an insecure (non SSL) connection negotiation request.
                   8933: lond generates some number from the time, the PID and sends it to
                   8934: the client.  The client must respond by echoing this information back.
                   8935: If the client does not do so, that's a violation of the challenge
                   8936: protocols and the connection will be failed.
                   8937: 
                   8938: =item (Red) No manager table. Nobody can manage!!    
                   8939: 
                   8940: lond has the concept of privileged hosts that
                   8941: can perform remote management function such
                   8942: as update the hosts.tab.   The manager hosts
                   8943: are described in the 
                   8944: ~httpd/lonTabs/managers.tab file.
                   8945: this message is logged if this file is missing.
                   8946: 
                   8947: 
                   8948: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
                   8949: 
                   8950: Reports the successful parse and registration
                   8951: of a specific manager. 
                   8952: 
                   8953: =item Green existing host <clustername:dnsname>  
                   8954: 
                   8955: The manager host is already defined in the hosts.tab
                   8956: the information in that table, rather than the info in the
                   8957: manager table will be used to determine the manager's ip.
                   8958: 
                   8959: =item (Red) Unable to craete <filename>                 
                   8960: 
                   8961: lond has been asked to create new versions of an administrative
                   8962: file (by a manager).  When this is done, the new file is created
                   8963: in a temp file and then renamed into place so that there are always
                   8964: usable administrative files, even if the update fails.  This failure
                   8965: message means that the temp file could not be created.
                   8966: The update is abandoned, and the old file is available for use.
                   8967: 
                   8968: =item (Green) CopyFile from <oldname> to <newname> failed
                   8969: 
                   8970: In an update of administrative files, the copy of the existing file to a
                   8971: backup file failed.  The installation of the new file may still succeed,
                   8972: but there will not be a back up file to rever to (this should probably
                   8973: be yellow).
                   8974: 
                   8975: =item (Green) Pushfile: backed up <oldname> to <newname>
                   8976: 
                   8977: See above, the backup of the old administrative file succeeded.
                   8978: 
                   8979: =item (Red)  Pushfile: Unable to install <filename> <reason>
                   8980: 
                   8981: The new administrative file could not be installed.  In this case,
                   8982: the old administrative file is still in use.
                   8983: 
                   8984: =item (Green) Installed new < filename>.                      
                   8985: 
                   8986: The new administrative file was successfullly installed.                                               
                   8987: 
                   8988: =item (Red) Reinitializing lond pid=<pid>                    
                   8989: 
                   8990: The lonc child process <pid> will be sent a USR2 
                   8991: signal.
                   8992: 
                   8993: =item (Red) Reinitializing self                                    
                   8994: 
                   8995: We've been asked to re-read our administrative files,and
                   8996: are doing so.
                   8997: 
                   8998: =item (Yellow) error:Invalid process identifier <ident>  
                   8999: 
                   9000: A reinit command was received, but the target part of the 
                   9001: command was not valid.  It must be either
                   9002: 'lond' or 'lonc' but was <ident>
                   9003: 
                   9004: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
                   9005: 
                   9006: Checking to see if lond has been handed a valid edit
                   9007: command.  It is possible the edit command is not valid
                   9008: in that case there are no log messages to indicate that.
                   9009: 
                   9010: =item Result of password change for  <username> pwchange_success
                   9011: 
                   9012: The password for <username> was
                   9013: successfully changed.
                   9014: 
                   9015: =item Unable to open <user> passwd to change password
                   9016: 
                   9017: Could not rewrite the 
                   9018: internal password file for a user
                   9019: 
                   9020: =item Result of password change for <user> : <result>
1.490     droeschl 9021: 
1.409     foxr     9022: A unix password change for <user> was attempted 
                   9023: and the pipe returned <result>  
                   9024: 
                   9025: =item LWP GET: <message> for <fname> (<remoteurl>)
                   9026: 
                   9027: The lightweight process fetch for a resource failed
                   9028: with <message> the local filename that should
                   9029: have existed/been created was  <fname> the
                   9030: corresponding URI: <remoteurl>  This is emitted in several
                   9031: places.
                   9032: 
                   9033: =item Unable to move <transname> to <destname>     
                   9034: 
                   9035: From fetch_user_file_handler - the user file was replicated but could not
                   9036: be mv'd to its final location.
                   9037: 
                   9038: =item Looking for <domain> <username>              
                   9039: 
                   9040: From user_has_session_handler - This should be a Debug call instead
                   9041: it indicates lond is about to check whether the specified user has a 
                   9042: session active on the specified domain on the local host.
                   9043: 
                   9044: =item Client <ip> (<name>) hanging up: <input>     
                   9045: 
                   9046: lond has been asked to exit by its client.  The <ip> and <name> identify the
                   9047: client systemand <input> is the full exit command sent to the server.
                   9048: 
                   9049: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
1.490     droeschl 9050: 
1.409     foxr     9051: A lond child terminated.  NOte that this termination can also occur when the
                   9052: child receives the QUIT or DIE signals.  <pid> is the process id of the child,
                   9053: <hostname> the host lond is working for, and <message> the reason the child died
                   9054: to the best of our ability to get it (I would guess that any numeric value
                   9055: represents and errno value).  This is immediately followed by
                   9056: 
                   9057: =item  Famous last words: Catching exception - <log> 
                   9058: 
                   9059: Where log is some recent information about the state of the child.
                   9060: 
                   9061: =item Red CRITICAL: TIME OUT <pid>                     
                   9062: 
                   9063: Some timeout occured for server <pid>.  THis is normally a timeout on an LWP
                   9064: doing an HTTP::GET.
                   9065: 
                   9066: =item child <pid> died                              
                   9067: 
                   9068: The reaper caught a SIGCHILD for the lond child process <pid>
                   9069: This should be modified to also display the IP of the dying child
                   9070: $children{$pid}
                   9071: 
                   9072: =item Unknown child 0 died                           
                   9073: A child died but the wait for it returned a pid of zero which really should not
                   9074: ever happen. 
                   9075: 
                   9076: =item Child <which> - <pid> looks like we missed it's death 
                   9077: 
                   9078: When a sigchild is received, the reaper process checks all children to see if they are
                   9079: alive.  If children are dying quite quickly, the lack of signal queuing can mean
                   9080: that a signal hearalds the death of more than one child.  If so this message indicates
                   9081: which other one died. <which> is the ip of a dead child
                   9082: 
                   9083: =item Free socket: <shutdownretval>                
                   9084: 
                   9085: The HUNTSMAN sub was called due to a SIGINT in a child process.  The socket is being shutdown.
                   9086: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
                   9087: to return anything. This is followed by: 
                   9088: 
                   9089: =item Red CRITICAL: Shutting down                       
                   9090: 
                   9091: Just prior to exit.
                   9092: 
                   9093: =item Free socket: <shutdownretval>                 
                   9094: 
                   9095: The HUPSMAN sub was called due to a SIGHUP.  all children get killsed, and lond execs itself.
                   9096: This is followed by:
                   9097: 
                   9098: =item (Red) CRITICAL: Restarting                         
                   9099: 
                   9100: lond is about to exec itself to restart.
                   9101: 
                   9102: =item (Blue) Updating connections                        
                   9103: 
                   9104: (In response to a USR2).  All the children (except the one for localhost)
                   9105: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
                   9106: 
                   9107: =item (Blue) UpdateHosts killing child <pid> for ip <ip>   
                   9108: 
                   9109: Due to USR2 as above.
                   9110: 
                   9111: =item (Green) keeping child for ip <ip> (pid = <pid>)    
                   9112: 
                   9113: In response to USR2 as above, the child indicated is not being restarted because
                   9114: it's assumed that we'll always need a child for the localhost.
                   9115: 
                   9116: 
                   9117: =item Going to check on the children                
                   9118: 
                   9119: Parent is about to check on the health of the child processes.
                   9120: Note that this is in response to a USR1 sent to the parent lond.
                   9121: there may be one or more of the next two messages:
                   9122: 
                   9123: =item <pid> is dead                                 
                   9124: 
                   9125: A child that we have in our child hash as alive has evidently died.
                   9126: 
                   9127: =item  Child <pid> did not respond                   
                   9128: 
                   9129: In the health check the child <pid> did not update/produce a pid_.txt
                   9130: file when sent it's USR1 signal.  That process is killed with a 9 signal, as it's
                   9131: assumed to be hung in some un-fixable way.
                   9132: 
                   9133: =item Finished checking children                   
1.490     droeschl 9134: 
1.409     foxr     9135: Master processs's USR1 processing is cojmplete.
                   9136: 
                   9137: =item (Red) CRITICAL: ------- Starting ------            
                   9138: 
                   9139: (There are more '-'s on either side).  Lond has forked itself off to 
                   9140: form a new session and is about to start actual initialization.
                   9141: 
                   9142: =item (Green) Attempting to start child (<client>)       
                   9143: 
                   9144: Started a new child process for <client>.  Client is IO::Socket object
                   9145: connected to the child.  This was as a result of a TCP/IP connection from a client.
                   9146: 
                   9147: =item Unable to determine who caller was, getpeername returned nothing
1.490     droeschl 9148: 
1.409     foxr     9149: In child process initialization.  either getpeername returned undef or
                   9150: a zero sized object was returned.  Processing continues, but in my opinion,
                   9151: this should be cause for the child to exit.
                   9152: 
                   9153: =item Unable to determine clientip                  
                   9154: 
                   9155: In child process initialization.  The peer address from getpeername was not defined.
                   9156: The client address is stored as "Unavailable" and processing continues.
                   9157: 
                   9158: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
1.490     droeschl 9159: 
1.409     foxr     9160: In child initialization.  A good connectionw as received from <ip>.
                   9161: 
                   9162: =over 2
                   9163: 
                   9164: =item <name> 
                   9165: 
                   9166: is the name of the client from hosts.tab.
                   9167: 
                   9168: =item <type> 
                   9169: 
                   9170: Is the connection type which is either 
                   9171: 
                   9172: =over 2
                   9173: 
                   9174: =item manager 
                   9175: 
                   9176: The connection is from a manager node, not in hosts.tab
                   9177: 
                   9178: =item client  
                   9179: 
                   9180: the connection is from a non-manager in the hosts.tab
                   9181: 
                   9182: =item both
                   9183: 
                   9184: The connection is from a manager in the hosts.tab.
                   9185: 
                   9186: =back
                   9187: 
                   9188: =back
                   9189: 
                   9190: =item (Blue) Certificates not installed -- trying insecure auth
                   9191: 
                   9192: One of the certificate file, key file or
                   9193: certificate authority file could not be found for a client attempting
                   9194: SSL connection intiation.  COnnection will be attemptied in in-secure mode.
                   9195: (this would be a system with an up to date lond that has not gotten a 
                   9196: certificate from us).
                   9197: 
                   9198: =item (Green)  Successful local authentication            
                   9199: 
                   9200: A local connection successfully negotiated the encryption key. 
                   9201: In this case the IDEA key is in a file (that is hopefully well protected).
                   9202: 
                   9203: =item (Green) Successful ssl authentication with <client>  
                   9204: 
                   9205: The client (<client> is the peer's name in hosts.tab), has successfully
                   9206: negotiated an SSL connection with this child process.
                   9207: 
                   9208: =item (Green) Successful insecure authentication with <client>
1.490     droeschl 9209: 
1.409     foxr     9210: 
                   9211: The client has successfully negotiated an  insecure connection withthe child process.
                   9212: 
                   9213: =item (Yellow) Attempted insecure connection disallowed    
                   9214: 
                   9215: The client attempted and failed to successfully negotiate a successful insecure
                   9216: connection.  This can happen either because the variable londAllowInsecure is false
                   9217: or undefined, or becuse the child did not successfully echo back the challenge
                   9218: string.
                   9219: 
                   9220: 
                   9221: =back
                   9222: 
1.441     raeburn  9223: =back
                   9224: 
1.409     foxr     9225: 
                   9226: =cut

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