Annotation of loncom/lond, revision 1.539

1.1       albertel    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60      www         4: #
1.539   ! raeburn     5: # $Id: lond,v 1.538 2017/06/06 13:32:38 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.539   ! raeburn    68: my $VERSION='$Revision: 1.538 $'; #' 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))) {
        !          1922: 
1.529     raeburn  1923:                 &Failure($client,"refused\n",$userinput);
                   1924:                 return 1;
                   1925:             }
1.399     raeburn  1926:             my @ulsstats=stat($ulsdir);
                   1927:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1928:         }
                   1929:     } else {
                   1930:         $ulsout='no_such_dir';
1.400     raeburn  1931:     }
                   1932:     if ($ulsout eq '') { $ulsout='empty'; }
                   1933:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
                   1934:     return 1;
1.399     raeburn  1935: }
                   1936: &register_handler("ls3", \&ls3_handler, 0, 1, 0);
1.280     matthew  1937: 
1.477     raeburn  1938: sub read_lonnet_global {
                   1939:     my ($cmd,$tail,$client) = @_;
                   1940:     my $userinput = "$cmd:$tail";
                   1941:     my $requested = &Apache::lonnet::thaw_unescape($tail);
                   1942:     my $result;
1.480     raeburn  1943:     my %packagevars = (
                   1944:                         spareid => \%Apache::lonnet::spareid,
                   1945:                         perlvar => \%Apache::lonnet::perlvar,
                   1946:                       );
                   1947:     my %limit_to = (
                   1948:                     perlvar => {
1.531     raeburn  1949:                                  lonOtherAuthen  => 1,
                   1950:                                  lonBalancer     => 1,
                   1951:                                  lonVersion      => 1,
                   1952:                                  lonAdmEMail     => 1,
                   1953:                                  lonSupportEMail => 1,  
                   1954:                                  lonSysEMail     => 1,
                   1955:                                  lonHostID       => 1,
                   1956:                                  lonRole         => 1,
                   1957:                                  lonDefDomain    => 1,
                   1958:                                  lonLoadLim      => 1,
                   1959:                                  lonUserLoadLim  => 1,
1.480     raeburn  1960:                                }
                   1961:                   );
1.477     raeburn  1962:     if (ref($requested) eq 'HASH') {
                   1963:         foreach my $what (keys(%{$requested})) {
                   1964:             my $response;
1.480     raeburn  1965:             my $items = {};
                   1966:             if (exists($packagevars{$what})) {
                   1967:                 if (ref($limit_to{$what}) eq 'HASH') {
                   1968:                     foreach my $varname (keys(%{$packagevars{$what}})) {
                   1969:                         if ($limit_to{$what}{$varname}) {
                   1970:                             $items->{$varname} = $packagevars{$what}{$varname};
                   1971:                         }
                   1972:                     }
                   1973:                 } else {
                   1974:                     $items = $packagevars{$what};
1.477     raeburn  1975:                 }
1.480     raeburn  1976:                 if ($what eq 'perlvar') {
                   1977:                     if (!exists($packagevars{$what}{'lonBalancer'})) {
                   1978:                         if ($dist =~ /^(centos|rhes|fedora|scientific)/) {
                   1979:                             my $othervarref=LONCAPA::Configuration::read_conf('httpd.conf');
                   1980:                             if (ref($othervarref) eq 'HASH') {
                   1981:                                 $items->{'lonBalancer'} = $othervarref->{'lonBalancer'};
                   1982:                             }
                   1983:                         }
                   1984:                     }
1.477     raeburn  1985:                 }
1.480     raeburn  1986:                 $response = &Apache::lonnet::freeze_escape($items);
1.477     raeburn  1987:             }
1.478     raeburn  1988:             $result .= &escape($what).'='.$response.'&';
1.477     raeburn  1989:         }
                   1990:     }
                   1991:     $result =~ s/\&$//;
                   1992:     &Reply($client,\$result,$userinput);
                   1993:     return 1;
                   1994: }
                   1995: &register_handler("readlonnetglobal", \&read_lonnet_global, 0, 1, 0);
                   1996: 
1.479     raeburn  1997: sub server_devalidatecache_handler {
                   1998:     my ($cmd,$tail,$client) = @_;
                   1999:     my $userinput = "$cmd:$tail";
1.503     raeburn  2000:     my $items = &unescape($tail);
                   2001:     my @cached = split(/\&/,$items);
                   2002:     foreach my $key (@cached) {
                   2003:         if ($key =~ /:/) {
                   2004:             my ($name,$id) = map { &unescape($_); } split(/:/,$key);
                   2005:             &Apache::lonnet::devalidate_cache_new($name,$id);
                   2006:         }
                   2007:     }
1.479     raeburn  2008:     my $result = 'ok';
                   2009:     &Reply($client,\$result,$userinput);
                   2010:     return 1;
                   2011: }
1.481     raeburn  2012: &register_handler("devalidatecache", \&server_devalidatecache_handler, 0, 1, 0);
1.479     raeburn  2013: 
1.410     raeburn  2014: sub server_timezone_handler {
                   2015:     my ($cmd,$tail,$client) = @_;
                   2016:     my $userinput = "$cmd:$tail";
                   2017:     my $timezone;
                   2018:     my $clockfile = '/etc/sysconfig/clock'; # Fedora/CentOS/SuSE
                   2019:     my $tzfile = '/etc/timezone'; # Debian/Ubuntu
                   2020:     if (-e $clockfile) {
                   2021:         if (open(my $fh,"<$clockfile")) {
                   2022:             while (<$fh>) {
                   2023:                 next if (/^[\#\s]/);
                   2024:                 if (/^(?:TIME)?ZONE\s*=\s*['"]?\s*([\w\/]+)/) {
                   2025:                     $timezone = $1;
                   2026:                     last;
                   2027:                 }
                   2028:             }
                   2029:             close($fh);
                   2030:         }
                   2031:     } elsif (-e $tzfile) {
                   2032:         if (open(my $fh,"<$tzfile")) {
                   2033:             $timezone = <$fh>;
                   2034:             close($fh);
                   2035:             chomp($timezone);
                   2036:             if ($timezone =~ m{^Etc/(\w+)$}) {
                   2037:                 $timezone = $1;
                   2038:             }
                   2039:         }
                   2040:     }
                   2041:     &Reply($client,\$timezone,$userinput); # This supports debug logging.
                   2042:     return 1;
                   2043: }
                   2044: &register_handler("servertimezone", \&server_timezone_handler, 0, 1, 0);
                   2045: 
1.413     raeburn  2046: sub server_loncaparev_handler {
                   2047:     my ($cmd,$tail,$client) = @_;
                   2048:     my $userinput = "$cmd:$tail";
                   2049:     &Reply($client,\$perlvar{'lonVersion'},$userinput);
                   2050:     return 1;
                   2051: }
                   2052: &register_handler("serverloncaparev", \&server_loncaparev_handler, 0, 1, 0);
                   2053: 
1.448     raeburn  2054: sub server_homeID_handler {
                   2055:     my ($cmd,$tail,$client) = @_;
                   2056:     my $userinput = "$cmd:$tail";
                   2057:     &Reply($client,\$perlvar{'lonHostID'},$userinput);
                   2058:     return 1;
                   2059: }
                   2060: &register_handler("serverhomeID", \&server_homeID_handler, 0, 1, 0);
                   2061: 
1.471     raeburn  2062: sub server_distarch_handler {
                   2063:     my ($cmd,$tail,$client) = @_;
                   2064:     my $userinput = "$cmd:$tail";
                   2065:     my $reply = &distro_and_arch();
                   2066:     &Reply($client,\$reply,$userinput);
                   2067:     return 1;
                   2068: }
                   2069: &register_handler("serverdistarch", \&server_distarch_handler, 0, 1, 0);
                   2070: 
1.523     raeburn  2071: sub server_certs_handler {
                   2072:     my ($cmd,$tail,$client) = @_;
                   2073:     my $userinput = "$cmd:$tail";
                   2074:     my $result;
                   2075:     my $result = &LONCAPA::Lond::server_certs(\%perlvar);
                   2076:     &Reply($client,\$result,$userinput);
                   2077:     return;
                   2078: }
                   2079: &register_handler("servercerts", \&server_certs_handler, 0, 1, 0);
                   2080: 
1.218     foxr     2081: #   Process a reinit request.  Reinit requests that either
                   2082: #   lonc or lond be reinitialized so that an updated 
                   2083: #   host.tab or domain.tab can be processed.
                   2084: #
                   2085: # Parameters:
                   2086: #      $cmd    - the actual keyword that invoked us.
                   2087: #      $tail   - the tail of the request that invoked us.
                   2088: #      $client - File descriptor connected to the client
                   2089: #  Returns:
                   2090: #      1       - Ok to continue processing.
                   2091: #      0       - Program should exit
                   2092: #  Implicit output:
                   2093: #     a reply is sent to the client.
                   2094: #
                   2095: sub reinit_process_handler {
                   2096:     my ($cmd, $tail, $client) = @_;
                   2097:    
                   2098:     my $userinput = "$cmd:$tail";
                   2099:    
                   2100:     my $cert = &GetCertificate($userinput);
                   2101:     if(&ValidManager($cert)) {
                   2102: 	chomp($userinput);
                   2103: 	my $reply = &ReinitProcess($userinput);
1.387     albertel 2104: 	&Reply( $client,  \$reply, $userinput);
1.218     foxr     2105:     } else {
                   2106: 	&Failure( $client, "refused\n", $userinput);
                   2107:     }
                   2108:     return 1;
                   2109: }
                   2110: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
                   2111: 
                   2112: #  Process the editing script for a table edit operation.
                   2113: #  the editing operation must be encrypted and requested by
                   2114: #  a manager host.
                   2115: #
                   2116: # Parameters:
                   2117: #      $cmd    - the actual keyword that invoked us.
                   2118: #      $tail   - the tail of the request that invoked us.
                   2119: #      $client - File descriptor connected to the client
                   2120: #  Returns:
                   2121: #      1       - Ok to continue processing.
                   2122: #      0       - Program should exit
                   2123: #  Implicit output:
                   2124: #     a reply is sent to the client.
                   2125: #
                   2126: sub edit_table_handler {
                   2127:     my ($command, $tail, $client) = @_;
                   2128:    
                   2129:     my $userinput = "$command:$tail";
                   2130: 
                   2131:     my $cert = &GetCertificate($userinput);
                   2132:     if(&ValidManager($cert)) {
                   2133: 	my($filetype, $script) = split(/:/, $tail);
                   2134: 	if (($filetype eq "hosts") || 
                   2135: 	    ($filetype eq "domain")) {
                   2136: 	    if($script ne "") {
                   2137: 		&Reply($client,              # BUGBUG - EditFile
                   2138: 		      &EditFile($userinput), #   could fail.
                   2139: 		      $userinput);
                   2140: 	    } else {
                   2141: 		&Failure($client,"refused\n",$userinput);
                   2142: 	    }
                   2143: 	} else {
                   2144: 	    &Failure($client,"refused\n",$userinput);
                   2145: 	}
                   2146:     } else {
                   2147: 	&Failure($client,"refused\n",$userinput);
                   2148:     }
                   2149:     return 1;
                   2150: }
1.263     albertel 2151: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
1.218     foxr     2152: 
1.220     foxr     2153: #
                   2154: #   Authenticate a user against the LonCAPA authentication
                   2155: #   database.  Note that there are several authentication
                   2156: #   possibilities:
                   2157: #   - unix     - The user can be authenticated against the unix
                   2158: #                password file.
                   2159: #   - internal - The user can be authenticated against a purely 
                   2160: #                internal per user password file.
                   2161: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
                   2162: #                ticket granting authority.
                   2163: #   - user     - The person tailoring LonCAPA can supply a user authentication
                   2164: #                mechanism that is per system.
                   2165: #
                   2166: # Parameters:
                   2167: #    $cmd      - The command that got us here.
                   2168: #    $tail     - Tail of the command (remaining parameters).
                   2169: #    $client   - File descriptor connected to client.
                   2170: # Returns
                   2171: #     0        - Requested to exit, caller should shut down.
                   2172: #     1        - Continue processing.
                   2173: # Implicit inputs:
                   2174: #    The authentication systems describe above have their own forms of implicit
                   2175: #    input into the authentication process that are described above.
                   2176: #
                   2177: sub authenticate_handler {
                   2178:     my ($cmd, $tail, $client) = @_;
                   2179: 
                   2180:     
                   2181:     #  Regenerate the full input line 
                   2182:     
                   2183:     my $userinput  = $cmd.":".$tail;
                   2184:     
                   2185:     #  udom    - User's domain.
                   2186:     #  uname   - Username.
                   2187:     #  upass   - User's password.
1.396     raeburn  2188:     #  checkdefauth - Pass to validate_user() to try authentication
                   2189:     #                 with default auth type(s) if no user account.
1.447     raeburn  2190:     #  clientcancheckhost - Passed by clients with functionality in lonauth.pm
                   2191:     #                       to check if session can be hosted.
1.220     foxr     2192:     
1.447     raeburn  2193:     my ($udom, $uname, $upass, $checkdefauth, $clientcancheckhost)=split(/:/,$tail);
1.399     raeburn  2194:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass,  checkdefauth = $checkdefauth");
1.220     foxr     2195:     chomp($upass);
                   2196:     $upass=&unescape($upass);
                   2197: 
1.396     raeburn  2198:     my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
1.220     foxr     2199:     if($pwdcorrect) {
1.447     raeburn  2200:         my $canhost = 1;
                   2201:         unless ($clientcancheckhost) {
1.448     raeburn  2202:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   2203:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.452     raeburn  2204:             my @intdoms;
                   2205:             my $internet_names = &Apache::lonnet::get_internet_names($clientname);
                   2206:             if (ref($internet_names) eq 'ARRAY') {
                   2207:                 @intdoms = @{$internet_names};
                   2208:             }
1.448     raeburn  2209:             unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
1.447     raeburn  2210:                 my ($remote,$hosted);
                   2211:                 my $remotesession = &get_usersession_config($udom,'remotesession');
                   2212:                 if (ref($remotesession) eq 'HASH') {
1.525     raeburn  2213:                     $remote = $remotesession->{'remote'};
1.447     raeburn  2214:                 }
1.448     raeburn  2215:                 my $hostedsession = &get_usersession_config($clienthomedom,'hostedsession');
1.447     raeburn  2216:                 if (ref($hostedsession) eq 'HASH') {
                   2217:                     $hosted = $hostedsession->{'hosted'};
                   2218:                 }
1.448     raeburn  2219:                 $canhost = &Apache::lonnet::can_host_session($udom,$clientname,
1.492     droeschl 2220:                                                              $clientversion,
1.447     raeburn  2221:                                                              $remote,$hosted);
                   2222:             }
                   2223:         }
                   2224:         if ($canhost) {               
                   2225:             &Reply( $client, "authorized\n", $userinput);
                   2226:         } else {
                   2227:             &Reply( $client, "not_allowed_to_host\n", $userinput);
                   2228:         }
1.220     foxr     2229: 	#
                   2230: 	#  Bad credentials: Failed to authorize
                   2231: 	#
                   2232:     } else {
                   2233: 	&Failure( $client, "non_authorized\n", $userinput);
                   2234:     }
                   2235: 
                   2236:     return 1;
                   2237: }
1.263     albertel 2238: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
1.214     foxr     2239: 
1.222     foxr     2240: #
                   2241: #   Change a user's password.  Note that this function is complicated by
                   2242: #   the fact that a user may be authenticated in more than one way:
                   2243: #   At present, we are not able to change the password for all types of
                   2244: #   authentication methods.  Only for:
                   2245: #      unix    - unix password or shadow passoword style authentication.
                   2246: #      local   - Locally written authentication mechanism.
                   2247: #   For now, kerb4 and kerb5 password changes are not supported and result
                   2248: #   in an error.
                   2249: # FUTURE WORK:
                   2250: #    Support kerberos passwd changes?
                   2251: # Parameters:
                   2252: #    $cmd      - The command that got us here.
                   2253: #    $tail     - Tail of the command (remaining parameters).
                   2254: #    $client   - File descriptor connected to client.
                   2255: # Returns
                   2256: #     0        - Requested to exit, caller should shut down.
                   2257: #     1        - Continue processing.
                   2258: # Implicit inputs:
                   2259: #    The authentication systems describe above have their own forms of implicit
                   2260: #    input into the authentication process that are described above.
                   2261: sub change_password_handler {
                   2262:     my ($cmd, $tail, $client) = @_;
                   2263: 
                   2264:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
                   2265: 
                   2266:     #
                   2267:     #  udom  - user's domain.
                   2268:     #  uname - Username.
                   2269:     #  upass - Current password.
                   2270:     #  npass - New password.
1.346     raeburn  2271:     #  context - Context in which this was called 
                   2272:     #            (preferences or reset_by_email).
1.428     raeburn  2273:     #  lonhost - HostID of server where request originated 
1.222     foxr     2274:    
1.428     raeburn  2275:     my ($udom,$uname,$upass,$npass,$context,$lonhost)=split(/:/,$tail);
1.222     foxr     2276: 
                   2277:     $upass=&unescape($upass);
                   2278:     $npass=&unescape($npass);
                   2279:     &Debug("Trying to change password for $uname");
                   2280: 
                   2281:     # First require that the user can be authenticated with their
1.346     raeburn  2282:     # old password unless context was 'reset_by_email':
                   2283:     
1.428     raeburn  2284:     my ($validated,$failure);
1.346     raeburn  2285:     if ($context eq 'reset_by_email') {
1.428     raeburn  2286:         if ($lonhost eq '') {
                   2287:             $failure = 'invalid_client';
                   2288:         } else {
                   2289:             $validated = 1;
                   2290:         }
1.346     raeburn  2291:     } else {
                   2292:         $validated = &validate_user($udom, $uname, $upass);
                   2293:     }
1.222     foxr     2294:     if($validated) {
                   2295: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
                   2296: 	
                   2297: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
                   2298: 	if ($howpwd eq 'internal') {
                   2299: 	    &Debug("internal auth");
1.518     raeburn  2300:             my $ncpass = &hash_passwd($udom,$npass);
1.222     foxr     2301: 	    if(&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
1.428     raeburn  2302: 		my $msg="Result of password change for $uname: pwchange_success";
                   2303:                 if ($lonhost) {
                   2304:                     $msg .= " - request originated from: $lonhost";
                   2305:                 }
                   2306:                 &logthis($msg);
1.518     raeburn  2307:                 &update_passwd_history($uname,$udom,$howpwd,$context);
1.222     foxr     2308: 		&Reply($client, "ok\n", $userinput);
                   2309: 	    } else {
                   2310: 		&logthis("Unable to open $uname passwd "               
                   2311: 			 ."to change password");
                   2312: 		&Failure( $client, "non_authorized\n",$userinput);
                   2313: 	    }
1.346     raeburn  2314: 	} elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
1.287     foxr     2315: 	    my $result = &change_unix_password($uname, $npass);
1.518     raeburn  2316:             if ($result eq 'ok') {
                   2317:                 &update_passwd_history($uname,$udom,$howpwd,$context);
                   2318:              }
1.222     foxr     2319: 	    &logthis("Result of password change for $uname: ".
1.287     foxr     2320: 		     $result);
1.387     albertel 2321: 	    &Reply($client, \$result, $userinput);
1.222     foxr     2322: 	} else {
                   2323: 	    # this just means that the current password mode is not
                   2324: 	    # one we know how to change (e.g the kerberos auth modes or
                   2325: 	    # locally written auth handler).
                   2326: 	    #
                   2327: 	    &Failure( $client, "auth_mode_error\n", $userinput);
                   2328: 	}  
                   2329: 	
1.224     foxr     2330:     } else {
1.428     raeburn  2331: 	if ($failure eq '') {
                   2332: 	    $failure = 'non_authorized';
                   2333: 	}
                   2334: 	&Failure( $client, "$failure\n", $userinput);
1.222     foxr     2335:     }
                   2336: 
                   2337:     return 1;
                   2338: }
1.263     albertel 2339: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
1.222     foxr     2340: 
1.518     raeburn  2341: sub hash_passwd {
                   2342:     my ($domain,$plainpass,@rest) = @_;
                   2343:     my ($salt,$cost);
                   2344:     if (@rest) {
                   2345:         $cost = $rest[0];
                   2346:         # salt is first 22 characters, base-64 encoded by bcrypt
                   2347:         my $plainsalt = substr($rest[1],0,22);
                   2348:         $salt = Crypt::Eksblowfish::Bcrypt::de_base64($plainsalt);
                   2349:     } else {
1.533     raeburn  2350:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2351:         my $defaultcost = $domdefaults{'intauth_cost'};
1.518     raeburn  2352:         if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   2353:             $cost = 10;
                   2354:         } else {
                   2355:             $cost = $defaultcost;
                   2356:         }
                   2357:         # Generate random 16-octet base64 salt
                   2358:         $salt = "";
                   2359:         $salt .= pack("C", int rand(256)) for 1..16;
                   2360:     }
                   2361:     my $hash = &Crypt::Eksblowfish::Bcrypt::bcrypt_hash({
                   2362:         key_nul => 1,
                   2363:         cost    => $cost,
                   2364:         salt    => $salt,
                   2365:     }, Digest::SHA::sha512(Encode::encode('UTF-8',$plainpass)));
                   2366: 
                   2367:     my $result = join("!", "", "bcrypt", sprintf("%02d",$cost),
                   2368:                 &Crypt::Eksblowfish::Bcrypt::en_base64($salt).
                   2369:                 &Crypt::Eksblowfish::Bcrypt::en_base64($hash));
                   2370:     return $result;
                   2371: }
                   2372: 
1.225     foxr     2373: #
                   2374: #   Create a new user.  User in this case means a lon-capa user.
                   2375: #   The user must either already exist in some authentication realm
                   2376: #   like kerberos or the /etc/passwd.  If not, a user completely local to
                   2377: #   this loncapa system is created.
                   2378: #
                   2379: # Parameters:
                   2380: #    $cmd      - The command that got us here.
                   2381: #    $tail     - Tail of the command (remaining parameters).
                   2382: #    $client   - File descriptor connected to client.
                   2383: # Returns
                   2384: #     0        - Requested to exit, caller should shut down.
                   2385: #     1        - Continue processing.
                   2386: # Implicit inputs:
                   2387: #    The authentication systems describe above have their own forms of implicit
                   2388: #    input into the authentication process that are described above.
                   2389: sub add_user_handler {
                   2390: 
                   2391:     my ($cmd, $tail, $client) = @_;
                   2392: 
                   2393: 
                   2394:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2395:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
                   2396: 
                   2397:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
                   2398: 
                   2399: 
                   2400:     if($udom eq $currentdomainid) { # Reject new users for other domains...
                   2401: 	
                   2402: 	my $oldumask=umask(0077);
                   2403: 	chomp($npass);
                   2404: 	$npass=&unescape($npass);
                   2405: 	my $passfilename  = &password_path($udom, $uname);
                   2406: 	&Debug("Password file created will be:".$passfilename);
                   2407: 	if (-e $passfilename) {
                   2408: 	    &Failure( $client, "already_exists\n", $userinput);
                   2409: 	} else {
                   2410: 	    my $fperror='';
1.264     albertel 2411: 	    if (!&mkpath($passfilename)) {
                   2412: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
                   2413: 		    ."makeuser";
1.225     foxr     2414: 	    }
                   2415: 	    unless ($fperror) {
1.518     raeburn  2416: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2417:                                              $passfilename,'makeuser');
1.390     raeburn  2418: 		&Reply($client,\$result, $userinput);     #BUGBUG - could be fail
1.225     foxr     2419: 	    } else {
1.387     albertel 2420: 		&Failure($client, \$fperror, $userinput);
1.225     foxr     2421: 	    }
                   2422: 	}
                   2423: 	umask($oldumask);
                   2424:     }  else {
                   2425: 	&Failure($client, "not_right_domain\n",
                   2426: 		$userinput);	# Even if we are multihomed.
                   2427:     
                   2428:     }
                   2429:     return 1;
                   2430: 
                   2431: }
                   2432: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
                   2433: 
                   2434: #
                   2435: #   Change the authentication method of a user.  Note that this may
                   2436: #   also implicitly change the user's password if, for example, the user is
                   2437: #   joining an existing authentication realm.  Known authentication realms at
                   2438: #   this time are:
                   2439: #    internal   - Purely internal password file (only loncapa knows this user)
                   2440: #    local      - Institutionally written authentication module.
                   2441: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
                   2442: #    kerb4      - kerberos version 4
                   2443: #    kerb5      - kerberos version 5
                   2444: #
                   2445: # Parameters:
                   2446: #    $cmd      - The command that got us here.
                   2447: #    $tail     - Tail of the command (remaining parameters).
                   2448: #    $client   - File descriptor connected to client.
                   2449: # Returns
                   2450: #     0        - Requested to exit, caller should shut down.
                   2451: #     1        - Continue processing.
                   2452: # Implicit inputs:
                   2453: #    The authentication systems describe above have their own forms of implicit
                   2454: #    input into the authentication process that are described above.
1.287     foxr     2455: # NOTE:
                   2456: #   This is also used to change the authentication credential values (e.g. passwd).
                   2457: #   
1.225     foxr     2458: #
                   2459: sub change_authentication_handler {
                   2460: 
                   2461:     my ($cmd, $tail, $client) = @_;
                   2462:    
                   2463:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
                   2464: 
                   2465:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2466:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
                   2467:     if ($udom ne $currentdomainid) {
                   2468: 	&Failure( $client, "not_right_domain\n", $client);
                   2469:     } else {
                   2470: 	
                   2471: 	chomp($npass);
                   2472: 	
                   2473: 	$npass=&unescape($npass);
1.261     foxr     2474: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
1.225     foxr     2475: 	my $passfilename = &password_path($udom, $uname);
                   2476: 	if ($passfilename) {	# Not allowed to create a new user!!
1.287     foxr     2477: 	    # If just changing the unix passwd. need to arrange to run
1.502     raeburn  2478: 	    # passwd since otherwise make_passwd_file will fail as 
                   2479: 	    # creation of unix authenticated users is no longer supported
                   2480:             # except from the command line, when running make_domain_coordinator.pl
1.287     foxr     2481: 
                   2482: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
                   2483: 		my $result = &change_unix_password($uname, $npass);
                   2484: 		&logthis("Result of password change for $uname: ".$result);
                   2485: 		if ($result eq "ok") {
1.518     raeburn  2486:                     &update_passwd_history($uname,$udom,$umode,'changeuserauth'); 
1.390     raeburn  2487: 		    &Reply($client, \$result);
1.288     albertel 2488: 		} else {
1.387     albertel 2489: 		    &Failure($client, \$result);
1.287     foxr     2490: 		}
1.288     albertel 2491: 	    } else {
1.518     raeburn  2492: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2493:                                              $passfilename,'changeuserauth');
1.287     foxr     2494: 		#
                   2495: 		#  If the current auth mode is internal, and the old auth mode was
                   2496: 		#  unix, or krb*,  and the user is an author for this domain,
                   2497: 		#  re-run manage_permissions for that role in order to be able
                   2498: 		#  to take ownership of the construction space back to www:www
                   2499: 		#
1.502     raeburn  2500: 
                   2501: 
1.387     albertel 2502: 		&Reply($client, \$result, $userinput);
1.261     foxr     2503: 	    }
                   2504: 	       
                   2505: 
1.225     foxr     2506: 	} else {	       
1.251     foxr     2507: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
1.225     foxr     2508: 	}
                   2509:     }
                   2510:     return 1;
                   2511: }
                   2512: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
                   2513: 
1.518     raeburn  2514: sub update_passwd_history {
                   2515:     my ($uname,$udom,$umode,$context) = @_;
                   2516:     my $proname=&propath($udom,$uname);
                   2517:     my $now = time;
                   2518:     if (open(my $fh,">>$proname/passwd.log")) {
                   2519:         print $fh "$now:$umode:$context\n";
                   2520:         close($fh);
                   2521:     }
                   2522:     return;
                   2523: }
                   2524: 
1.225     foxr     2525: #
                   2526: #   Determines if this is the home server for a user.  The home server
                   2527: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
                   2528: #   to do is determine if this file exists.
                   2529: #
                   2530: # Parameters:
                   2531: #    $cmd      - The command that got us here.
                   2532: #    $tail     - Tail of the command (remaining parameters).
                   2533: #    $client   - File descriptor connected to client.
                   2534: # Returns
                   2535: #     0        - Requested to exit, caller should shut down.
                   2536: #     1        - Continue processing.
                   2537: # Implicit inputs:
                   2538: #    The authentication systems describe above have their own forms of implicit
                   2539: #    input into the authentication process that are described above.
                   2540: #
                   2541: sub is_home_handler {
                   2542:     my ($cmd, $tail, $client) = @_;
                   2543:    
                   2544:     my $userinput  = "$cmd:$tail";
                   2545:    
                   2546:     my ($udom,$uname)=split(/:/,$tail);
                   2547:     chomp($uname);
                   2548:     my $passfile = &password_filename($udom, $uname);
                   2549:     if($passfile) {
                   2550: 	&Reply( $client, "found\n", $userinput);
                   2551:     } else {
                   2552: 	&Failure($client, "not_found\n", $userinput);
                   2553:     }
                   2554:     return 1;
                   2555: }
                   2556: &register_handler("home", \&is_home_handler, 0,1,0);
                   2557: 
                   2558: #
1.434     www      2559: #   Process an update request for a resource.
                   2560: #   A resource has been modified that we hold a subscription to.
1.225     foxr     2561: #   If the resource is not local, then we must update, or at least invalidate our
                   2562: #   cached copy of the resource. 
                   2563: # Parameters:
                   2564: #    $cmd      - The command that got us here.
                   2565: #    $tail     - Tail of the command (remaining parameters).
                   2566: #    $client   - File descriptor connected to client.
                   2567: # Returns
                   2568: #     0        - Requested to exit, caller should shut down.
                   2569: #     1        - Continue processing.
                   2570: # Implicit inputs:
                   2571: #    The authentication systems describe above have their own forms of implicit
                   2572: #    input into the authentication process that are described above.
                   2573: #
                   2574: sub update_resource_handler {
                   2575: 
                   2576:     my ($cmd, $tail, $client) = @_;
                   2577:    
                   2578:     my $userinput = "$cmd:$tail";
                   2579:    
                   2580:     my $fname= $tail;		# This allows interactive testing
                   2581: 
                   2582: 
                   2583:     my $ownership=ishome($fname);
                   2584:     if ($ownership eq 'not_owner') {
                   2585: 	if (-e $fname) {
1.434     www      2586:             # Delete preview file, if exists
                   2587:             unlink("$fname.tmp");
                   2588:             # Get usage stats
1.225     foxr     2589: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
                   2590: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
                   2591: 	    my $now=time;
                   2592: 	    my $since=$now-$atime;
1.434     www      2593:             # If the file has not been used within lonExpire seconds,
                   2594:             # unsubscribe from it and delete local copy
1.225     foxr     2595: 	    if ($since>$perlvar{'lonExpire'}) {
1.365     albertel 2596: 		my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
1.308     albertel 2597: 		&devalidate_meta_cache($fname);
1.225     foxr     2598: 		unlink("$fname");
1.334     albertel 2599: 		unlink("$fname.meta");
1.225     foxr     2600: 	    } else {
1.434     www      2601:             # Yes, this is in active use. Get a fresh copy. Since it might be in
                   2602:             # very active use and huge (like a movie), copy it to "in.transfer" filename first.
1.225     foxr     2603: 		my $transname="$fname.in.transfer";
1.365     albertel 2604: 		my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
1.225     foxr     2605: 		my $response;
1.537     raeburn  2606: # FIXME: cannot replicate files that take more than two minutes to transfer -- needs checking now 1200s timeout used
                   2607: # for LWP request.
                   2608: 		my $request=new HTTP::Request('GET',"$remoteurl");
                   2609:                 $response=&LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,0,1);
1.225     foxr     2610: 		if ($response->is_error()) {
1.455     www      2611: # FIXME: we should probably clean up here instead of just whine
1.225     foxr     2612: 		    unlink($transname);
                   2613: 		    my $message=$response->status_line;
                   2614: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2615: 		} else {
                   2616: 		    if ($remoteurl!~/\.meta$/) {
1.537     raeburn  2617: 			my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2618:                         my $mresponse = &LONCAPA::LWPReq::makerequest($clientname,$mrequest,$fname.'.meta',\%perlvar,120,0,1);
                   2619: 			if ($mresponse->is_error()) {
                   2620: 			    unlink($fname.'.meta');
1.225     foxr     2621: 			}
                   2622: 		    }
1.434     www      2623:                     # we successfully transfered, copy file over to real name
1.225     foxr     2624: 		    rename($transname,$fname);
1.308     albertel 2625: 		    &devalidate_meta_cache($fname);
1.225     foxr     2626: 		}
                   2627: 	    }
                   2628: 	    &Reply( $client, "ok\n", $userinput);
                   2629: 	} else {
                   2630: 	    &Failure($client, "not_found\n", $userinput);
                   2631: 	}
                   2632:     } else {
                   2633: 	&Failure($client, "rejected\n", $userinput);
                   2634:     }
                   2635:     return 1;
                   2636: }
                   2637: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
                   2638: 
1.308     albertel 2639: sub devalidate_meta_cache {
                   2640:     my ($url) = @_;
                   2641:     use Cache::Memcached;
                   2642:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.365     albertel 2643:     $url = &Apache::lonnet::declutter($url);
1.308     albertel 2644:     $url =~ s-\.meta$--;
                   2645:     my $id = &escape('meta:'.$url);
                   2646:     $memcache->delete($id);
                   2647: }
                   2648: 
1.225     foxr     2649: #
1.226     foxr     2650: #   Fetch a user file from a remote server to the user's home directory
                   2651: #   userfiles subdir.
1.225     foxr     2652: # Parameters:
                   2653: #    $cmd      - The command that got us here.
                   2654: #    $tail     - Tail of the command (remaining parameters).
                   2655: #    $client   - File descriptor connected to client.
                   2656: # Returns
                   2657: #     0        - Requested to exit, caller should shut down.
                   2658: #     1        - Continue processing.
                   2659: #
                   2660: sub fetch_user_file_handler {
                   2661: 
                   2662:     my ($cmd, $tail, $client) = @_;
                   2663: 
                   2664:     my $userinput = "$cmd:$tail";
                   2665:     my $fname           = $tail;
1.232     foxr     2666:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1.225     foxr     2667:     my $udir=&propath($udom,$uname).'/userfiles';
                   2668:     unless (-e $udir) {
                   2669: 	mkdir($udir,0770); 
                   2670:     }
1.232     foxr     2671:     Debug("fetch user file for $fname");
1.225     foxr     2672:     if (-e $udir) {
                   2673: 	$ufile=~s/^[\.\~]+//;
1.232     foxr     2674: 
                   2675: 	# IF necessary, create the path right down to the file.
                   2676: 	# Note that any regular files in the way of this path are
                   2677: 	# wiped out to deal with some earlier folly of mine.
                   2678: 
1.267     raeburn  2679: 	if (!&mkpath($udir.'/'.$ufile)) {
1.264     albertel 2680: 	    &Failure($client, "unable_to_create\n", $userinput);	    
1.232     foxr     2681: 	}
                   2682: 
1.225     foxr     2683: 	my $destname=$udir.'/'.$ufile;
                   2684: 	my $transname=$udir.'/'.$ufile.'.in.transit';
1.476     raeburn  2685:         my $clientprotocol=$Apache::lonnet::protocol{$clientname};
                   2686:         $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.486     raeburn  2687: 	my $clienthost = &Apache::lonnet::hostname($clientname);
                   2688: 	my $remoteurl=$clientprotocol.'://'.$clienthost.'/userfiles/'.$fname;
1.225     foxr     2689: 	my $response;
1.232     foxr     2690: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
1.537     raeburn  2691: 	my $request=new HTTP::Request('GET',"$remoteurl");
                   2692:         my $verifycert = 1;
                   2693:         my @machine_ids = &Apache::lonnet::current_machine_ids();
                   2694:         if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   2695:             $verifycert = 0;
                   2696:         }
                   2697:         $response = &LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,$verifycert);
1.225     foxr     2698: 	if ($response->is_error()) {
                   2699: 	    unlink($transname);
                   2700: 	    my $message=$response->status_line;
                   2701: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2702: 	    &Failure($client, "failed\n", $userinput);
                   2703: 	} else {
1.232     foxr     2704: 	    Debug("Renaming $transname to $destname");
1.225     foxr     2705: 	    if (!rename($transname,$destname)) {
                   2706: 		&logthis("Unable to move $transname to $destname");
                   2707: 		unlink($transname);
                   2708: 		&Failure($client, "failed\n", $userinput);
                   2709: 	    } else {
1.495     raeburn  2710:                 if ($fname =~ /^default.+\.(page|sequence)$/) {
                   2711:                     my ($major,$minor) = split(/\./,$clientversion);
                   2712:                     if (($major < 2) || ($major == 2 && $minor < 11)) {
                   2713:                         my $now = time;
                   2714:                         &Apache::lonnet::do_cache_new('crschange',$udom.'_'.$uname,$now,600);
                   2715:                         my $key = &escape('internal.contentchange');
                   2716:                         my $what = "$key=$now";
                   2717:                         my $hashref = &tie_user_hash($udom,$uname,'environment',
                   2718:                                                      &GDBM_WRCREAT(),"P",$what);
                   2719:                         if ($hashref) {
                   2720:                             $hashref->{$key}=$now;
                   2721:                             if (!&untie_user_hash($hashref)) {
                   2722:                                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   2723:                                          "when updating internal.contentchange");
                   2724:                             }
                   2725:                         }
                   2726:                     }
                   2727:                 }
1.225     foxr     2728: 		&Reply($client, "ok\n", $userinput);
                   2729: 	    }
                   2730: 	}   
                   2731:     } else {
                   2732: 	&Failure($client, "not_home\n", $userinput);
                   2733:     }
                   2734:     return 1;
                   2735: }
                   2736: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
                   2737: 
1.226     foxr     2738: #
                   2739: #   Remove a file from a user's home directory userfiles subdirectory.
                   2740: # Parameters:
                   2741: #    cmd   - the Lond request keyword that got us here.
                   2742: #    tail  - the part of the command past the keyword.
                   2743: #    client- File descriptor connected with the client.
                   2744: #
                   2745: # Returns:
                   2746: #    1    - Continue processing.
                   2747: sub remove_user_file_handler {
                   2748:     my ($cmd, $tail, $client) = @_;
                   2749: 
                   2750:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2751: 
                   2752:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2753:     if ($ufile =~m|/\.\./|) {
                   2754: 	# any files paths with /../ in them refuse 
                   2755: 	# to deal with
                   2756: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2757:     } else {
                   2758: 	my $udir = &propath($udom,$uname);
                   2759: 	if (-e $udir) {
                   2760: 	    my $file=$udir.'/userfiles/'.$ufile;
                   2761: 	    if (-e $file) {
1.253     foxr     2762: 		#
                   2763: 		#   If the file is a regular file unlink is fine...
1.520     raeburn  2764: 		#   However it's possible the client wants a dir 
                   2765: 		#   removed, in which case rmdir is more appropriate.
                   2766: 		#   Note: rmdir will only remove an empty directory.
1.253     foxr     2767: 		#
1.240     banghart 2768: 	        if (-f $file){
1.241     albertel 2769: 		    unlink($file);
1.520     raeburn  2770:                     # for html files remove the associated .bak file 
                   2771:                     # which may have been created by the editor.
                   2772:                     if ($ufile =~ m{^((docs|supplemental)/(?:\d+|default)/\d+(?:|/.+)/)[^/]+\.x?html?$}i) {
                   2773:                         my $path = $1;
                   2774:                         if (-e $file.'.bak') {
                   2775:                             unlink($file.'.bak');
                   2776:                         }
                   2777:                     }
1.241     albertel 2778: 		} elsif(-d $file) {
                   2779: 		    rmdir($file);
1.240     banghart 2780: 		}
1.226     foxr     2781: 		if (-e $file) {
1.253     foxr     2782: 		    #  File is still there after we deleted it ?!?
                   2783: 
1.226     foxr     2784: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2785: 		} else {
                   2786: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2787: 		}
                   2788: 	    } else {
                   2789: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2790: 	    }
                   2791: 	} else {
                   2792: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2793: 	}
                   2794:     }
                   2795:     return 1;
                   2796: }
                   2797: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
                   2798: 
1.236     albertel 2799: #
                   2800: #   make a directory in a user's home directory userfiles subdirectory.
                   2801: # Parameters:
                   2802: #    cmd   - the Lond request keyword that got us here.
                   2803: #    tail  - the part of the command past the keyword.
                   2804: #    client- File descriptor connected with the client.
                   2805: #
                   2806: # Returns:
                   2807: #    1    - Continue processing.
                   2808: sub mkdir_user_file_handler {
                   2809:     my ($cmd, $tail, $client) = @_;
                   2810: 
                   2811:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2812:     $dir=&unescape($dir);
                   2813:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2814:     if ($ufile =~m|/\.\./|) {
                   2815: 	# any files paths with /../ in them refuse 
                   2816: 	# to deal with
                   2817: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2818:     } else {
                   2819: 	my $udir = &propath($udom,$uname);
                   2820: 	if (-e $udir) {
1.264     albertel 2821: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
                   2822: 	    if (!&mkpath($newdir)) {
                   2823: 		&Failure($client, "failed\n", "$cmd:$tail");
1.236     albertel 2824: 	    }
1.264     albertel 2825: 	    &Reply($client, "ok\n", "$cmd:$tail");
1.236     albertel 2826: 	} else {
                   2827: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2828: 	}
                   2829:     }
                   2830:     return 1;
                   2831: }
                   2832: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
                   2833: 
1.237     albertel 2834: #
                   2835: #   rename a file in a user's home directory userfiles subdirectory.
                   2836: # Parameters:
                   2837: #    cmd   - the Lond request keyword that got us here.
                   2838: #    tail  - the part of the command past the keyword.
                   2839: #    client- File descriptor connected with the client.
                   2840: #
                   2841: # Returns:
                   2842: #    1    - Continue processing.
                   2843: sub rename_user_file_handler {
                   2844:     my ($cmd, $tail, $client) = @_;
                   2845: 
                   2846:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
                   2847:     $old=&unescape($old);
                   2848:     $new=&unescape($new);
                   2849:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
                   2850: 	# any files paths with /../ in them refuse to deal with
                   2851: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2852:     } else {
                   2853: 	my $udir = &propath($udom,$uname);
                   2854: 	if (-e $udir) {
                   2855: 	    my $oldfile=$udir.'/userfiles/'.$old;
                   2856: 	    my $newfile=$udir.'/userfiles/'.$new;
                   2857: 	    if (-e $newfile) {
                   2858: 		&Failure($client, "exists\n", "$cmd:$tail");
                   2859: 	    } elsif (! -e $oldfile) {
                   2860: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2861: 	    } else {
                   2862: 		if (!rename($oldfile,$newfile)) {
                   2863: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2864: 		} else {
                   2865: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2866: 		}
                   2867: 	    }
                   2868: 	} else {
                   2869: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2870: 	}
                   2871:     }
                   2872:     return 1;
                   2873: }
                   2874: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
                   2875: 
1.227     foxr     2876: #
1.382     albertel 2877: #  Checks if the specified user has an active session on the server
                   2878: #  return ok if so, not_found if not
                   2879: #
                   2880: # Parameters:
                   2881: #   cmd      - The request keyword that dispatched to tus.
                   2882: #   tail     - The tail of the request (colon separated parameters).
                   2883: #   client   - Filehandle open on the client.
                   2884: # Return:
                   2885: #    1.
                   2886: sub user_has_session_handler {
                   2887:     my ($cmd, $tail, $client) = @_;
                   2888: 
                   2889:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
                   2890:     
                   2891:     opendir(DIR,$perlvar{'lonIDsDir'});
                   2892:     my $filename;
                   2893:     while ($filename=readdir(DIR)) {
                   2894: 	last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
                   2895:     }
                   2896:     if ($filename) {
                   2897: 	&Reply($client, "ok\n", "$cmd:$tail");
                   2898:     } else {
                   2899: 	&Failure($client, "not_found\n", "$cmd:$tail");
                   2900:     }
                   2901:     return 1;
                   2902: 
                   2903: }
                   2904: &register_handler("userhassession", \&user_has_session_handler, 0,1,0);
                   2905: 
                   2906: #
1.263     albertel 2907: #  Authenticate access to a user file by checking that the token the user's 
                   2908: #  passed also exists in their session file
1.227     foxr     2909: #
                   2910: # Parameters:
                   2911: #   cmd      - The request keyword that dispatched to tus.
                   2912: #   tail     - The tail of the request (colon separated parameters).
                   2913: #   client   - Filehandle open on the client.
                   2914: # Return:
                   2915: #    1.
                   2916: sub token_auth_user_file_handler {
                   2917:     my ($cmd, $tail, $client) = @_;
                   2918: 
                   2919:     my ($fname, $session) = split(/:/, $tail);
                   2920:     
                   2921:     chomp($session);
1.393     raeburn  2922:     my $reply="non_auth";
1.343     albertel 2923:     my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
                   2924:     if (open(ENVIN,"$file")) {
1.332     albertel 2925: 	flock(ENVIN,LOCK_SH);
1.343     albertel 2926: 	tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
                   2927: 	if (exists($disk_env{"userfile.$fname"})) {
1.393     raeburn  2928: 	    $reply="ok";
1.343     albertel 2929: 	} else {
                   2930: 	    foreach my $envname (keys(%disk_env)) {
                   2931: 		if ($envname=~ m|^userfile\.\Q$fname\E|) {
1.393     raeburn  2932: 		    $reply="ok";
1.343     albertel 2933: 		    last;
                   2934: 		}
                   2935: 	    }
1.227     foxr     2936: 	}
1.343     albertel 2937: 	untie(%disk_env);
1.227     foxr     2938: 	close(ENVIN);
1.387     albertel 2939: 	&Reply($client, \$reply, "$cmd:$tail");
1.227     foxr     2940:     } else {
                   2941: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
                   2942:     }
                   2943:     return 1;
                   2944: 
                   2945: }
                   2946: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229     foxr     2947: 
                   2948: #
                   2949: #   Unsubscribe from a resource.
                   2950: #
                   2951: # Parameters:
                   2952: #    $cmd      - The command that got us here.
                   2953: #    $tail     - Tail of the command (remaining parameters).
                   2954: #    $client   - File descriptor connected to client.
                   2955: # Returns
                   2956: #     0        - Requested to exit, caller should shut down.
                   2957: #     1        - Continue processing.
                   2958: #
                   2959: sub unsubscribe_handler {
                   2960:     my ($cmd, $tail, $client) = @_;
                   2961: 
                   2962:     my $userinput= "$cmd:$tail";
                   2963:     
                   2964:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
                   2965: 
                   2966:     &Debug("Unsubscribing $fname");
                   2967:     if (-e $fname) {
                   2968: 	&Debug("Exists");
                   2969: 	&Reply($client, &unsub($fname,$clientip), $userinput);
                   2970:     } else {
                   2971: 	&Failure($client, "not_found\n", $userinput);
                   2972:     }
                   2973:     return 1;
                   2974: }
                   2975: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
1.263     albertel 2976: 
1.230     foxr     2977: #   Subscribe to a resource
                   2978: #
                   2979: # Parameters:
                   2980: #    $cmd      - The command that got us here.
                   2981: #    $tail     - Tail of the command (remaining parameters).
                   2982: #    $client   - File descriptor connected to client.
                   2983: # Returns
                   2984: #     0        - Requested to exit, caller should shut down.
                   2985: #     1        - Continue processing.
                   2986: #
                   2987: sub subscribe_handler {
                   2988:     my ($cmd, $tail, $client)= @_;
                   2989: 
                   2990:     my $userinput  = "$cmd:$tail";
                   2991: 
                   2992:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
                   2993: 
                   2994:     return 1;
                   2995: }
                   2996: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
                   2997: 
                   2998: #
1.379     albertel 2999: #   Determine the latest version of a resource (it looks for the highest
                   3000: #   past version and then returns that +1)
1.230     foxr     3001: #
                   3002: # Parameters:
                   3003: #    $cmd      - The command that got us here.
                   3004: #    $tail     - Tail of the command (remaining parameters).
1.379     albertel 3005: #                 (Should consist of an absolute path to a file)
1.230     foxr     3006: #    $client   - File descriptor connected to client.
                   3007: # Returns
                   3008: #     0        - Requested to exit, caller should shut down.
                   3009: #     1        - Continue processing.
                   3010: #
                   3011: sub current_version_handler {
                   3012:     my ($cmd, $tail, $client) = @_;
                   3013: 
                   3014:     my $userinput= "$cmd:$tail";
                   3015:    
                   3016:     my $fname   = $tail;
                   3017:     &Reply( $client, &currentversion($fname)."\n", $userinput);
                   3018:     return 1;
                   3019: 
                   3020: }
                   3021: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
                   3022: 
                   3023: #  Make an entry in a user's activity log.
                   3024: #
                   3025: # Parameters:
                   3026: #    $cmd      - The command that got us here.
                   3027: #    $tail     - Tail of the command (remaining parameters).
                   3028: #    $client   - File descriptor connected to client.
                   3029: # Returns
                   3030: #     0        - Requested to exit, caller should shut down.
                   3031: #     1        - Continue processing.
                   3032: #
                   3033: sub activity_log_handler {
                   3034:     my ($cmd, $tail, $client) = @_;
                   3035: 
                   3036: 
                   3037:     my $userinput= "$cmd:$tail";
                   3038: 
                   3039:     my ($udom,$uname,$what)=split(/:/,$tail);
                   3040:     chomp($what);
                   3041:     my $proname=&propath($udom,$uname);
                   3042:     my $now=time;
                   3043:     my $hfh;
                   3044:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
                   3045: 	print $hfh "$now:$clientname:$what\n";
                   3046: 	&Reply( $client, "ok\n", $userinput); 
                   3047:     } else {
                   3048: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
                   3049: 		 ."while attempting log\n", 
                   3050: 		 $userinput);
                   3051:     }
                   3052: 
                   3053:     return 1;
                   3054: }
1.263     albertel 3055: &register_handler("log", \&activity_log_handler, 0, 1, 0);
1.230     foxr     3056: 
                   3057: #
                   3058: #   Put a namespace entry in a user profile hash.
                   3059: #   My druthers would be for this to be an encrypted interaction too.
                   3060: #   anything that might be an inadvertent covert channel about either
                   3061: #   user authentication or user personal information....
                   3062: #
                   3063: # Parameters:
                   3064: #    $cmd      - The command that got us here.
                   3065: #    $tail     - Tail of the command (remaining parameters).
                   3066: #    $client   - File descriptor connected to client.
                   3067: # Returns
                   3068: #     0        - Requested to exit, caller should shut down.
                   3069: #     1        - Continue processing.
                   3070: #
                   3071: sub put_user_profile_entry {
                   3072:     my ($cmd, $tail, $client)  = @_;
1.229     foxr     3073: 
1.230     foxr     3074:     my $userinput = "$cmd:$tail";
                   3075:     
1.242     raeburn  3076:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
1.230     foxr     3077:     if ($namespace ne 'roles') {
                   3078: 	chomp($what);
                   3079: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3080: 				  &GDBM_WRCREAT(),"P",$what);
                   3081: 	if($hashref) {
                   3082: 	    my @pairs=split(/\&/,$what);
                   3083: 	    foreach my $pair (@pairs) {
                   3084: 		my ($key,$value)=split(/=/,$pair);
                   3085: 		$hashref->{$key}=$value;
                   3086: 	    }
1.311     albertel 3087: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3088: 		&Reply( $client, "ok\n", $userinput);
                   3089: 	    } else {
                   3090: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3091: 			"while attempting put\n", 
                   3092: 			$userinput);
                   3093: 	    }
                   3094: 	} else {
1.316     albertel 3095: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.230     foxr     3096: 		     "while attempting put\n", $userinput);
                   3097: 	}
                   3098:     } else {
                   3099:         &Failure( $client, "refused\n", $userinput);
                   3100:     }
                   3101:     
                   3102:     return 1;
                   3103: }
                   3104: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
                   3105: 
1.283     albertel 3106: #   Put a piece of new data in hash, returns error if entry already exists
                   3107: # Parameters:
                   3108: #    $cmd      - The command that got us here.
                   3109: #    $tail     - Tail of the command (remaining parameters).
                   3110: #    $client   - File descriptor connected to client.
                   3111: # Returns
                   3112: #     0        - Requested to exit, caller should shut down.
                   3113: #     1        - Continue processing.
                   3114: #
                   3115: sub newput_user_profile_entry {
                   3116:     my ($cmd, $tail, $client)  = @_;
                   3117: 
                   3118:     my $userinput = "$cmd:$tail";
                   3119: 
                   3120:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
                   3121:     if ($namespace eq 'roles') {
                   3122:         &Failure( $client, "refused\n", $userinput);
                   3123: 	return 1;
                   3124:     }
                   3125: 
                   3126:     chomp($what);
                   3127: 
                   3128:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3129: 				 &GDBM_WRCREAT(),"N",$what);
                   3130:     if(!$hashref) {
1.316     albertel 3131: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.283     albertel 3132: 		  "while attempting put\n", $userinput);
                   3133: 	return 1;
                   3134:     }
                   3135: 
                   3136:     my @pairs=split(/\&/,$what);
                   3137:     foreach my $pair (@pairs) {
                   3138: 	my ($key,$value)=split(/=/,$pair);
                   3139: 	if (exists($hashref->{$key})) {
1.513     raeburn  3140:             if (!&untie_user_hash($hashref)) {
                   3141:                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   3142:                          "while attempting newput - early out as key exists");
                   3143:             }
                   3144:             &Failure($client, "key_exists: ".$key."\n",$userinput);
                   3145:             return 1;
1.283     albertel 3146: 	}
                   3147:     }
                   3148: 
                   3149:     foreach my $pair (@pairs) {
                   3150: 	my ($key,$value)=split(/=/,$pair);
                   3151: 	$hashref->{$key}=$value;
                   3152:     }
                   3153: 
1.311     albertel 3154:     if (&untie_user_hash($hashref)) {
1.283     albertel 3155: 	&Reply( $client, "ok\n", $userinput);
                   3156:     } else {
                   3157: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3158: 		 "while attempting put\n", 
                   3159: 		 $userinput);
                   3160:     }
                   3161:     return 1;
                   3162: }
                   3163: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
                   3164: 
1.230     foxr     3165: # 
                   3166: #   Increment a profile entry in the user history file.
                   3167: #   The history contains keyword value pairs.  In this case,
                   3168: #   The value itself is a pair of numbers.  The first, the current value
                   3169: #   the second an increment that this function applies to the current
                   3170: #   value.
                   3171: #
                   3172: # Parameters:
                   3173: #    $cmd      - The command that got us here.
                   3174: #    $tail     - Tail of the command (remaining parameters).
                   3175: #    $client   - File descriptor connected to client.
                   3176: # Returns
                   3177: #     0        - Requested to exit, caller should shut down.
                   3178: #     1        - Continue processing.
                   3179: #
                   3180: sub increment_user_value_handler {
                   3181:     my ($cmd, $tail, $client) = @_;
                   3182:     
                   3183:     my $userinput   = "$cmd:$tail";
                   3184:     
                   3185:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
                   3186:     if ($namespace ne 'roles') {
                   3187:         chomp($what);
                   3188: 	my $hashref = &tie_user_hash($udom, $uname,
                   3189: 				     $namespace, &GDBM_WRCREAT(),
                   3190: 				     "P",$what);
                   3191: 	if ($hashref) {
                   3192: 	    my @pairs=split(/\&/,$what);
                   3193: 	    foreach my $pair (@pairs) {
                   3194: 		my ($key,$value)=split(/=/,$pair);
1.284     raeburn  3195:                 $value = &unescape($value);
1.230     foxr     3196: 		# We could check that we have a number...
                   3197: 		if (! defined($value) || $value eq '') {
                   3198: 		    $value = 1;
                   3199: 		}
                   3200: 		$hashref->{$key}+=$value;
1.284     raeburn  3201:                 if ($namespace eq 'nohist_resourcetracker') {
                   3202:                     if ($hashref->{$key} < 0) {
                   3203:                         $hashref->{$key} = 0;
                   3204:                     }
                   3205:                 }
1.230     foxr     3206: 	    }
1.311     albertel 3207: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3208: 		&Reply( $client, "ok\n", $userinput);
                   3209: 	    } else {
                   3210: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3211: 			 "while attempting inc\n", $userinput);
                   3212: 	    }
                   3213: 	} else {
                   3214: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3215: 		     "while attempting inc\n", $userinput);
                   3216: 	}
                   3217:     } else {
                   3218: 	&Failure($client, "refused\n", $userinput);
                   3219:     }
                   3220:     
                   3221:     return 1;
                   3222: }
                   3223: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
                   3224: 
                   3225: #
                   3226: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
                   3227: #   Each 'role' a user has implies a set of permissions.  Adding a new role
                   3228: #   for a person grants the permissions packaged with that role
                   3229: #   to that user when the role is selected.
                   3230: #
                   3231: # Parameters:
                   3232: #    $cmd       - The command string (rolesput).
                   3233: #    $tail      - The remainder of the request line.  For rolesput this
                   3234: #                 consists of a colon separated list that contains:
                   3235: #                 The domain and user that is granting the role (logged).
                   3236: #                 The domain and user that is getting the role.
                   3237: #                 The roles being granted as a set of & separated pairs.
                   3238: #                 each pair a key value pair.
                   3239: #    $client    - File descriptor connected to the client.
                   3240: # Returns:
                   3241: #     0         - If the daemon should exit
                   3242: #     1         - To continue processing.
                   3243: #
                   3244: #
                   3245: sub roles_put_handler {
                   3246:     my ($cmd, $tail, $client) = @_;
                   3247: 
                   3248:     my $userinput  = "$cmd:$tail";
                   3249: 
                   3250:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
                   3251:     
                   3252: 
                   3253:     my $namespace='roles';
                   3254:     chomp($what);
                   3255:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3256: 				 &GDBM_WRCREAT(), "P",
                   3257: 				 "$exedom:$exeuser:$what");
                   3258:     #
                   3259:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
                   3260:     #  handle is open for the minimal amount of time.  Since the flush
                   3261:     #  is done on close this improves the chances the log will be an un-
                   3262:     #  corrupted ordered thing.
                   3263:     if ($hashref) {
1.261     foxr     3264: 	my $pass_entry = &get_auth_type($udom, $uname);
                   3265: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
                   3266: 	$auth_type = $auth_type.":";
1.230     foxr     3267: 	my @pairs=split(/\&/,$what);
                   3268: 	foreach my $pair (@pairs) {
                   3269: 	    my ($key,$value)=split(/=/,$pair);
                   3270: 	    &manage_permissions($key, $udom, $uname,
1.260     foxr     3271: 			       $auth_type);
1.230     foxr     3272: 	    $hashref->{$key}=$value;
                   3273: 	}
1.311     albertel 3274: 	if (&untie_user_hash($hashref)) {
1.230     foxr     3275: 	    &Reply($client, "ok\n", $userinput);
                   3276: 	} else {
                   3277: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3278: 		     "while attempting rolesput\n", $userinput);
                   3279: 	}
                   3280:     } else {
                   3281: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3282: 		 "while attempting rolesput\n", $userinput);
                   3283:     }
                   3284:     return 1;
                   3285: }
                   3286: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
                   3287: 
                   3288: #
1.231     foxr     3289: #   Deletes (removes) a role for a user.   This is equivalent to removing
                   3290: #  a permissions package associated with the role from the user's profile.
                   3291: #
                   3292: # Parameters:
                   3293: #     $cmd                 - The command (rolesdel)
                   3294: #     $tail                - The remainder of the request line. This consists
                   3295: #                             of:
                   3296: #                             The domain and user requesting the change (logged)
                   3297: #                             The domain and user being changed.
                   3298: #                             The roles being revoked.  These are shipped to us
                   3299: #                             as a bunch of & separated role name keywords.
                   3300: #     $client              - The file handle open on the client.
                   3301: # Returns:
                   3302: #     1                    - Continue processing
                   3303: #     0                    - Exit.
                   3304: #
                   3305: sub roles_delete_handler {
                   3306:     my ($cmd, $tail, $client)  = @_;
                   3307: 
                   3308:     my $userinput    = "$cmd:$tail";
                   3309:    
                   3310:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
                   3311:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
                   3312: 	   "what = ".$what);
                   3313:     my $namespace='roles';
                   3314:     chomp($what);
                   3315:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3316: 				 &GDBM_WRCREAT(), "D",
                   3317: 				 "$exedom:$exeuser:$what");
                   3318:     
                   3319:     if ($hashref) {
                   3320: 	my @rolekeys=split(/\&/,$what);
                   3321: 	
                   3322: 	foreach my $key (@rolekeys) {
                   3323: 	    delete $hashref->{$key};
                   3324: 	}
1.315     albertel 3325: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3326: 	    &Reply($client, "ok\n", $userinput);
                   3327: 	} else {
                   3328: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3329: 		     "while attempting rolesdel\n", $userinput);
                   3330: 	}
                   3331:     } else {
                   3332:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3333: 		 "while attempting rolesdel\n", $userinput);
                   3334:     }
                   3335:     
                   3336:     return 1;
                   3337: }
                   3338: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
                   3339: 
                   3340: # Unencrypted get from a user's profile database.  See 
                   3341: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
                   3342: # This function retrieves a keyed item from a specific named database in the
                   3343: # user's directory.
                   3344: #
                   3345: # Parameters:
                   3346: #   $cmd             - Command request keyword (get).
                   3347: #   $tail            - Tail of the command.  This is a colon separated list
                   3348: #                      consisting of the domain and username that uniquely
                   3349: #                      identifies the profile,
                   3350: #                      The 'namespace' which selects the gdbm file to 
                   3351: #                      do the lookup in, 
                   3352: #                      & separated list of keys to lookup.  Note that
                   3353: #                      the values are returned as an & separated list too.
                   3354: #   $client          - File descriptor open on the client.
                   3355: # Returns:
                   3356: #   1       - Continue processing.
                   3357: #   0       - Exit.
                   3358: #
                   3359: sub get_profile_entry {
                   3360:     my ($cmd, $tail, $client) = @_;
                   3361: 
                   3362:     my $userinput= "$cmd:$tail";
                   3363:    
                   3364:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3365:     chomp($what);
1.255     foxr     3366: 
1.390     raeburn  3367: 
1.255     foxr     3368:     my $replystring = read_profile($udom, $uname, $namespace, $what);
                   3369:     my ($first) = split(/:/,$replystring);
                   3370:     if($first ne "error") {
1.387     albertel 3371: 	&Reply($client, \$replystring, $userinput);
1.231     foxr     3372:     } else {
1.255     foxr     3373: 	&Failure($client, $replystring." while attempting get\n", $userinput);
1.231     foxr     3374:     }
                   3375:     return 1;
1.255     foxr     3376: 
                   3377: 
1.231     foxr     3378: }
                   3379: &register_handler("get", \&get_profile_entry, 0,1,0);
                   3380: 
                   3381: #
                   3382: #  Process the encrypted get request.  Note that the request is sent
                   3383: #  in clear, but the reply is encrypted.  This is a small covert channel:
                   3384: #  information about the sensitive keys is given to the snooper.  Just not
                   3385: #  information about the values of the sensitive key.  Hmm if I wanted to
                   3386: #  know these I'd snoop for the egets. Get the profile item names from them
                   3387: #  and then issue a get for them since there's no enforcement of the
                   3388: #  requirement of an encrypted get for particular profile items.  If I
                   3389: #  were re-doing this, I'd force the request to be encrypted as well as the
                   3390: #  reply.  I'd also just enforce encrypted transactions for all gets since
                   3391: #  that would prevent any covert channel snooping.
                   3392: #
                   3393: #  Parameters:
                   3394: #     $cmd               - Command keyword of request (eget).
1.536     raeburn  3395: #     $tail              - Tail of the command.  See GetProfileEntry
                   3396: #                          for more information about this.
1.231     foxr     3397: #     $client            - File open on the client.
                   3398: #  Returns:
                   3399: #     1      - Continue processing
                   3400: #     0      - server should exit.
                   3401: sub get_profile_entry_encrypted {
                   3402:     my ($cmd, $tail, $client) = @_;
                   3403: 
                   3404:     my $userinput = "$cmd:$tail";
                   3405:    
1.339     albertel 3406:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
1.231     foxr     3407:     chomp($what);
1.255     foxr     3408:     my $qresult = read_profile($udom, $uname, $namespace, $what);
                   3409:     my ($first) = split(/:/, $qresult);
                   3410:     if($first ne "error") {
                   3411: 	
                   3412: 	if ($cipher) {
                   3413: 	    my $cmdlength=length($qresult);
                   3414: 	    $qresult.="         ";
                   3415: 	    my $encqresult='';
                   3416: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   3417: 		$encqresult.= unpack("H16", 
                   3418: 				     $cipher->encrypt(substr($qresult,
                   3419: 							     $encidx,
                   3420: 							     8)));
                   3421: 	    }
                   3422: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   3423: 	} else {
1.231     foxr     3424: 		&Failure( $client, "error:no_key\n", $userinput);
                   3425: 	    }
                   3426:     } else {
1.255     foxr     3427: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
                   3428: 
1.231     foxr     3429:     }
                   3430:     
                   3431:     return 1;
                   3432: }
1.255     foxr     3433: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263     albertel 3434: 
1.231     foxr     3435: #
                   3436: #   Deletes a key in a user profile database.
                   3437: #   
                   3438: #   Parameters:
                   3439: #       $cmd                  - Command keyword (del).
                   3440: #       $tail                 - Command tail.  IN this case a colon
                   3441: #                               separated list containing:
                   3442: #                               The domain and user that identifies uniquely
                   3443: #                               the identity of the user.
                   3444: #                               The profile namespace (name of the profile
                   3445: #                               database file).
                   3446: #                               & separated list of keywords to delete.
                   3447: #       $client              - File open on client socket.
                   3448: # Returns:
                   3449: #     1   - Continue processing
                   3450: #     0   - Exit server.
                   3451: #
                   3452: #
                   3453: sub delete_profile_entry {
                   3454:     my ($cmd, $tail, $client) = @_;
                   3455: 
                   3456:     my $userinput = "cmd:$tail";
                   3457: 
                   3458:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3459:     chomp($what);
                   3460:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3461: 				 &GDBM_WRCREAT(),
                   3462: 				 "D",$what);
                   3463:     if ($hashref) {
                   3464:         my @keys=split(/\&/,$what);
                   3465: 	foreach my $key (@keys) {
                   3466: 	    delete($hashref->{$key});
                   3467: 	}
1.315     albertel 3468: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3469: 	    &Reply($client, "ok\n", $userinput);
                   3470: 	} else {
                   3471: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3472: 		    "while attempting del\n", $userinput);
                   3473: 	}
                   3474:     } else {
                   3475: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3476: 		 "while attempting del\n", $userinput);
                   3477:     }
                   3478:     return 1;
                   3479: }
                   3480: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263     albertel 3481: 
1.231     foxr     3482: #
                   3483: #  List the set of keys that are defined in a profile database file.
                   3484: #  A successful reply from this will contain an & separated list of
                   3485: #  the keys. 
                   3486: # Parameters:
                   3487: #     $cmd              - Command request (keys).
                   3488: #     $tail             - Remainder of the request, a colon separated
                   3489: #                         list containing domain/user that identifies the
                   3490: #                         user being queried, and the database namespace
                   3491: #                         (database filename essentially).
                   3492: #     $client           - File open on the client.
                   3493: #  Returns:
                   3494: #    1    - Continue processing.
                   3495: #    0    - Exit the server.
                   3496: #
                   3497: sub get_profile_keys {
                   3498:     my ($cmd, $tail, $client) = @_;
                   3499: 
                   3500:     my $userinput = "$cmd:$tail";
                   3501: 
                   3502:     my ($udom,$uname,$namespace)=split(/:/,$tail);
                   3503:     my $qresult='';
                   3504:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3505: 				  &GDBM_READER());
                   3506:     if ($hashref) {
                   3507: 	foreach my $key (keys %$hashref) {
                   3508: 	    $qresult.="$key&";
                   3509: 	}
1.315     albertel 3510: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3511: 	    $qresult=~s/\&$//;
1.387     albertel 3512: 	    &Reply($client, \$qresult, $userinput);
1.231     foxr     3513: 	} else {
                   3514: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3515: 		    "while attempting keys\n", $userinput);
                   3516: 	}
                   3517:     } else {
                   3518: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3519: 		 "while attempting keys\n", $userinput);
                   3520:     }
                   3521:    
                   3522:     return 1;
                   3523: }
                   3524: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
                   3525: 
                   3526: #
                   3527: #   Dump the contents of a user profile database.
                   3528: #   Note that this constitutes a very large covert channel too since
                   3529: #   the dump will return sensitive information that is not encrypted.
                   3530: #   The naive security assumption is that the session negotiation ensures
                   3531: #   our client is trusted and I don't believe that's assured at present.
                   3532: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
                   3533: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
                   3534: # 
                   3535: #  Parameters:
                   3536: #     $cmd           - The command request keyword (currentdump).
                   3537: #     $tail          - Remainder of the request, consisting of a colon
                   3538: #                      separated list that has the domain/username and
                   3539: #                      the namespace to dump (database file).
                   3540: #     $client        - file open on the remote client.
                   3541: # Returns:
                   3542: #     1    - Continue processing.
                   3543: #     0    - Exit the server.
                   3544: #
                   3545: sub dump_profile_database {
                   3546:     my ($cmd, $tail, $client) = @_;
                   3547: 
1.494     droeschl 3548:     my $res = LONCAPA::Lond::dump_profile_database($tail);
                   3549: 
                   3550:     if ($res =~ /^error:/) {
                   3551:         Failure($client, \$res, "$cmd:$tail");
                   3552:     } else {
                   3553:         Reply($client, \$res, "$cmd:$tail");
                   3554:     }
                   3555: 
                   3556:     return 1;  
                   3557: 
                   3558:     #TODO remove 
1.231     foxr     3559:     my $userinput = "$cmd:$tail";
                   3560:    
                   3561:     my ($udom,$uname,$namespace) = split(/:/,$tail);
                   3562:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3563: 				 &GDBM_READER());
                   3564:     if ($hashref) {
                   3565: 	# Structure of %data:
                   3566: 	# $data{$symb}->{$parameter}=$value;
                   3567: 	# $data{$symb}->{'v.'.$parameter}=$version;
                   3568: 	# since $parameter will be unescaped, we do not
                   3569:  	# have to worry about silly parameter names...
                   3570: 	
                   3571:         my $qresult='';
                   3572: 	my %data = ();                     # A hash of anonymous hashes..
                   3573: 	while (my ($key,$value) = each(%$hashref)) {
                   3574: 	    my ($v,$symb,$param) = split(/:/,$key);
                   3575: 	    next if ($v eq 'version' || $symb eq 'keys');
                   3576: 	    next if (exists($data{$symb}) && 
                   3577: 		     exists($data{$symb}->{$param}) &&
                   3578: 		     $data{$symb}->{'v.'.$param} > $v);
                   3579: 	    $data{$symb}->{$param}=$value;
                   3580: 	    $data{$symb}->{'v.'.$param}=$v;
                   3581: 	}
1.311     albertel 3582: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3583: 	    while (my ($symb,$param_hash) = each(%data)) {
                   3584: 		while(my ($param,$value) = each (%$param_hash)){
                   3585: 		    next if ($param =~ /^v\./);       # Ignore versions...
                   3586: 		    #
                   3587: 		    #   Just dump the symb=value pairs separated by &
                   3588: 		    #
                   3589: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
                   3590: 		}
                   3591: 	    }
                   3592: 	    chop($qresult);
1.387     albertel 3593: 	    &Reply($client , \$qresult, $userinput);
1.231     foxr     3594: 	} else {
                   3595: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3596: 		     "while attempting currentdump\n", $userinput);
                   3597: 	}
                   3598:     } else {
                   3599: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3600: 		"while attempting currentdump\n", $userinput);
                   3601:     }
                   3602: 
                   3603:     return 1;
                   3604: }
                   3605: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
                   3606: 
                   3607: #
                   3608: #   Dump a profile database with an optional regular expression
                   3609: #   to match against the keys.  In this dump, no effort is made
                   3610: #   to separate symb from version information. Presumably the
                   3611: #   databases that are dumped by this command are of a different
                   3612: #   structure.  Need to look at this and improve the documentation of
                   3613: #   both this and the currentdump handler.
                   3614: # Parameters:
                   3615: #    $cmd                     - The command keyword.
                   3616: #    $tail                    - All of the characters after the $cmd:
                   3617: #                               These are expected to be a colon
                   3618: #                               separated list containing:
                   3619: #                               domain/user - identifying the user.
                   3620: #                               namespace   - identifying the database.
                   3621: #                               regexp      - optional regular expression
                   3622: #                                             that is matched against
                   3623: #                                             database keywords to do
                   3624: #                                             selective dumps.
1.488     raeburn  3625: #                               range       - optional range of entries
                   3626: #                                             e.g., 10-20 would return the
                   3627: #                                             10th to 19th items, etc.  
1.231     foxr     3628: #   $client                   - Channel open on the client.
                   3629: # Returns:
                   3630: #    1    - Continue processing.
                   3631: # Side effects:
                   3632: #    response is written to $client.
                   3633: #
                   3634: sub dump_with_regexp {
                   3635:     my ($cmd, $tail, $client) = @_;
                   3636: 
1.494     droeschl 3637:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
1.490     droeschl 3638:     
                   3639:     if ($res =~ /^error:/) {
                   3640:         Failure($client, \$res, "$cmd:$tail");
                   3641:     } else {
                   3642:         Reply($client, \$res, "$cmd:$tail");
                   3643:     }
1.231     foxr     3644: 
                   3645:     return 1;
                   3646: }
                   3647: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
                   3648: 
                   3649: #  Store a set of key=value pairs associated with a versioned name.
                   3650: #
                   3651: #  Parameters:
                   3652: #    $cmd                - Request command keyword.
                   3653: #    $tail               - Tail of the request.  This is a colon
                   3654: #                          separated list containing:
                   3655: #                          domain/user - User and authentication domain.
                   3656: #                          namespace   - Name of the database being modified
                   3657: #                          rid         - Resource keyword to modify.
                   3658: #                          what        - new value associated with rid.
1.512     raeburn  3659: #                          laststore   - (optional) version=timestamp
                   3660: #                                        for most recent transaction for rid
                   3661: #                                        in namespace, when cstore was called
1.231     foxr     3662: #
                   3663: #    $client             - Socket open on the client.
                   3664: #
                   3665: #
                   3666: #  Returns:
                   3667: #      1 (keep on processing).
                   3668: #  Side-Effects:
                   3669: #    Writes to the client
1.512     raeburn  3670: #    Successful storage will cause either 'ok', or, if $laststore was included
                   3671: #    in the tail of the request, and the version number for the last transaction
                   3672: #    is larger than the version in $laststore, delay:$numtrans , where $numtrans
                   3673: #    is the number of store evevnts recorded for rid in namespace since
                   3674: #    lonnet::store() was called by the client.
                   3675: #
1.231     foxr     3676: sub store_handler {
                   3677:     my ($cmd, $tail, $client) = @_;
                   3678:  
                   3679:     my $userinput = "$cmd:$tail";
1.512     raeburn  3680:     chomp($tail);
                   3681:     my ($udom,$uname,$namespace,$rid,$what,$laststore) =split(/:/,$tail);
1.231     foxr     3682:     if ($namespace ne 'roles') {
                   3683: 
                   3684: 	my @pairs=split(/\&/,$what);
                   3685: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
1.268     albertel 3686: 				       &GDBM_WRCREAT(), "S",
1.231     foxr     3687: 				       "$rid:$what");
                   3688: 	if ($hashref) {
                   3689: 	    my $now = time;
1.512     raeburn  3690:             my $numtrans;
                   3691:             if ($laststore) {
                   3692:                 my ($previousversion,$previoustime) = split(/\=/,$laststore);
                   3693:                 my ($lastversion,$lasttime) = (0,0);
                   3694:                 $lastversion = $hashref->{"version:$rid"};
                   3695:                 if ($lastversion) {
                   3696:                     $lasttime = $hashref->{"$lastversion:$rid:timestamp"};
                   3697:                 }
                   3698:                 if (($previousversion) && ($previousversion !~ /\D/)) {
                   3699:                     if (($lastversion > $previousversion) && ($lasttime >= $previoustime)) {
                   3700:                         $numtrans = $lastversion - $previousversion;
                   3701:                     }
                   3702:                 } elsif ($lastversion) {
                   3703:                     $numtrans = $lastversion;
                   3704:                 }
                   3705:                 if ($numtrans) {
                   3706:                     $numtrans =~ s/D//g;
                   3707:                 }
                   3708:             }
1.231     foxr     3709: 	    $hashref->{"version:$rid"}++;
                   3710: 	    my $version=$hashref->{"version:$rid"};
                   3711: 	    my $allkeys=''; 
                   3712: 	    foreach my $pair (@pairs) {
                   3713: 		my ($key,$value)=split(/=/,$pair);
                   3714: 		$allkeys.=$key.':';
                   3715: 		$hashref->{"$version:$rid:$key"}=$value;
                   3716: 	    }
                   3717: 	    $hashref->{"$version:$rid:timestamp"}=$now;
                   3718: 	    $allkeys.='timestamp';
                   3719: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
1.311     albertel 3720: 	    if (&untie_user_hash($hashref)) {
1.512     raeburn  3721:                 my $msg = 'ok';
                   3722:                 if ($numtrans) {
                   3723:                     $msg = 'delay:'.$numtrans;
                   3724:                 }
                   3725: 		&Reply($client, "$msg\n", $userinput);
1.231     foxr     3726: 	    } else {
                   3727: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3728: 			"while attempting store\n", $userinput);
                   3729: 	    }
                   3730: 	} else {
                   3731: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3732: 		     "while attempting store\n", $userinput);
                   3733: 	}
                   3734:     } else {
                   3735: 	&Failure($client, "refused\n", $userinput);
                   3736:     }
                   3737: 
                   3738:     return 1;
                   3739: }
                   3740: &register_handler("store", \&store_handler, 0, 1, 0);
1.263     albertel 3741: 
1.323     albertel 3742: #  Modify a set of key=value pairs associated with a versioned name.
                   3743: #
                   3744: #  Parameters:
                   3745: #    $cmd                - Request command keyword.
                   3746: #    $tail               - Tail of the request.  This is a colon
                   3747: #                          separated list containing:
                   3748: #                          domain/user - User and authentication domain.
                   3749: #                          namespace   - Name of the database being modified
                   3750: #                          rid         - Resource keyword to modify.
                   3751: #                          v           - Version item to modify
                   3752: #                          what        - new value associated with rid.
                   3753: #
                   3754: #    $client             - Socket open on the client.
                   3755: #
                   3756: #
                   3757: #  Returns:
                   3758: #      1 (keep on processing).
                   3759: #  Side-Effects:
                   3760: #    Writes to the client
                   3761: sub putstore_handler {
                   3762:     my ($cmd, $tail, $client) = @_;
                   3763:  
                   3764:     my $userinput = "$cmd:$tail";
                   3765: 
                   3766:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
                   3767:     if ($namespace ne 'roles') {
                   3768: 
                   3769: 	chomp($what);
                   3770: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
                   3771: 				       &GDBM_WRCREAT(), "M",
                   3772: 				       "$rid:$v:$what");
                   3773: 	if ($hashref) {
                   3774: 	    my $now = time;
                   3775: 	    my %data = &hash_extract($what);
                   3776: 	    my @allkeys;
                   3777: 	    while (my($key,$value) = each(%data)) {
                   3778: 		push(@allkeys,$key);
                   3779: 		$hashref->{"$v:$rid:$key"} = $value;
                   3780: 	    }
                   3781: 	    my $allkeys = join(':',@allkeys);
                   3782: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
                   3783: 
                   3784: 	    if (&untie_user_hash($hashref)) {
                   3785: 		&Reply($client, "ok\n", $userinput);
                   3786: 	    } else {
                   3787: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3788: 			"while attempting store\n", $userinput);
                   3789: 	    }
                   3790: 	} else {
                   3791: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3792: 		     "while attempting store\n", $userinput);
                   3793: 	}
                   3794:     } else {
                   3795: 	&Failure($client, "refused\n", $userinput);
                   3796:     }
                   3797: 
                   3798:     return 1;
                   3799: }
                   3800: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
                   3801: 
                   3802: sub hash_extract {
                   3803:     my ($str)=@_;
                   3804:     my %hash;
                   3805:     foreach my $pair (split(/\&/,$str)) {
                   3806: 	my ($key,$value)=split(/=/,$pair);
                   3807: 	$hash{$key}=$value;
                   3808:     }
                   3809:     return (%hash);
                   3810: }
                   3811: sub hash_to_str {
                   3812:     my ($hash_ref)=@_;
                   3813:     my $str;
                   3814:     foreach my $key (keys(%$hash_ref)) {
                   3815: 	$str.=$key.'='.$hash_ref->{$key}.'&';
                   3816:     }
                   3817:     $str=~s/\&$//;
                   3818:     return $str;
                   3819: }
                   3820: 
1.231     foxr     3821: #
                   3822: #  Dump out all versions of a resource that has key=value pairs associated
                   3823: # with it for each version.  These resources are built up via the store
                   3824: # command.
                   3825: #
                   3826: #  Parameters:
                   3827: #     $cmd               - Command keyword.
                   3828: #     $tail              - Remainder of the request which consists of:
                   3829: #                          domain/user   - User and auth. domain.
                   3830: #                          namespace     - name of resource database.
                   3831: #                          rid           - Resource id.
                   3832: #    $client             - socket open on the client.
                   3833: #
                   3834: # Returns:
                   3835: #      1  indicating the caller should not yet exit.
                   3836: # Side-effects:
                   3837: #   Writes a reply to the client.
                   3838: #   The reply is a string of the following shape:
                   3839: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
                   3840: #    Where the 1 above represents version 1.
                   3841: #    this continues for all pairs of keys in all versions.
                   3842: #
                   3843: #
                   3844: #    
                   3845: #
                   3846: sub restore_handler {
                   3847:     my ($cmd, $tail, $client) = @_;
                   3848: 
                   3849:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
1.351     banghart 3850:     my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
1.352     albertel 3851:     $namespace=~s/\//\_/g;
1.350     albertel 3852:     $namespace = &LONCAPA::clean_username($namespace);
1.349     albertel 3853: 
1.231     foxr     3854:     chomp($rid);
                   3855:     my $qresult='';
1.309     albertel 3856:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
                   3857:     if ($hashref) {
                   3858: 	my $version=$hashref->{"version:$rid"};
1.231     foxr     3859: 	$qresult.="version=$version&";
                   3860: 	my $scope;
                   3861: 	for ($scope=1;$scope<=$version;$scope++) {
1.309     albertel 3862: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
1.231     foxr     3863: 	    my @keys=split(/:/,$vkeys);
                   3864: 	    my $key;
                   3865: 	    $qresult.="$scope:keys=$vkeys&";
                   3866: 	    foreach $key (@keys) {
1.309     albertel 3867: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
1.231     foxr     3868: 	    }                                  
                   3869: 	}
1.311     albertel 3870: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3871: 	    $qresult=~s/\&$//;
1.387     albertel 3872: 	    &Reply( $client, \$qresult, $userinput);
1.231     foxr     3873: 	} else {
                   3874: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3875: 		    "while attempting restore\n", $userinput);
                   3876: 	}
                   3877:     } else {
                   3878: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3879: 		"while attempting restore\n", $userinput);
                   3880:     }
                   3881:   
                   3882:     return 1;
                   3883: 
                   3884: 
                   3885: }
                   3886: &register_handler("restore", \&restore_handler, 0,1,0);
1.234     foxr     3887: 
                   3888: #
1.324     raeburn  3889: #   Add a chat message to a synchronous discussion board.
1.234     foxr     3890: #
                   3891: # Parameters:
                   3892: #    $cmd                - Request keyword.
                   3893: #    $tail               - Tail of the command. A colon separated list
                   3894: #                          containing:
                   3895: #                          cdom    - Domain on which the chat board lives
1.324     raeburn  3896: #                          cnum    - Course containing the chat board.
                   3897: #                          newpost - Body of the posting.
                   3898: #                          group   - Optional group, if chat board is only 
                   3899: #                                    accessible in a group within the course 
1.234     foxr     3900: #   $client              - Socket open on the client.
                   3901: # Returns:
                   3902: #   1    - Indicating caller should keep on processing.
                   3903: #
                   3904: # Side-effects:
                   3905: #   writes a reply to the client.
                   3906: #
                   3907: #
                   3908: sub send_chat_handler {
                   3909:     my ($cmd, $tail, $client) = @_;
                   3910: 
                   3911:     
                   3912:     my $userinput = "$cmd:$tail";
                   3913: 
1.324     raeburn  3914:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
                   3915:     &chat_add($cdom,$cnum,$newpost,$group);
1.234     foxr     3916:     &Reply($client, "ok\n", $userinput);
                   3917: 
                   3918:     return 1;
                   3919: }
                   3920: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263     albertel 3921: 
1.234     foxr     3922: #
1.324     raeburn  3923: #   Retrieve the set of chat messages from a discussion board.
1.234     foxr     3924: #
                   3925: #  Parameters:
                   3926: #    $cmd             - Command keyword that initiated the request.
                   3927: #    $tail            - Remainder of the request after the command
                   3928: #                       keyword.  In this case a colon separated list of
                   3929: #                       chat domain    - Which discussion board.
                   3930: #                       chat id        - Discussion thread(?)
                   3931: #                       domain/user    - Authentication domain and username
                   3932: #                                        of the requesting person.
1.324     raeburn  3933: #                       group          - Optional course group containing
                   3934: #                                        the board.      
1.234     foxr     3935: #   $client           - Socket open on the client program.
                   3936: # Returns:
                   3937: #    1     - continue processing
                   3938: # Side effects:
                   3939: #    Response is written to the client.
                   3940: #
                   3941: sub retrieve_chat_handler {
                   3942:     my ($cmd, $tail, $client) = @_;
                   3943: 
                   3944: 
                   3945:     my $userinput = "$cmd:$tail";
                   3946: 
1.324     raeburn  3947:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
1.234     foxr     3948:     my $reply='';
1.324     raeburn  3949:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
1.234     foxr     3950: 	$reply.=&escape($_).':';
                   3951:     }
                   3952:     $reply=~s/\:$//;
1.387     albertel 3953:     &Reply($client, \$reply, $userinput);
1.234     foxr     3954: 
                   3955: 
                   3956:     return 1;
                   3957: }
                   3958: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
                   3959: 
                   3960: #
                   3961: #  Initiate a query of an sql database.  SQL query repsonses get put in
                   3962: #  a file for later retrieval.  This prevents sql query results from
                   3963: #  bottlenecking the system.  Note that with loncnew, perhaps this is
                   3964: #  less of an issue since multiple outstanding requests can be concurrently
                   3965: #  serviced.
                   3966: #
                   3967: #  Parameters:
1.535     raeburn  3968: #     $cmd       - Command keyword that initiated the request.
1.234     foxr     3969: #     $tail      - Remainder of the command after the keyword.
                   3970: #                  For this function, this consists of a query and
                   3971: #                  3 arguments that are self-documentingly labelled
                   3972: #                  in the original arg1, arg2, arg3.
                   3973: #     $client    - Socket open on the client.
                   3974: # Return:
                   3975: #    1   - Indicating processing should continue.
                   3976: # Side-effects:
                   3977: #    a reply is written to $client.
                   3978: #
                   3979: sub send_query_handler {
                   3980:     my ($cmd, $tail, $client) = @_;
                   3981: 
                   3982:     my $userinput = "$cmd:$tail";
                   3983: 
                   3984:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
                   3985:     $query=~s/\n*$//g;
1.534     raeburn  3986:     if (($query eq 'usersearch') || ($query eq 'instdirsearch')) {
                   3987:         my $usersearchconf = &get_usersearch_config($currentdomainid,'directorysrch');
                   3988:         my $earlyout;
                   3989:         if (ref($usersearchconf) eq 'HASH') {
                   3990:             if ($currentdomainid eq $clienthomedom) {
                   3991:                 if ($query eq 'usersearch') {
                   3992:                     if ($usersearchconf->{'lcavailable'} eq '0') {
                   3993:                         $earlyout = 1;
                   3994:                     }
                   3995:                 } else {
                   3996:                     if ($usersearchconf->{'available'} eq '0') {
                   3997:                         $earlyout = 1;
                   3998:                     }
                   3999:                 }
                   4000:             } else {
                   4001:                 if ($query eq 'usersearch') {
                   4002:                     if ($usersearchconf->{'lclocalonly'}) {
                   4003:                         $earlyout = 1;
                   4004:                     }
                   4005:                 } else {
                   4006:                     if ($usersearchconf->{'localonly'}) {
                   4007:                         $earlyout = 1;
                   4008:                     }
                   4009:                 }
                   4010:             }
                   4011:         }
                   4012:         if ($earlyout) {
                   4013:             &Reply($client, "query_not_authorized\n");
                   4014:             return 1;
                   4015:         }
                   4016:     }
1.234     foxr     4017:     &Reply($client, "". &sql_reply("$clientname\&$query".
                   4018: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
                   4019: 	  $userinput);
                   4020:     
                   4021:     return 1;
                   4022: }
                   4023: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
                   4024: 
                   4025: #
                   4026: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
                   4027: #   The query is submitted via a "querysend" transaction.
                   4028: #   There it is passed on to the lonsql daemon, queued and issued to
                   4029: #   mysql.
                   4030: #     This transaction is invoked when the sql transaction is complete
                   4031: #   it stores the query results in flie and indicates query completion.
                   4032: #   presumably local software then fetches this response... I'm guessing
                   4033: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
                   4034: #   lonsql on completion of the query interacts with the lond of our
                   4035: #   client to do a query reply storing two files:
                   4036: #    - id     - The results of the query.
                   4037: #    - id.end - Indicating the transaction completed. 
                   4038: #    NOTE: id is a unique id assigned to the query and querysend time.
                   4039: # Parameters:
                   4040: #    $cmd        - Command keyword that initiated this request.
                   4041: #    $tail       - Remainder of the tail.  In this case that's a colon
                   4042: #                  separated list containing the query Id and the 
                   4043: #                  results of the query.
                   4044: #    $client     - Socket open on the client.
                   4045: # Return:
                   4046: #    1           - Indicating that we should continue processing.
                   4047: # Side effects:
                   4048: #    ok written to the client.
                   4049: #
                   4050: sub reply_query_handler {
                   4051:     my ($cmd, $tail, $client) = @_;
                   4052: 
                   4053: 
                   4054:     my $userinput = "$cmd:$tail";
                   4055: 
1.339     albertel 4056:     my ($id,$reply)=split(/:/,$tail); 
1.234     foxr     4057:     my $store;
                   4058:     my $execdir=$perlvar{'lonDaemons'};
                   4059:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
                   4060: 	$reply=~s/\&/\n/g;
                   4061: 	print $store $reply;
                   4062: 	close $store;
                   4063: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
                   4064: 	print $store2 "done\n";
                   4065: 	close $store2;
                   4066: 	&Reply($client, "ok\n", $userinput);
                   4067:     } else {
                   4068: 	&Failure($client, "error: ".($!+0)
                   4069: 		." IO::File->new Failed ".
                   4070: 		"while attempting queryreply\n", $userinput);
                   4071:     }
                   4072:  
                   4073: 
                   4074:     return 1;
                   4075: }
                   4076: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
                   4077: 
                   4078: #
                   4079: #  Process the courseidput request.  Not quite sure what this means
                   4080: #  at the system level sense.  It appears a gdbm file in the 
                   4081: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
                   4082: #  a set of entries made in that database.
                   4083: #
                   4084: # Parameters:
                   4085: #   $cmd      - The command keyword that initiated this request.
                   4086: #   $tail     - Tail of the command.  In this case consists of a colon
                   4087: #               separated list contaning the domain to apply this to and
                   4088: #               an ampersand separated list of keyword=value pairs.
1.272     raeburn  4089: #               Each value is a colon separated list that includes:  
                   4090: #               description, institutional code and course owner.
                   4091: #               For backward compatibility with versions included
                   4092: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
                   4093: #               code and/or course owner are preserved from the existing 
                   4094: #               record when writing a new record in response to 1.1 or 
                   4095: #               1.2 implementations of lonnet::flushcourselogs().   
                   4096: #                      
1.234     foxr     4097: #   $client   - Socket open on the client.
                   4098: # Returns:
                   4099: #   1    - indicating that processing should continue
                   4100: #
                   4101: # Side effects:
                   4102: #   reply is written to the client.
                   4103: #
                   4104: sub put_course_id_handler {
                   4105:     my ($cmd, $tail, $client) = @_;
                   4106: 
                   4107: 
                   4108:     my $userinput = "$cmd:$tail";
                   4109: 
1.266     raeburn  4110:     my ($udom, $what) = split(/:/, $tail,2);
1.234     foxr     4111:     chomp($what);
                   4112:     my $now=time;
                   4113:     my @pairs=split(/\&/,$what);
                   4114: 
                   4115:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4116:     if ($hashref) {
                   4117: 	foreach my $pair (@pairs) {
1.271     raeburn  4118:             my ($key,$courseinfo) = split(/=/,$pair,2);
                   4119:             $courseinfo =~ s/=/:/g;
1.384     raeburn  4120:             if (defined($hashref->{$key})) {
                   4121:                 my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
                   4122:                 if (ref($value) eq 'HASH') {
                   4123:                     my @items = ('description','inst_code','owner','type');
                   4124:                     my @new_items = split(/:/,$courseinfo,-1);
                   4125:                     my %storehash; 
                   4126:                     for (my $i=0; $i<@new_items; $i++) {
1.391     raeburn  4127:                         $storehash{$items[$i]} = &unescape($new_items[$i]);
1.384     raeburn  4128:                     }
                   4129:                     $hashref->{$key} = 
                   4130:                         &Apache::lonnet::freeze_escape(\%storehash);
                   4131:                     my $unesc_key = &unescape($key);
                   4132:                     $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4133:                     next;
1.383     raeburn  4134:                 }
1.384     raeburn  4135:             }
                   4136:             my @current_items = split(/:/,$hashref->{$key},-1);
                   4137:             shift(@current_items); # remove description
                   4138:             pop(@current_items);   # remove last access
                   4139:             my $numcurrent = scalar(@current_items);
                   4140:             if ($numcurrent > 3) {
                   4141:                 $numcurrent = 3;
                   4142:             }
                   4143:             my @new_items = split(/:/,$courseinfo,-1);
                   4144:             my $numnew = scalar(@new_items);
                   4145:             if ($numcurrent > 0) {
                   4146:                 if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2 
                   4147:                     for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
                   4148:                         $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
1.333     raeburn  4149:                     }
1.272     raeburn  4150:                 }
                   4151:             }
1.384     raeburn  4152:             $hashref->{$key}=$courseinfo.':'.$now;
1.234     foxr     4153: 	}
1.311     albertel 4154: 	if (&untie_domain_hash($hashref)) {
1.253     foxr     4155: 	    &Reply( $client, "ok\n", $userinput);
1.234     foxr     4156: 	} else {
1.253     foxr     4157: 	    &Failure($client, "error: ".($!+0)
1.234     foxr     4158: 		     ." untie(GDBM) Failed ".
                   4159: 		     "while attempting courseidput\n", $userinput);
                   4160: 	}
                   4161:     } else {
1.253     foxr     4162: 	&Failure($client, "error: ".($!+0)
1.234     foxr     4163: 		 ." tie(GDBM) Failed ".
                   4164: 		 "while attempting courseidput\n", $userinput);
                   4165:     }
                   4166: 
                   4167:     return 1;
                   4168: }
                   4169: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
                   4170: 
1.383     raeburn  4171: sub put_course_id_hash_handler {
                   4172:     my ($cmd, $tail, $client) = @_;
                   4173:     my $userinput = "$cmd:$tail";
1.384     raeburn  4174:     my ($udom,$mode,$what) = split(/:/, $tail,3);
1.383     raeburn  4175:     chomp($what);
                   4176:     my $now=time;
                   4177:     my @pairs=split(/\&/,$what);
1.384     raeburn  4178:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
1.383     raeburn  4179:     if ($hashref) {
                   4180:         foreach my $pair (@pairs) {
                   4181:             my ($key,$value)=split(/=/,$pair);
1.384     raeburn  4182:             my $unesc_key = &unescape($key);
                   4183:             if ($mode ne 'timeonly') {
                   4184:                 if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
                   4185:                     my $curritems = &Apache::lonnet::thaw_unescape($key); 
                   4186:                     if (ref($curritems) ne 'HASH') {
                   4187:                         my @current_items = split(/:/,$hashref->{$key},-1);
                   4188:                         my $lasttime = pop(@current_items);
                   4189:                         $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
                   4190:                     } else {
                   4191:                         $hashref->{&escape('lasttime:'.$unesc_key)} = '';
                   4192:                     }
                   4193:                 } 
                   4194:                 $hashref->{$key} = $value;
                   4195:             }
                   4196:             if ($mode ne 'notime') {
                   4197:                 $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4198:             }
1.383     raeburn  4199:         }
                   4200:         if (&untie_domain_hash($hashref)) {
                   4201:             &Reply($client, "ok\n", $userinput);
                   4202:         } else {
                   4203:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4204:                      "while attempting courseidputhash\n", $userinput);
                   4205:         }
                   4206:     } else {
                   4207:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4208:                   "while attempting courseidputhash\n", $userinput);
                   4209:     }
                   4210:     return 1;
                   4211: }
                   4212: &register_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
                   4213: 
1.234     foxr     4214: #  Retrieves the value of a course id resource keyword pattern
                   4215: #  defined since a starting date.  Both the starting date and the
                   4216: #  keyword pattern are optional.  If the starting date is not supplied it
                   4217: #  is treated as the beginning of time.  If the pattern is not found,
                   4218: #  it is treatred as "." matching everything.
                   4219: #
                   4220: #  Parameters:
                   4221: #     $cmd     - Command keyword that resulted in us being dispatched.
                   4222: #     $tail    - The remainder of the command that, in this case, consists
                   4223: #                of a colon separated list of:
                   4224: #                 domain   - The domain in which the course database is 
                   4225: #                            defined.
                   4226: #                 since    - Optional parameter describing the minimum
                   4227: #                            time of definition(?) of the resources that
                   4228: #                            will match the dump.
                   4229: #                 description - regular expression that is used to filter
                   4230: #                            the dump.  Only keywords matching this regexp
                   4231: #                            will be used.
1.272     raeburn  4232: #                 institutional code - optional supplied code to filter 
                   4233: #                            the dump. Only courses with an institutional code 
                   4234: #                            that match the supplied code will be returned.
1.336     raeburn  4235: #                 owner    - optional supplied username and domain of owner to
                   4236: #                            filter the dump.  Only courses for which the course
                   4237: #                            owner matches the supplied username and/or domain
                   4238: #                            will be returned. Pre-2.2.0 legacy entries from 
                   4239: #                            nohist_courseiddump will only contain usernames.
1.384     raeburn  4240: #                 type     - optional parameter for selection 
1.418     raeburn  4241: #                 regexp_ok - if 1 or -1 allow the supplied institutional code
                   4242: #                            filter to behave as a regular expression:
                   4243: #	                      1 will not exclude the course if the instcode matches the RE 
                   4244: #                            -1 will exclude the course if the instcode matches the RE
1.384     raeburn  4245: #                 rtn_as_hash - whether to return the information available for
                   4246: #                            each matched item as a frozen hash of all 
                   4247: #                            key, value pairs in the item's hash, or as a 
                   4248: #                            colon-separated list of (in order) description,
                   4249: #                            institutional code, and course owner.
1.404     raeburn  4250: #                 selfenrollonly - filter by courses allowing self-enrollment  
                   4251: #                                  now or in the future (selfenrollonly = 1).
                   4252: #                 catfilter - filter by course category, assigned to a course 
                   4253: #                             using manually defined categories (i.e., not
1.407     raeburn  4254: #                             self-cataloging based on on institutional code).   
1.404     raeburn  4255: #                 showhidden - include course in results even if course  
1.407     raeburn  4256: #                              was set to be excluded from course catalog (DC only).
1.404     raeburn  4257: #                 caller -  if set to 'coursecatalog', courses set to be hidden
                   4258: #                           from course catalog will be excluded from results (unless
                   4259: #                           overridden by "showhidden".
1.427     raeburn  4260: #                 cloner - escaped username:domain of course cloner (if picking course to
1.419     raeburn  4261: #                          clone).
                   4262: #                 cc_clone_list - escaped comma separated list of courses for which 
                   4263: #                                 course cloner has active CC role (and so can clone
                   4264: #                                 automatically).
1.427     raeburn  4265: #                 cloneonly - filter by courses for which cloner has rights to clone.
                   4266: #                 createdbefore - include courses for which creation date preceeded this date.
                   4267: #                 createdafter - include courses for which creation date followed this date.
                   4268: #                 creationcontext - include courses created in specified context 
1.404     raeburn  4269: #
1.445     raeburn  4270: #                 domcloner - flag to indicate if user can create CCs in course's domain.
1.505     raeburn  4271: #                             If so, ability to clone course is automatic.
                   4272: #                 hasuniquecode - filter by courses for which a six character unique code has 
                   4273: #                                 been set.
1.445     raeburn  4274: #
1.234     foxr     4275: #     $client  - The socket open on the client.
                   4276: # Returns:
                   4277: #    1     - Continue processing.
                   4278: # Side Effects:
                   4279: #   a reply is written to $client.
                   4280: sub dump_course_id_handler {
                   4281:     my ($cmd, $tail, $client) = @_;
1.494     droeschl 4282: 
                   4283:     my $res = LONCAPA::Lond::dump_course_id_handler($tail);
                   4284:     if ($res =~ /^error:/) {
                   4285:         Failure($client, \$res, "$cmd:$tail");
                   4286:     } else {
                   4287:         Reply($client, \$res, "$cmd:$tail");
                   4288:     }
                   4289: 
                   4290:     return 1;  
                   4291: 
                   4292:     #TODO remove
1.234     foxr     4293:     my $userinput = "$cmd:$tail";
                   4294: 
1.333     raeburn  4295:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
1.404     raeburn  4296:         $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
1.427     raeburn  4297:         $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
1.505     raeburn  4298:         $creationcontext,$domcloner,$hasuniquecode) =split(/:/,$tail);
1.397     raeburn  4299:     my $now = time;
1.419     raeburn  4300:     my ($cloneruname,$clonerudom,%cc_clone);
1.234     foxr     4301:     if (defined($description)) {
                   4302: 	$description=&unescape($description);
                   4303:     } else {
                   4304: 	$description='.';
                   4305:     }
1.266     raeburn  4306:     if (defined($instcodefilter)) {
                   4307:         $instcodefilter=&unescape($instcodefilter);
                   4308:     } else {
                   4309:         $instcodefilter='.';
                   4310:     }
1.336     raeburn  4311:     my ($ownerunamefilter,$ownerdomfilter);
1.266     raeburn  4312:     if (defined($ownerfilter)) {
                   4313:         $ownerfilter=&unescape($ownerfilter);
1.336     raeburn  4314:         if ($ownerfilter ne '.' && defined($ownerfilter)) {
                   4315:             if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
                   4316:                  $ownerunamefilter = $1;
                   4317:                  $ownerdomfilter = $2;
                   4318:             } else {
                   4319:                 $ownerunamefilter = $ownerfilter;
                   4320:                 $ownerdomfilter = '';
                   4321:             }
                   4322:         }
1.266     raeburn  4323:     } else {
                   4324:         $ownerfilter='.';
                   4325:     }
1.336     raeburn  4326: 
1.282     raeburn  4327:     if (defined($coursefilter)) {
                   4328:         $coursefilter=&unescape($coursefilter);
                   4329:     } else {
                   4330:         $coursefilter='.';
                   4331:     }
1.333     raeburn  4332:     if (defined($typefilter)) {
                   4333:         $typefilter=&unescape($typefilter);
                   4334:     } else {
                   4335:         $typefilter='.';
                   4336:     }
1.344     raeburn  4337:     if (defined($regexp_ok)) {
                   4338:         $regexp_ok=&unescape($regexp_ok);
                   4339:     }
1.401     raeburn  4340:     if (defined($catfilter)) {
                   4341:         $catfilter=&unescape($catfilter);
                   4342:     }
1.419     raeburn  4343:     if (defined($cloner)) {
                   4344:         $cloner = &unescape($cloner);
                   4345:         ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/); 
                   4346:     }
                   4347:     if (defined($cc_clone_list)) {
                   4348:         $cc_clone_list = &unescape($cc_clone_list);
                   4349:         my @cc_cloners = split('&',$cc_clone_list);
                   4350:         foreach my $cid (@cc_cloners) {
                   4351:             my ($clonedom,$clonenum) = split(':',$cid);
                   4352:             next if ($clonedom ne $udom); 
                   4353:             $cc_clone{$clonedom.'_'.$clonenum} = 1;
                   4354:         } 
                   4355:     }
1.431     raeburn  4356:     if ($createdbefore ne '') {
1.427     raeburn  4357:         $createdbefore = &unescape($createdbefore);
                   4358:     } else {
                   4359:        $createdbefore = 0;
                   4360:     }
1.431     raeburn  4361:     if ($createdafter ne '') {
1.427     raeburn  4362:         $createdafter = &unescape($createdafter);
                   4363:     } else {
                   4364:         $createdafter = 0;
                   4365:     }
1.431     raeburn  4366:     if ($creationcontext ne '') {
1.427     raeburn  4367:         $creationcontext = &unescape($creationcontext);
                   4368:     } else {
                   4369:         $creationcontext = '.';
                   4370:     }
1.505     raeburn  4371:     unless ($hasuniquecode) {
                   4372:         $hasuniquecode = '.';
                   4373:     }
1.384     raeburn  4374:     my $unpack = 1;
1.485     raeburn  4375:     if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' && 
1.384     raeburn  4376:         $typefilter eq '.') {
                   4377:         $unpack = 0;
                   4378:     }
                   4379:     if (!defined($since)) { $since=0; }
1.234     foxr     4380:     my $qresult='';
                   4381:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4382:     if ($hashref) {
1.384     raeburn  4383: 	while (my ($key,$value) = each(%$hashref)) {
1.397     raeburn  4384:             my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
1.427     raeburn  4385:                 %unesc_val,$selfenroll_end,$selfenroll_types,$created,
                   4386:                 $context);
1.384     raeburn  4387:             $unesc_key = &unescape($key);
                   4388:             if ($unesc_key =~ /^lasttime:/) {
                   4389:                 next;
                   4390:             } else {
                   4391:                 $lasttime_key = &escape('lasttime:'.$unesc_key);
                   4392:             }
                   4393:             if ($hashref->{$lasttime_key} ne '') {
                   4394:                 $lasttime = $hashref->{$lasttime_key};
                   4395:                 next if ($lasttime<$since);
                   4396:             }
1.419     raeburn  4397:             my ($canclone,$valchange);
1.384     raeburn  4398:             my $items = &Apache::lonnet::thaw_unescape($value);
                   4399:             if (ref($items) eq 'HASH') {
1.429     raeburn  4400:                 if ($hashref->{$lasttime_key} eq '') {
1.430     raeburn  4401:                     next if ($since > 1);
1.429     raeburn  4402:                 }
1.384     raeburn  4403:                 $is_hash =  1;
1.445     raeburn  4404:                 if ($domcloner) {
                   4405:                     $canclone = 1;
                   4406:                 } elsif (defined($clonerudom)) {
1.419     raeburn  4407:                     if ($items->{'cloners'}) {
                   4408:                         my @cloneable = split(',',$items->{'cloners'});
                   4409:                         if (@cloneable) {
                   4410:                             if (grep(/^\*$/,@cloneable))  {
                   4411:                                 $canclone = 1;
                   4412:                             } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
                   4413:                                 $canclone = 1;
                   4414:                             } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
                   4415:                                 $canclone = 1;
                   4416:                             }
                   4417:                         }
                   4418:                         unless ($canclone) {
                   4419:                             if ($cloneruname ne '' && $clonerudom ne '') {
                   4420:                                 if ($cc_clone{$unesc_key}) {
                   4421:                                     $canclone = 1;
                   4422:                                     $items->{'cloners'} .= ','.$cloneruname.':'.
                   4423:                                                            $clonerudom;
                   4424:                                     $valchange = 1;
                   4425:                                 }
                   4426:                             }
                   4427:                         }
                   4428:                     } elsif (defined($cloneruname)) {
                   4429:                         if ($cc_clone{$unesc_key}) {
                   4430:                             $canclone = 1;
                   4431:                             $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4432:                             $valchange = 1;
                   4433:                         }
1.437     raeburn  4434:                         unless ($canclone) {
                   4435:                             if ($items->{'owner'} =~ /:/) {
                   4436:                                 if ($items->{'owner'} eq $cloner) {
                   4437:                                     $canclone = 1;
                   4438:                                 }
1.444     raeburn  4439:                             } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
1.437     raeburn  4440:                                 $canclone = 1;
                   4441:                             }
                   4442:                             if ($canclone) {
                   4443:                                 $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4444:                                 $valchange = 1;
                   4445:                             }
                   4446:                         }
1.419     raeburn  4447:                     }
                   4448:                 }
1.384     raeburn  4449:                 if ($unpack || !$rtn_as_hash) {
                   4450:                     $unesc_val{'descr'} = $items->{'description'};
                   4451:                     $unesc_val{'inst_code'} = $items->{'inst_code'};
                   4452:                     $unesc_val{'owner'} = $items->{'owner'};
                   4453:                     $unesc_val{'type'} = $items->{'type'};
1.419     raeburn  4454:                     $unesc_val{'cloners'} = $items->{'cloners'};
1.427     raeburn  4455:                     $unesc_val{'created'} = $items->{'created'};
                   4456:                     $unesc_val{'context'} = $items->{'context'};
1.404     raeburn  4457:                 }
                   4458:                 $selfenroll_types = $items->{'selfenroll_types'};
                   4459:                 $selfenroll_end = $items->{'selfenroll_end_date'};
1.427     raeburn  4460:                 $created = $items->{'created'};
                   4461:                 $context = $items->{'context'};
1.505     raeburn  4462:                 if ($hasuniquecode ne '.') {
                   4463:                     next unless ($items->{'uniquecode'});
                   4464:                 }
1.404     raeburn  4465:                 if ($selfenrollonly) {
                   4466:                     next if (!$selfenroll_types);
                   4467:                     if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
                   4468:                         next;
1.397     raeburn  4469:                     }
1.404     raeburn  4470:                 }
1.427     raeburn  4471:                 if ($creationcontext ne '.') {
                   4472:                     next if (($context ne '') && ($context ne $creationcontext));  
                   4473:                 }
                   4474:                 if ($createdbefore > 0) {
                   4475:                     next if (($created eq '') || ($created > $createdbefore));   
                   4476:                 }
                   4477:                 if ($createdafter > 0) {
                   4478:                     next if (($created eq '') || ($created <= $createdafter)); 
                   4479:                 }
1.404     raeburn  4480:                 if ($catfilter ne '') {
1.406     raeburn  4481:                     next if ($items->{'categories'} eq '');
                   4482:                     my @categories = split('&',$items->{'categories'}); 
1.407     raeburn  4483:                     next if (@categories == 0);
                   4484:                     my @subcats = split('&',$catfilter);
                   4485:                     my $matchcat = 0;
                   4486:                     foreach my $cat (@categories) {
                   4487:                         if (grep(/^\Q$cat\E$/,@subcats)) {
                   4488:                             $matchcat = 1;
                   4489:                             last;
                   4490:                         }
                   4491:                     }
                   4492:                     next if (!$matchcat);
1.404     raeburn  4493:                 }
                   4494:                 if ($caller eq 'coursecatalog') {
1.405     raeburn  4495:                     if ($items->{'hidefromcat'} eq 'yes') {
                   4496:                         next if !$showhidden;
1.401     raeburn  4497:                     }
1.384     raeburn  4498:                 }
1.383     raeburn  4499:             } else {
1.401     raeburn  4500:                 next if ($catfilter ne '');
1.419     raeburn  4501:                 next if ($selfenrollonly);
1.427     raeburn  4502:                 next if ($createdbefore || $createdafter);
                   4503:                 next if ($creationcontext ne '.');
1.419     raeburn  4504:                 if ((defined($clonerudom)) && (defined($cloneruname)))  {
                   4505:                     if ($cc_clone{$unesc_key}) {
                   4506:                         $canclone = 1;
                   4507:                         $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
                   4508:                     }
                   4509:                 }
1.384     raeburn  4510:                 $is_hash =  0;
1.388     raeburn  4511:                 my @courseitems = split(/:/,$value);
1.403     raeburn  4512:                 $lasttime = pop(@courseitems);
1.402     raeburn  4513:                 if ($hashref->{$lasttime_key} eq '') {
                   4514:                     next if ($lasttime<$since);
                   4515:                 }
1.384     raeburn  4516: 	        ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
1.383     raeburn  4517:             }
1.419     raeburn  4518:             if ($cloneonly) {
                   4519:                next unless ($canclone);
                   4520:             }
1.266     raeburn  4521:             my $match = 1;
1.384     raeburn  4522: 	    if ($description ne '.') {
                   4523:                 if (!$is_hash) {
                   4524:                     $unesc_val{'descr'} = &unescape($val{'descr'});
                   4525:                 }
                   4526:                 if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
1.266     raeburn  4527:                     $match = 0;
1.384     raeburn  4528:                 }
1.266     raeburn  4529:             }
1.384     raeburn  4530:             if ($instcodefilter ne '.') {
                   4531:                 if (!$is_hash) {
                   4532:                     $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
                   4533:                 }
1.418     raeburn  4534:                 if ($regexp_ok == 1) {
1.384     raeburn  4535:                     if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
1.344     raeburn  4536:                         $match = 0;
                   4537:                     }
1.418     raeburn  4538:                 } elsif ($regexp_ok == -1) {
                   4539:                     if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
                   4540:                         $match = 0;
                   4541:                     }
1.344     raeburn  4542:                 } else {
1.384     raeburn  4543:                     if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
1.344     raeburn  4544:                         $match = 0;
                   4545:                     }
1.266     raeburn  4546:                 }
1.234     foxr     4547: 	    }
1.384     raeburn  4548:             if ($ownerfilter ne '.') {
                   4549:                 if (!$is_hash) {
                   4550:                     $unesc_val{'owner'} = &unescape($val{'owner'});
                   4551:                 }
1.336     raeburn  4552:                 if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
1.384     raeburn  4553:                     if ($unesc_val{'owner'} =~ /:/) {
                   4554:                         if (eval{$unesc_val{'owner'} !~ 
                   4555:                              /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
1.336     raeburn  4556:                             $match = 0;
                   4557:                         } 
                   4558:                     } else {
1.384     raeburn  4559:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4560:                             $match = 0;
                   4561:                         }
                   4562:                     }
                   4563:                 } elsif ($ownerunamefilter ne '') {
1.384     raeburn  4564:                     if ($unesc_val{'owner'} =~ /:/) {
                   4565:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
1.336     raeburn  4566:                              $match = 0;
                   4567:                         }
                   4568:                     } else {
1.384     raeburn  4569:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4570:                             $match = 0;
                   4571:                         }
                   4572:                     }
                   4573:                 } elsif ($ownerdomfilter ne '') {
1.384     raeburn  4574:                     if ($unesc_val{'owner'} =~ /:/) {
                   4575:                         if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
1.336     raeburn  4576:                              $match = 0;
                   4577:                         }
                   4578:                     } else {
                   4579:                         if ($ownerdomfilter ne $udom) {
                   4580:                             $match = 0;
                   4581:                         }
                   4582:                     }
1.266     raeburn  4583:                 }
                   4584:             }
1.384     raeburn  4585:             if ($coursefilter ne '.') {
                   4586:                 if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
1.282     raeburn  4587:                     $match = 0;
                   4588:                 }
                   4589:             }
1.384     raeburn  4590:             if ($typefilter ne '.') {
                   4591:                 if (!$is_hash) {
                   4592:                     $unesc_val{'type'} = &unescape($val{'type'});
                   4593:                 }
                   4594:                 if ($unesc_val{'type'} eq '') {
1.333     raeburn  4595:                     if ($typefilter ne 'Course') {
                   4596:                         $match = 0;
                   4597:                     }
1.383     raeburn  4598:                 } else {
1.384     raeburn  4599:                     if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
1.333     raeburn  4600:                         $match = 0;
                   4601:                     }
                   4602:                 }
                   4603:             }
1.266     raeburn  4604:             if ($match == 1) {
1.384     raeburn  4605:                 if ($rtn_as_hash) {
                   4606:                     if ($is_hash) {
1.419     raeburn  4607:                         if ($valchange) {
                   4608:                             my $newvalue = &Apache::lonnet::freeze_escape($items);
                   4609:                             $qresult.=$key.'='.$newvalue.'&';
                   4610:                         } else {
                   4611:                             $qresult.=$key.'='.$value.'&';
                   4612:                         }
1.384     raeburn  4613:                     } else {
1.388     raeburn  4614:                         my %rtnhash = ( 'description' => &unescape($val{'descr'}),
                   4615:                                         'inst_code' => &unescape($val{'inst_code'}),
                   4616:                                         'owner'     => &unescape($val{'owner'}),
                   4617:                                         'type'      => &unescape($val{'type'}),
1.419     raeburn  4618:                                         'cloners'   => &unescape($val{'cloners'}),
1.384     raeburn  4619:                                       );
                   4620:                         my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
                   4621:                         $qresult.=$key.'='.$items.'&';
                   4622:                     }
1.383     raeburn  4623:                 } else {
1.384     raeburn  4624:                     if ($is_hash) {
                   4625:                         $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
                   4626:                                     &escape($unesc_val{'inst_code'}).':'.
                   4627:                                     &escape($unesc_val{'owner'}).'&';
                   4628:                     } else {
                   4629:                         $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
                   4630:                                     ':'.$val{'owner'}.'&';
                   4631:                     }
1.383     raeburn  4632:                 }
1.266     raeburn  4633:             }
1.234     foxr     4634: 	}
1.311     albertel 4635: 	if (&untie_domain_hash($hashref)) {
1.234     foxr     4636: 	    chop($qresult);
1.387     albertel 4637: 	    &Reply($client, \$qresult, $userinput);
1.234     foxr     4638: 	} else {
                   4639: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4640: 		    "while attempting courseiddump\n", $userinput);
                   4641: 	}
                   4642:     } else {
                   4643: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4644: 		"while attempting courseiddump\n", $userinput);
                   4645:     }
                   4646:     return 1;
                   4647: }
                   4648: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238     foxr     4649: 
1.438     raeburn  4650: sub course_lastaccess_handler {
                   4651:     my ($cmd, $tail, $client) = @_;
                   4652:     my $userinput = "$cmd:$tail";
                   4653:     my ($cdom,$cnum) = split(':',$tail); 
                   4654:     my (%lastaccess,$qresult);
                   4655:     my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
                   4656:     if ($hashref) {
                   4657:         while (my ($key,$value) = each(%$hashref)) {
                   4658:             my ($unesc_key,$lasttime);
                   4659:             $unesc_key = &unescape($key);
                   4660:             if ($cnum) {
                   4661:                 next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
                   4662:             }
                   4663:             if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
                   4664:                 $lastaccess{$1} = $value;
                   4665:             } else {
                   4666:                 my $items = &Apache::lonnet::thaw_unescape($value);
                   4667:                 if (ref($items) eq 'HASH') {
                   4668:                     unless ($lastaccess{$unesc_key}) {
                   4669:                         $lastaccess{$unesc_key} = '';
                   4670:                     }
                   4671:                 } else {
                   4672:                     my @courseitems = split(':',$value);
                   4673:                     $lastaccess{$unesc_key} = pop(@courseitems);
                   4674:                 }
                   4675:             }
                   4676:         }
                   4677:         foreach my $cid (sort(keys(%lastaccess))) {
                   4678:             $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&'; 
                   4679:         }
                   4680:         if (&untie_domain_hash($hashref)) {
                   4681:             if ($qresult) {
                   4682:                 chop($qresult);
                   4683:             }
                   4684:             &Reply($client, \$qresult, $userinput);
                   4685:         } else {
                   4686:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4687:                     "while attempting lastacourseaccess\n", $userinput);
                   4688:         }
                   4689:     } else {
                   4690:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4691:                 "while attempting lastcourseaccess\n", $userinput);
                   4692:     }
                   4693:     return 1;
                   4694: }
                   4695: &register_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
                   4696: 
1.238     foxr     4697: #
1.348     raeburn  4698: # Puts an unencrypted entry in a namespace db file at the domain level 
                   4699: #
                   4700: # Parameters:
                   4701: #    $cmd      - The command that got us here.
                   4702: #    $tail     - Tail of the command (remaining parameters).
                   4703: #    $client   - File descriptor connected to client.
                   4704: # Returns
                   4705: #     0        - Requested to exit, caller should shut down.
                   4706: #     1        - Continue processing.
                   4707: #  Side effects:
                   4708: #     reply is written to $client.
                   4709: #
                   4710: sub put_domain_handler {
                   4711:     my ($cmd,$tail,$client) = @_;
                   4712: 
                   4713:     my $userinput = "$cmd:$tail";
                   4714: 
                   4715:     my ($udom,$namespace,$what) =split(/:/,$tail,3);
                   4716:     chomp($what);
                   4717:     my @pairs=split(/\&/,$what);
                   4718:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
                   4719:                                    "P", $what);
                   4720:     if ($hashref) {
                   4721:         foreach my $pair (@pairs) {
                   4722:             my ($key,$value)=split(/=/,$pair);
                   4723:             $hashref->{$key}=$value;
                   4724:         }
                   4725:         if (&untie_domain_hash($hashref)) {
                   4726:             &Reply($client, "ok\n", $userinput);
                   4727:         } else {
                   4728:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4729:                      "while attempting putdom\n", $userinput);
                   4730:         }
                   4731:     } else {
                   4732:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4733:                   "while attempting putdom\n", $userinput);
                   4734:     }
                   4735: 
                   4736:     return 1;
                   4737: }
                   4738: &register_handler("putdom", \&put_domain_handler, 0, 1, 0);
                   4739: 
1.517     raeburn  4740: # Updates one or more entries in clickers.db file at the domain level
                   4741: #
                   4742: # Parameters:
                   4743: #    $cmd      - The command that got us here.
                   4744: #    $tail     - Tail of the command (remaining parameters).
                   4745: #                In this case a colon separated list containing:
                   4746: #                (a) the domain for which we are updating the entries,
                   4747: #                (b) the action required -- add or del -- and
                   4748: #                (c) a &-separated list of entries to add or delete.
                   4749: #    $client   - File descriptor connected to client.
                   4750: # Returns
                   4751: #     1        - Continue processing.
                   4752: #     0        - Requested to exit, caller should shut down.
                   4753: #  Side effects:
                   4754: #     reply is written to $client.
                   4755: #
                   4756: 
                   4757: 
                   4758: sub update_clickers {
                   4759:     my ($cmd, $tail, $client)  = @_;
                   4760: 
                   4761:     my $userinput = "$cmd:$tail";
                   4762:     my ($udom,$action,$what) =split(/:/,$tail,3);
                   4763:     chomp($what);
                   4764: 
                   4765:     my $hashref = &tie_domain_hash($udom, "clickers", &GDBM_WRCREAT(),
                   4766:                                  "U","$action:$what");
                   4767: 
                   4768:     if (!$hashref) {
                   4769:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4770:                   "while attempting updateclickers\n", $userinput);
                   4771:         return 1;
                   4772:     }
                   4773: 
                   4774:     my @pairs=split(/\&/,$what);
                   4775:     foreach my $pair (@pairs) {
                   4776:         my ($key,$value)=split(/=/,$pair);
                   4777:         if ($action eq 'add') {
                   4778:             if (exists($hashref->{$key})) {
                   4779:                 my @newvals = split(/,/,&unescape($value));
                   4780:                 my @currvals = split(/,/,&unescape($hashref->{$key}));
                   4781:                 my @merged = sort(keys(%{{map { $_ => 1 } (@newvals,@currvals)}}));
                   4782:                 $hashref->{$key}=&escape(join(',',@merged));
                   4783:             } else {
                   4784:                 $hashref->{$key}=$value;
                   4785:             }
                   4786:         } elsif ($action eq 'del') {
                   4787:             if (exists($hashref->{$key})) {
                   4788:                 my %current;
                   4789:                 map { $current{$_} = 1; } split(/,/,&unescape($hashref->{$key}));
                   4790:                 map { delete($current{$_}); } split(/,/,&unescape($value));
                   4791:                 if (keys(%current)) {
                   4792:                     $hashref->{$key}=&escape(join(',',sort(keys(%current))));
                   4793:                 } else {
                   4794:                     delete($hashref->{$key});
                   4795:                 }
                   4796:             }
                   4797:         }
                   4798:     }
                   4799:     if (&untie_user_hash($hashref)) {
                   4800:         &Reply( $client, "ok\n", $userinput);
                   4801:     } else {
                   4802:         &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   4803:                  "while attempting put\n",
                   4804:                  $userinput);
                   4805:     }
                   4806:     return 1;
                   4807: }
                   4808: &register_handler("updateclickers", \&update_clickers, 0, 1, 0);
                   4809: 
                   4810: 
                   4811: # Deletes one or more entries in a namespace db file at the domain level
                   4812: #
                   4813: # Parameters:
                   4814: #    $cmd      - The command that got us here.
                   4815: #    $tail     - Tail of the command (remaining parameters).
                   4816: #                In this case a colon separated list containing:
                   4817: #                (a) the domain for which we are deleting the entries,
                   4818: #                (b) &-separated list of keys to delete.  
                   4819: #    $client   - File descriptor connected to client.
                   4820: # Returns
                   4821: #     1        - Continue processing.
                   4822: #     0        - Requested to exit, caller should shut down.
                   4823: #  Side effects:
                   4824: #     reply is written to $client.
                   4825: #
                   4826: 
                   4827: sub del_domain_handler {
                   4828:     my ($cmd,$tail,$client) = @_;
                   4829: 
                   4830:     my $userinput = "$cmd:$tail";
                   4831: 
                   4832:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   4833:     chomp($what);
                   4834:     my $hashref = &tie_domain_hash($udom,$namespace,&GDBM_WRCREAT(),
                   4835:                                    "D", $what);
                   4836:     if ($hashref) {
                   4837:         my @keys=split(/\&/,$what);
                   4838:         foreach my $key (@keys) {
                   4839:             delete($hashref->{$key});
                   4840:         }
                   4841:         if (&untie_user_hash($hashref)) {
                   4842:             &Reply($client, "ok\n", $userinput);
                   4843:         } else {
                   4844:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4845:                     "while attempting deldom\n", $userinput);
                   4846:         }
                   4847:     } else {
                   4848:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4849:                  "while attempting deldom\n", $userinput);
                   4850:     }
                   4851:     return 1;
                   4852: }
                   4853: &register_handler("deldom", \&del_domain_handler, 0, 1, 0);
                   4854: 
                   4855: 
1.348     raeburn  4856: # Unencrypted get from the namespace database file at the domain level.
                   4857: # This function retrieves a keyed item from a specific named database in the
                   4858: # domain directory.
                   4859: #
                   4860: # Parameters:
                   4861: #   $cmd             - Command request keyword (get).
                   4862: #   $tail            - Tail of the command.  This is a colon separated list
                   4863: #                      consisting of the domain and the 'namespace' 
                   4864: #                      which selects the gdbm file to do the lookup in,
                   4865: #                      & separated list of keys to lookup.  Note that
                   4866: #                      the values are returned as an & separated list too.
                   4867: #   $client          - File descriptor open on the client.
                   4868: # Returns:
                   4869: #   1       - Continue processing.
                   4870: #   0       - Exit.
                   4871: #  Side effects:
                   4872: #     reply is written to $client.
                   4873: #
                   4874: 
                   4875: sub get_domain_handler {
                   4876:     my ($cmd, $tail, $client) = @_;
                   4877: 
1.461     foxr     4878: 
1.536     raeburn  4879:     my $userinput = "$cmd:$tail";
                   4880: 
                   4881:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   4882:     chomp($what);
                   4883:     if ($namespace =~ /^enc/) {
                   4884:         &Failure( $client, "refused\n", $userinput);
                   4885:     } else {
                   4886:         my @queries=split(/\&/,$what);
                   4887:         my $qresult='';
                   4888:         my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
                   4889:         if ($hashref) {
                   4890:             for (my $i=0;$i<=$#queries;$i++) {
                   4891:                 $qresult.="$hashref->{$queries[$i]}&";
                   4892:             }
                   4893:             if (&untie_domain_hash($hashref)) {
                   4894:                 $qresult=~s/\&$//;
                   4895:                 &Reply($client, \$qresult, $userinput);
                   4896:             } else {
                   4897:                 &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4898:                           "while attempting getdom\n",$userinput);
                   4899:             }
                   4900:         } else {
                   4901:             &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4902:                      "while attempting getdom\n",$userinput);
                   4903:         }
                   4904:     }
                   4905: 
                   4906:     return 1;
                   4907: }
                   4908: &register_handler("getdom", \&get_domain_handler, 0, 1, 0);
                   4909: 
                   4910: sub encrypted_get_domain_handler {
                   4911:     my ($cmd, $tail, $client) = @_;
                   4912: 
                   4913:     my $userinput = "$cmd:$tail";
1.348     raeburn  4914: 
                   4915:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   4916:     chomp($what);
                   4917:     my @queries=split(/\&/,$what);
                   4918:     my $qresult='';
                   4919:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
                   4920:     if ($hashref) {
                   4921:         for (my $i=0;$i<=$#queries;$i++) {
                   4922:             $qresult.="$hashref->{$queries[$i]}&";
                   4923:         }
                   4924:         if (&untie_domain_hash($hashref)) {
                   4925:             $qresult=~s/\&$//;
1.536     raeburn  4926:             if ($cipher) {
                   4927:                 my $cmdlength=length($qresult);
                   4928:                 $qresult.="         ";
                   4929:                 my $encqresult='';
                   4930:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   4931:                     $encqresult.= unpack("H16",
                   4932:                                          $cipher->encrypt(substr($qresult,
                   4933:                                                                  $encidx,
                   4934:                                                                  8)));
                   4935:                 }
                   4936:                 &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   4937:             } else {
                   4938:                 &Failure( $client, "error:no_key\n", $userinput);
                   4939:             }
1.348     raeburn  4940:         } else {
                   4941:             &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
1.536     raeburn  4942:                       "while attempting egetdom\n",$userinput);
1.348     raeburn  4943:         }
                   4944:     } else {
                   4945:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
1.536     raeburn  4946:                  "while attempting egetdom\n",$userinput);
1.348     raeburn  4947:     }
                   4948:     return 1;
                   4949: }
1.536     raeburn  4950: &register_handler("egetdom", \&encrypted_get_domain_handler, 1, 1, 0);
1.348     raeburn  4951: 
1.420     raeburn  4952: #
1.238     foxr     4953: #  Puts an id to a domains id database. 
                   4954: #
                   4955: #  Parameters:
                   4956: #   $cmd     - The command that triggered us.
                   4957: #   $tail    - Remainder of the request other than the command. This is a 
                   4958: #              colon separated list containing:
                   4959: #              $domain  - The domain for which we are writing the id.
                   4960: #              $pairs  - The id info to write... this is and & separated list
                   4961: #                        of keyword=value.
                   4962: #   $client  - Socket open on the client.
                   4963: #  Returns:
                   4964: #    1   - Continue processing.
                   4965: #  Side effects:
                   4966: #     reply is written to $client.
                   4967: #
                   4968: sub put_id_handler {
                   4969:     my ($cmd,$tail,$client) = @_;
                   4970: 
                   4971: 
                   4972:     my $userinput = "$cmd:$tail";
                   4973: 
                   4974:     my ($udom,$what)=split(/:/,$tail);
                   4975:     chomp($what);
                   4976:     my @pairs=split(/\&/,$what);
                   4977:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   4978: 				   "P", $what);
                   4979:     if ($hashref) {
                   4980: 	foreach my $pair (@pairs) {
                   4981: 	    my ($key,$value)=split(/=/,$pair);
                   4982: 	    $hashref->{$key}=$value;
                   4983: 	}
1.311     albertel 4984: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     4985: 	    &Reply($client, "ok\n", $userinput);
                   4986: 	} else {
                   4987: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4988: 		     "while attempting idput\n", $userinput);
                   4989: 	}
                   4990:     } else {
                   4991: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4992: 		  "while attempting idput\n", $userinput);
                   4993:     }
                   4994: 
                   4995:     return 1;
                   4996: }
1.263     albertel 4997: &register_handler("idput", \&put_id_handler, 0, 1, 0);
1.238     foxr     4998: 
                   4999: #
                   5000: #  Retrieves a set of id values from the id database.
                   5001: #  Returns an & separated list of results, one for each requested id to the
                   5002: #  client.
                   5003: #
                   5004: # Parameters:
                   5005: #   $cmd       - Command keyword that caused us to be dispatched.
                   5006: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5007: #               domain - the domain whose id table we dump
                   5008: #               ids      Consists of an & separated list of
                   5009: #                        id keywords whose values will be fetched.
                   5010: #                        nonexisting keywords will have an empty value.
                   5011: #   $client    - Socket open on the client.
                   5012: #
                   5013: # Returns:
                   5014: #    1 - indicating processing should continue.
                   5015: # Side effects:
                   5016: #   An & separated list of results is written to $client.
                   5017: #
                   5018: sub get_id_handler {
                   5019:     my ($cmd, $tail, $client) = @_;
                   5020: 
                   5021:     
                   5022:     my $userinput = "$client:$tail";
                   5023:     
                   5024:     my ($udom,$what)=split(/:/,$tail);
                   5025:     chomp($what);
                   5026:     my @queries=split(/\&/,$what);
                   5027:     my $qresult='';
                   5028:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
                   5029:     if ($hashref) {
                   5030: 	for (my $i=0;$i<=$#queries;$i++) {
                   5031: 	    $qresult.="$hashref->{$queries[$i]}&";
                   5032: 	}
1.311     albertel 5033: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     5034: 	    $qresult=~s/\&$//;
1.387     albertel 5035: 	    &Reply($client, \$qresult, $userinput);
1.238     foxr     5036: 	} else {
                   5037: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5038: 		      "while attempting idget\n",$userinput);
                   5039: 	}
                   5040:     } else {
                   5041: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5042: 		 "while attempting idget\n",$userinput);
                   5043:     }
                   5044:     
                   5045:     return 1;
                   5046: }
1.263     albertel 5047: &register_handler("idget", \&get_id_handler, 0, 1, 0);
1.238     foxr     5048: 
1.501     raeburn  5049: #   Deletes one or more ids in a domain's id database.
                   5050: #
                   5051: #   Parameters:
                   5052: #       $cmd                  - Command keyword (iddel).
                   5053: #       $tail                 - Command tail.  In this case a colon
                   5054: #                               separated list containing:
                   5055: #                               The domain for which we are deleting the id(s).
                   5056: #                               &-separated list of id(s) to delete.
                   5057: #       $client               - File open on client socket.
                   5058: # Returns:
                   5059: #     1   - Continue processing
                   5060: #     0   - Exit server.
                   5061: #     
                   5062: #
                   5063: 
                   5064: sub del_id_handler {
                   5065:     my ($cmd,$tail,$client) = @_;
                   5066: 
                   5067:     my $userinput = "$cmd:$tail";
                   5068: 
                   5069:     my ($udom,$what)=split(/:/,$tail);
                   5070:     chomp($what);
                   5071:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   5072:                                    "D", $what);
                   5073:     if ($hashref) {
                   5074:         my @keys=split(/\&/,$what);
                   5075:         foreach my $key (@keys) {
                   5076:             delete($hashref->{$key});
                   5077:         }
                   5078:         if (&untie_user_hash($hashref)) {
                   5079:             &Reply($client, "ok\n", $userinput);
                   5080:         } else {
                   5081:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5082:                     "while attempting iddel\n", $userinput);
                   5083:         }
                   5084:     } else {
                   5085:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5086:                  "while attempting iddel\n", $userinput);
                   5087:     }
                   5088:     return 1;
                   5089: }
                   5090: &register_handler("iddel", \&del_id_handler, 0, 1, 0);
                   5091: 
1.238     foxr     5092: #
1.299     raeburn  5093: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
                   5094: #
                   5095: # Parameters
                   5096: #   $cmd       - Command keyword that caused us to be dispatched.
                   5097: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5098: #               domain - the domain whose dcmail we are recording
                   5099: #               email    Consists of key=value pair 
                   5100: #                        where key is unique msgid
                   5101: #                        and value is message (in XML)
                   5102: #   $client    - Socket open on the client.
                   5103: #
                   5104: # Returns:
                   5105: #    1 - indicating processing should continue.
                   5106: # Side effects
                   5107: #     reply is written to $client.
                   5108: #
                   5109: sub put_dcmail_handler {
                   5110:     my ($cmd,$tail,$client) = @_;
                   5111:     my $userinput = "$cmd:$tail";
1.463     foxr     5112: 
                   5113: 
1.299     raeburn  5114:     my ($udom,$what)=split(/:/,$tail);
                   5115:     chomp($what);
                   5116:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5117:     if ($hashref) {
                   5118:         my ($key,$value)=split(/=/,$what);
                   5119:         $hashref->{$key}=$value;
                   5120:     }
1.311     albertel 5121:     if (&untie_domain_hash($hashref)) {
1.299     raeburn  5122:         &Reply($client, "ok\n", $userinput);
                   5123:     } else {
                   5124:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5125:                  "while attempting dcmailput\n", $userinput);
                   5126:     }
                   5127:     return 1;
                   5128: }
                   5129: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
                   5130: 
                   5131: #
                   5132: # Retrieves broadcast e-mail from nohist_dcmail database
                   5133: # Returns to client an & separated list of key=value pairs,
                   5134: # where key is msgid and value is message information.
                   5135: #
                   5136: # Parameters
                   5137: #   $cmd       - Command keyword that caused us to be dispatched.
                   5138: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5139: #               domain - the domain whose dcmail table we dump
                   5140: #               startfilter - beginning of time window 
                   5141: #               endfilter - end of time window
                   5142: #               sendersfilter - & separated list of username:domain 
                   5143: #                 for senders to search for.
                   5144: #   $client    - Socket open on the client.
                   5145: #
                   5146: # Returns:
                   5147: #    1 - indicating processing should continue.
                   5148: # Side effects
                   5149: #     reply (& separated list of msgid=messageinfo pairs) is 
                   5150: #     written to $client.
                   5151: #
                   5152: sub dump_dcmail_handler {
                   5153:     my ($cmd, $tail, $client) = @_;
                   5154:                                                                                 
                   5155:     my $userinput = "$cmd:$tail";
                   5156:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
                   5157:     chomp($sendersfilter);
                   5158:     my @senders = ();
                   5159:     if (defined($startfilter)) {
                   5160:         $startfilter=&unescape($startfilter);
                   5161:     } else {
                   5162:         $startfilter='.';
                   5163:     }
                   5164:     if (defined($endfilter)) {
                   5165:         $endfilter=&unescape($endfilter);
                   5166:     } else {
                   5167:         $endfilter='.';
                   5168:     }
                   5169:     if (defined($sendersfilter)) {
                   5170:         $sendersfilter=&unescape($sendersfilter);
1.300     albertel 5171: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
1.299     raeburn  5172:     }
                   5173: 
                   5174:     my $qresult='';
                   5175:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5176:     if ($hashref) {
                   5177:         while (my ($key,$value) = each(%$hashref)) {
                   5178:             my $match = 1;
1.303     albertel 5179:             my ($timestamp,$subj,$uname,$udom) = 
                   5180: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
1.299     raeburn  5181:             $subj = &unescape($subj);
                   5182:             unless ($startfilter eq '.' || !defined($startfilter)) {
                   5183:                 if ($timestamp < $startfilter) {
                   5184:                     $match = 0;
                   5185:                 }
                   5186:             }
                   5187:             unless ($endfilter eq '.' || !defined($endfilter)) {
                   5188:                 if ($timestamp > $endfilter) {
                   5189:                     $match = 0;
                   5190:                 }
                   5191:             }
                   5192:             unless (@senders < 1) {
                   5193:                 unless (grep/^$uname:$udom$/,@senders) {
                   5194:                     $match = 0;
                   5195:                 }
                   5196:             }
                   5197:             if ($match == 1) {
                   5198:                 $qresult.=$key.'='.$value.'&';
                   5199:             }
                   5200:         }
1.311     albertel 5201:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5202:             chop($qresult);
1.387     albertel 5203:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5204:         } else {
                   5205:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5206:                     "while attempting dcmaildump\n", $userinput);
                   5207:         }
                   5208:     } else {
                   5209:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5210:                 "while attempting dcmaildump\n", $userinput);
                   5211:     }
                   5212:     return 1;
                   5213: }
                   5214: 
                   5215: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
                   5216: 
                   5217: #
                   5218: # Puts domain roles in nohist_domainroles database
                   5219: #
                   5220: # Parameters
                   5221: #   $cmd       - Command keyword that caused us to be dispatched.
                   5222: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5223: #               domain - the domain whose roles we are recording  
                   5224: #               role -   Consists of key=value pair
                   5225: #                        where key is unique role
                   5226: #                        and value is start/end date information
                   5227: #   $client    - Socket open on the client.
                   5228: #
                   5229: # Returns:
                   5230: #    1 - indicating processing should continue.
                   5231: # Side effects
                   5232: #     reply is written to $client.
                   5233: #
                   5234: 
                   5235: sub put_domainroles_handler {
                   5236:     my ($cmd,$tail,$client) = @_;
                   5237: 
                   5238:     my $userinput = "$cmd:$tail";
                   5239:     my ($udom,$what)=split(/:/,$tail);
                   5240:     chomp($what);
                   5241:     my @pairs=split(/\&/,$what);
                   5242:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5243:     if ($hashref) {
                   5244:         foreach my $pair (@pairs) {
                   5245:             my ($key,$value)=split(/=/,$pair);
                   5246:             $hashref->{$key}=$value;
                   5247:         }
1.311     albertel 5248:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5249:             &Reply($client, "ok\n", $userinput);
                   5250:         } else {
                   5251:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5252:                      "while attempting domroleput\n", $userinput);
                   5253:         }
                   5254:     } else {
                   5255:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5256:                   "while attempting domroleput\n", $userinput);
                   5257:     }
                   5258:                                                                                   
                   5259:     return 1;
                   5260: }
                   5261: 
                   5262: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
                   5263: 
                   5264: #
                   5265: # Retrieves domain roles from nohist_domainroles database
                   5266: # Returns to client an & separated list of key=value pairs,
                   5267: # where key is role and value is start and end date information.
                   5268: #
                   5269: # Parameters
                   5270: #   $cmd       - Command keyword that caused us to be dispatched.
                   5271: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5272: #               domain - the domain whose domain roles table we dump
                   5273: #   $client    - Socket open on the client.
                   5274: #
                   5275: # Returns:
                   5276: #    1 - indicating processing should continue.
                   5277: # Side effects
                   5278: #     reply (& separated list of role=start/end info pairs) is
                   5279: #     written to $client.
                   5280: #
                   5281: sub dump_domainroles_handler {
                   5282:     my ($cmd, $tail, $client) = @_;
                   5283:                                                                                            
                   5284:     my $userinput = "$cmd:$tail";
                   5285:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
                   5286:     chomp($rolesfilter);
                   5287:     my @roles = ();
                   5288:     if (defined($startfilter)) {
                   5289:         $startfilter=&unescape($startfilter);
                   5290:     } else {
                   5291:         $startfilter='.';
                   5292:     }
                   5293:     if (defined($endfilter)) {
                   5294:         $endfilter=&unescape($endfilter);
                   5295:     } else {
                   5296:         $endfilter='.';
                   5297:     }
                   5298:     if (defined($rolesfilter)) {
                   5299:         $rolesfilter=&unescape($rolesfilter);
1.300     albertel 5300: 	@roles = split(/\&/,$rolesfilter);
1.299     raeburn  5301:     }
1.421     raeburn  5302: 
1.299     raeburn  5303:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5304:     if ($hashref) {
                   5305:         my $qresult = '';
                   5306:         while (my ($key,$value) = each(%$hashref)) {
                   5307:             my $match = 1;
1.421     raeburn  5308:             my ($end,$start) = split(/:/,&unescape($value));
1.299     raeburn  5309:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
1.421     raeburn  5310:             unless (@roles < 1) {
                   5311:                 unless (grep/^\Q$trole\E$/,@roles) {
                   5312:                     $match = 0;
                   5313:                     next;
                   5314:                 }
                   5315:             }
1.299     raeburn  5316:             unless ($startfilter eq '.' || !defined($startfilter)) {
1.415     raeburn  5317:                 if ((defined($start)) && ($start >= $startfilter)) {
1.299     raeburn  5318:                     $match = 0;
1.421     raeburn  5319:                     next;
1.299     raeburn  5320:                 }
                   5321:             }
                   5322:             unless ($endfilter eq '.' || !defined($endfilter)) {
1.421     raeburn  5323:                 if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
1.299     raeburn  5324:                     $match = 0;
1.421     raeburn  5325:                     next;
1.299     raeburn  5326:                 }
                   5327:             }
                   5328:             if ($match == 1) {
                   5329:                 $qresult.=$key.'='.$value.'&';
                   5330:             }
                   5331:         }
1.311     albertel 5332:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5333:             chop($qresult);
1.387     albertel 5334:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5335:         } else {
                   5336:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5337:                     "while attempting domrolesdump\n", $userinput);
                   5338:         }
                   5339:     } else {
                   5340:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5341:                 "while attempting domrolesdump\n", $userinput);
                   5342:     }
                   5343:     return 1;
                   5344: }
                   5345: 
                   5346: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
                   5347: 
                   5348: 
1.238     foxr     5349: #  Process the tmpput command I'm not sure what this does.. Seems to
                   5350: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
                   5351: # where Id is the client's ip concatenated with a sequence number.
                   5352: # The file will contain some value that is passed in.  Is this e.g.
                   5353: # a login token?
                   5354: #
                   5355: # Parameters:
                   5356: #    $cmd     - The command that got us dispatched.
                   5357: #    $tail    - The remainder of the request following $cmd:
                   5358: #               In this case this will be the contents of the file.
                   5359: #    $client  - Socket connected to the client.
                   5360: # Returns:
                   5361: #    1 indicating processing can continue.
                   5362: # Side effects:
                   5363: #   A file is created in the local filesystem.
                   5364: #   A reply is sent to the client.
                   5365: sub tmp_put_handler {
                   5366:     my ($cmd, $what, $client) = @_;
                   5367: 
                   5368:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
                   5369: 
1.347     raeburn  5370:     my ($record,$context) = split(/:/,$what);
                   5371:     if ($context ne '') {
                   5372:         chomp($context);
                   5373:         $context = &unescape($context);
                   5374:     }
                   5375:     my ($id,$store);
1.238     foxr     5376:     $tmpsnum++;
1.454     raeburn  5377:     if (($context eq 'resetpw') || ($context eq 'createaccount')) {
1.347     raeburn  5378:         $id = &md5_hex(&md5_hex(time.{}.rand().$$));
                   5379:     } else {
                   5380:         $id = $$.'_'.$clientip.'_'.$tmpsnum;
                   5381:     }
1.238     foxr     5382:     $id=~s/\W/\_/g;
1.347     raeburn  5383:     $record=~s/\n//g;
1.238     foxr     5384:     my $execdir=$perlvar{'lonDaemons'};
                   5385:     if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
1.347     raeburn  5386: 	print $store $record;
1.238     foxr     5387: 	close $store;
1.387     albertel 5388: 	&Reply($client, \$id, $userinput);
1.238     foxr     5389:     } else {
                   5390: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5391: 		  "while attempting tmpput\n", $userinput);
                   5392:     }
                   5393:     return 1;
                   5394:   
                   5395: }
                   5396: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263     albertel 5397: 
1.238     foxr     5398: #   Processes the tmpget command.  This command returns the contents
                   5399: #  of a temporary resource file(?) created via tmpput.
                   5400: #
                   5401: # Paramters:
                   5402: #    $cmd      - Command that got us dispatched.
                   5403: #    $id       - Tail of the command, contain the id of the resource
                   5404: #                we want to fetch.
                   5405: #    $client   - socket open on the client.
                   5406: # Return:
                   5407: #    1         - Inidcating processing can continue.
                   5408: # Side effects:
                   5409: #   A reply is sent to the client.
                   5410: #
                   5411: sub tmp_get_handler {
                   5412:     my ($cmd, $id, $client) = @_;
                   5413: 
                   5414:     my $userinput = "$cmd:$id"; 
                   5415:     
                   5416: 
                   5417:     $id=~s/\W/\_/g;
                   5418:     my $store;
                   5419:     my $execdir=$perlvar{'lonDaemons'};
                   5420:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
                   5421: 	my $reply=<$store>;
1.387     albertel 5422: 	&Reply( $client, \$reply, $userinput);
1.238     foxr     5423: 	close $store;
                   5424:     } else {
                   5425: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5426: 		  "while attempting tmpget\n", $userinput);
                   5427:     }
                   5428: 
                   5429:     return 1;
                   5430: }
                   5431: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263     albertel 5432: 
1.238     foxr     5433: #
                   5434: #  Process the tmpdel command.  This command deletes a temp resource
                   5435: #  created by the tmpput command.
                   5436: #
                   5437: # Parameters:
                   5438: #   $cmd      - Command that got us here.
                   5439: #   $id       - Id of the temporary resource created.
                   5440: #   $client   - socket open on the client process.
                   5441: #
                   5442: # Returns:
                   5443: #   1     - Indicating processing should continue.
                   5444: # Side Effects:
                   5445: #   A file is deleted
                   5446: #   A reply is sent to the client.
                   5447: sub tmp_del_handler {
                   5448:     my ($cmd, $id, $client) = @_;
                   5449:     
                   5450:     my $userinput= "$cmd:$id";
                   5451:     
                   5452:     chomp($id);
                   5453:     $id=~s/\W/\_/g;
                   5454:     my $execdir=$perlvar{'lonDaemons'};
                   5455:     if (unlink("$execdir/tmp/$id.tmp")) {
                   5456: 	&Reply($client, "ok\n", $userinput);
                   5457:     } else {
                   5458: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
                   5459: 		  "while attempting tmpdel\n", $userinput);
                   5460:     }
                   5461:     
                   5462:     return 1;
                   5463: 
                   5464: }
                   5465: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263     albertel 5466: 
1.238     foxr     5467: #
1.246     foxr     5468: #   Processes the setannounce command.  This command
                   5469: #   creates a file named announce.txt in the top directory of
                   5470: #   the documentn root and sets its contents.  The announce.txt file is
                   5471: #   printed in its entirety at the LonCAPA login page.  Note:
                   5472: #   once the announcement.txt fileis created it cannot be deleted.
                   5473: #   However, setting the contents of the file to empty removes the
                   5474: #   announcement from the login page of loncapa so who cares.
                   5475: #
                   5476: # Parameters:
                   5477: #    $cmd          - The command that got us dispatched.
                   5478: #    $announcement - The text of the announcement.
                   5479: #    $client       - Socket open on the client process.
                   5480: # Retunrns:
                   5481: #   1             - Indicating request processing should continue
                   5482: # Side Effects:
                   5483: #   The file {DocRoot}/announcement.txt is created.
                   5484: #   A reply is sent to $client.
                   5485: #
                   5486: sub set_announce_handler {
                   5487:     my ($cmd, $announcement, $client) = @_;
                   5488:   
                   5489:     my $userinput    = "$cmd:$announcement";
                   5490: 
                   5491:     chomp($announcement);
                   5492:     $announcement=&unescape($announcement);
                   5493:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
                   5494: 				'/announcement.txt')) {
                   5495: 	print $store $announcement;
                   5496: 	close $store;
                   5497: 	&Reply($client, "ok\n", $userinput);
                   5498:     } else {
                   5499: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
                   5500:     }
                   5501: 
                   5502:     return 1;
                   5503: }
                   5504: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263     albertel 5505: 
1.246     foxr     5506: #
                   5507: #  Return the version of the daemon.  This can be used to determine
                   5508: #  the compatibility of cross version installations or, alternatively to
                   5509: #  simply know who's out of date and who isn't.  Note that the version
                   5510: #  is returned concatenated with the tail.
                   5511: # Parameters:
                   5512: #   $cmd        - the request that dispatched to us.
                   5513: #   $tail       - Tail of the request (client's version?).
                   5514: #   $client     - Socket open on the client.
                   5515: #Returns:
                   5516: #   1 - continue processing requests.
                   5517: # Side Effects:
                   5518: #   Replies with version to $client.
                   5519: sub get_version_handler {
                   5520:     my ($cmd, $tail, $client) = @_;
                   5521: 
                   5522:     my $userinput  = $cmd.$tail;
                   5523:     
                   5524:     &Reply($client, &version($userinput)."\n", $userinput);
                   5525: 
                   5526: 
                   5527:     return 1;
                   5528: }
                   5529: &register_handler("version", \&get_version_handler, 0, 1, 0);
1.263     albertel 5530: 
1.246     foxr     5531: #  Set the current host and domain.  This is used to support
                   5532: #  multihomed systems.  Each IP of the system, or even separate daemons
                   5533: #  on the same IP can be treated as handling a separate lonCAPA virtual
                   5534: #  machine.  This command selects the virtual lonCAPA.  The client always
                   5535: #  knows the right one since it is lonc and it is selecting the domain/system
                   5536: #  from the hosts.tab file.
                   5537: # Parameters:
                   5538: #    $cmd      - Command that dispatched us.
                   5539: #    $tail     - Tail of the command (domain/host requested).
                   5540: #    $socket   - Socket open on the client.
                   5541: #
                   5542: # Returns:
                   5543: #     1   - Indicates the program should continue to process requests.
                   5544: # Side-effects:
                   5545: #     The default domain/system context is modified for this daemon.
                   5546: #     a reply is sent to the client.
                   5547: #
                   5548: sub set_virtual_host_handler {
                   5549:     my ($cmd, $tail, $socket) = @_;
                   5550:   
                   5551:     my $userinput  ="$cmd:$tail";
                   5552: 
                   5553:     &Reply($client, &sethost($userinput)."\n", $userinput);
                   5554: 
                   5555: 
                   5556:     return 1;
                   5557: }
1.247     albertel 5558: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246     foxr     5559: 
                   5560: #  Process a request to exit:
                   5561: #   - "bye" is sent to the client.
                   5562: #   - The client socket is shutdown and closed.
                   5563: #   - We indicate to the caller that we should exit.
                   5564: # Formal Parameters:
                   5565: #   $cmd                - The command that got us here.
                   5566: #   $tail               - Tail of the command (empty).
                   5567: #   $client             - Socket open on the tail.
                   5568: # Returns:
                   5569: #   0      - Indicating the program should exit!!
                   5570: #
                   5571: sub exit_handler {
                   5572:     my ($cmd, $tail, $client) = @_;
                   5573: 
                   5574:     my $userinput = "$cmd:$tail";
                   5575: 
                   5576:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
                   5577:     &Reply($client, "bye\n", $userinput);
                   5578:     $client->shutdown(2);        # shutdown the socket forcibly.
                   5579:     $client->close();
                   5580: 
                   5581:     return 0;
                   5582: }
1.248     foxr     5583: &register_handler("exit", \&exit_handler, 0,1,1);
                   5584: &register_handler("init", \&exit_handler, 0,1,1);
                   5585: &register_handler("quit", \&exit_handler, 0,1,1);
                   5586: 
                   5587: #  Determine if auto-enrollment is enabled.
                   5588: #  Note that the original had what I believe to be a defect.
                   5589: #  The original returned 0 if the requestor was not a registerd client.
                   5590: #  It should return "refused".
                   5591: # Formal Parameters:
                   5592: #   $cmd       - The command that invoked us.
                   5593: #   $tail      - The tail of the command (Extra command parameters.
                   5594: #   $client    - The socket open on the client that issued the request.
                   5595: # Returns:
                   5596: #    1         - Indicating processing should continue.
                   5597: #
                   5598: sub enrollment_enabled_handler {
                   5599:     my ($cmd, $tail, $client) = @_;
                   5600:     my $userinput = $cmd.":".$tail; # For logging purposes.
                   5601: 
                   5602:     
1.337     albertel 5603:     my ($cdom) = split(/:/, $tail, 2);   # Domain we're asking about.
                   5604: 
1.248     foxr     5605:     my $outcome  = &localenroll::run($cdom);
1.387     albertel 5606:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5607: 
                   5608:     return 1;
                   5609: }
                   5610: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
                   5611: 
1.417     raeburn  5612: #
1.423     raeburn  5613: #   Validate an institutional code used for a LON-CAPA course.          
1.417     raeburn  5614: #
                   5615: # Formal Parameters:
                   5616: #   $cmd          - The command request that got us dispatched.
                   5617: #   $tail         - The tail of the command.  In this case,
                   5618: #                   this is a colon separated set of words that will be split
                   5619: #                   into:
1.424     raeburn  5620: #                        $dom      - The domain for which the check of 
                   5621: #                                    institutional course code will occur.
                   5622: #
                   5623: #                        $instcode - The institutional code for the course
                   5624: #                                    being requested, or validated for rights
                   5625: #                                    to request.
                   5626: #
                   5627: #                        $owner    - The course requestor (who will be the
                   5628: #                                    course owner, in the form username:domain
                   5629: #
1.417     raeburn  5630: #   $client       - Socket open on the client.
                   5631: # Returns:
                   5632: #    1           - Indicating processing should continue.
                   5633: #
                   5634: sub validate_instcode_handler {
                   5635:     my ($cmd, $tail, $client) = @_;
                   5636:     my $userinput = "$cmd:$tail";
1.423     raeburn  5637:     my ($dom,$instcode,$owner) = split(/:/, $tail);
1.422     raeburn  5638:     $instcode = &unescape($instcode);
                   5639:     $owner = &unescape($owner);
1.498     raeburn  5640:     my ($outcome,$description,$credits) = 
1.426     raeburn  5641:         &localenroll::validate_instcode($dom,$instcode,$owner);
1.498     raeburn  5642:     my $result = &escape($outcome).'&'.&escape($description).'&'.
                   5643:                  &escape($credits);
1.426     raeburn  5644:     &Reply($client, \$result, $userinput);
1.417     raeburn  5645: 
                   5646:     return 1;
                   5647: }
                   5648: &register_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
                   5649: 
1.248     foxr     5650: #   Get the official sections for which auto-enrollment is possible.
                   5651: #   Since the admin people won't know about 'unofficial sections' 
                   5652: #   we cannot auto-enroll on them.
                   5653: # Formal Parameters:
                   5654: #    $cmd     - The command request that got us dispatched here.
                   5655: #    $tail    - The remainder of the request.  In our case this
                   5656: #               will be split into:
                   5657: #               $coursecode   - The course name from the admin point of view.
                   5658: #               $cdom         - The course's domain(?).
                   5659: #    $client  - Socket open on the client.
                   5660: # Returns:
                   5661: #    1    - Indiciting processing should continue.
                   5662: #
                   5663: sub get_sections_handler {
                   5664:     my ($cmd, $tail, $client) = @_;
                   5665:     my $userinput = "$cmd:$tail";
                   5666: 
                   5667:     my ($coursecode, $cdom) = split(/:/, $tail);
                   5668:     my @secs = &localenroll::get_sections($coursecode,$cdom);
                   5669:     my $seclist = &escape(join(':',@secs));
                   5670: 
1.387     albertel 5671:     &Reply($client, \$seclist, $userinput);
1.248     foxr     5672:     
                   5673: 
                   5674:     return 1;
                   5675: }
                   5676: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
                   5677: 
                   5678: #   Validate the owner of a new course section.  
                   5679: #
                   5680: # Formal Parameters:
                   5681: #   $cmd      - Command that got us dispatched.
                   5682: #   $tail     - the remainder of the command.  For us this consists of a
                   5683: #               colon separated string containing:
                   5684: #                  $inst    - Course Id from the institutions point of view.
                   5685: #                  $owner   - Proposed owner of the course.
                   5686: #                  $cdom    - Domain of the course (from the institutions
                   5687: #                             point of view?)..
                   5688: #   $client   - Socket open on the client.
                   5689: #
                   5690: # Returns:
                   5691: #   1        - Processing should continue.
                   5692: #
                   5693: sub validate_course_owner_handler {
                   5694:     my ($cmd, $tail, $client)  = @_;
                   5695:     my $userinput = "$cmd:$tail";
1.470     raeburn  5696:     my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
                   5697:     
1.336     raeburn  5698:     $owner = &unescape($owner);
1.470     raeburn  5699:     $coowners = &unescape($coowners);
                   5700:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
1.387     albertel 5701:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5702: 
                   5703: 
                   5704: 
                   5705:     return 1;
                   5706: }
                   5707: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263     albertel 5708: 
1.248     foxr     5709: #
                   5710: #   Validate a course section in the official schedule of classes
                   5711: #   from the institutions point of view (part of autoenrollment).
                   5712: #
                   5713: # Formal Parameters:
                   5714: #   $cmd          - The command request that got us dispatched.
                   5715: #   $tail         - The tail of the command.  In this case,
                   5716: #                   this is a colon separated set of words that will be split
                   5717: #                   into:
                   5718: #                        $inst_course_id - The course/section id from the
                   5719: #                                          institutions point of view.
                   5720: #                        $cdom           - The domain from the institutions
                   5721: #                                          point of view.
                   5722: #   $client       - Socket open on the client.
                   5723: # Returns:
                   5724: #    1           - Indicating processing should continue.
                   5725: #
                   5726: sub validate_course_section_handler {
                   5727:     my ($cmd, $tail, $client) = @_;
                   5728:     my $userinput = "$cmd:$tail";
                   5729:     my ($inst_course_id, $cdom) = split(/:/, $tail);
                   5730: 
                   5731:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
1.387     albertel 5732:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5733: 
                   5734: 
                   5735:     return 1;
                   5736: }
                   5737: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
                   5738: 
                   5739: #
1.340     raeburn  5740: #   Validate course owner's access to enrollment data for specific class section. 
                   5741: #   
                   5742: #
                   5743: # Formal Parameters:
                   5744: #    $cmd     - The command request that got us dispatched.
                   5745: #    $tail    - The tail of the command.   In this case this is a colon separated
                   5746: #               set of words that will be split into:
                   5747: #               $inst_class  - Institutional code for the specific class section   
                   5748: #               $courseowner - The escaped username:domain of the course owner 
                   5749: #               $cdom        - The domain of the course from the institution's
                   5750: #                              point of view.
                   5751: #    $client  - The socket open on the client.
                   5752: # Returns:
                   5753: #    1 - continue processing.
                   5754: #
                   5755: 
                   5756: sub validate_class_access_handler {
                   5757:     my ($cmd, $tail, $client) = @_;
                   5758:     my $userinput = "$cmd:$tail";
1.383     raeburn  5759:     my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
1.392     raeburn  5760:     my $owners = &unescape($ownerlist);
1.341     albertel 5761:     my $outcome;
                   5762:     eval {
                   5763: 	local($SIG{__DIE__})='DEFAULT';
1.392     raeburn  5764: 	$outcome=&localenroll::check_section($inst_class,$owners,$cdom);
1.341     albertel 5765:     };
1.387     albertel 5766:     &Reply($client,\$outcome, $userinput);
1.340     raeburn  5767: 
                   5768:     return 1;
                   5769: }
                   5770: &register_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
                   5771: 
                   5772: #
                   5773: #   Create a password for a new LON-CAPA user added by auto-enrollment.
                   5774: #   Only used for case where authentication method for new user is localauth
1.248     foxr     5775: #
                   5776: # Formal Parameters:
                   5777: #    $cmd     - The command request that got us dispatched.
                   5778: #    $tail    - The tail of the command.   In this case this is a colon separated
                   5779: #               set of words that will be split into:
1.340     raeburn  5780: #               $authparam - An authentication parameter (localauth parameter).
1.248     foxr     5781: #               $cdom      - The domain of the course from the institution's
                   5782: #                            point of view.
                   5783: #    $client  - The socket open on the client.
                   5784: # Returns:
                   5785: #    1 - continue processing.
                   5786: #
                   5787: sub create_auto_enroll_password_handler {
                   5788:     my ($cmd, $tail, $client) = @_;
                   5789:     my $userinput = "$cmd:$tail";
                   5790: 
                   5791:     my ($authparam, $cdom) = split(/:/, $userinput);
                   5792: 
                   5793:     my ($create_passwd,$authchk);
                   5794:     ($authparam,
                   5795:      $create_passwd,
                   5796:      $authchk) = &localenroll::create_password($authparam,$cdom);
                   5797: 
                   5798:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
                   5799: 	   $userinput);
                   5800: 
                   5801: 
                   5802:     return 1;
                   5803: }
                   5804: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
                   5805: 		  0, 1, 0);
                   5806: 
1.522     raeburn  5807: sub auto_export_grades_handler {
                   5808:     my ($cmd, $tail, $client) = @_;
                   5809:     my $userinput = "$cmd:$tail";
                   5810:     my ($cdom,$cnum,$info,$data) = split(/:/,$tail);
                   5811:     my $inforef = &Apache::lonnet::thaw_unescape($info);
                   5812:     my $dataref = &Apache::lonnet::thaw_unescape($data);
                   5813:     my ($outcome,$result);;
                   5814:     eval {
                   5815:         local($SIG{__DIE__})='DEFAULT';
                   5816:         my %rtnhash;
                   5817:         $outcome=&localenroll::export_grades($cdom,$cnum,$inforef,$dataref,\%rtnhash);
                   5818:         if ($outcome eq 'ok') {
                   5819:             foreach my $key (keys(%rtnhash)) {
                   5820:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   5821:             }
                   5822:             $result =~ s/\&$//;
                   5823:         }
                   5824:     };
                   5825:     if (!$@) {
                   5826:         if ($outcome eq 'ok') {
                   5827:             if ($cipher) {
                   5828:                 my $cmdlength=length($result);
                   5829:                 $result.="         ";
                   5830:                 my $encresult='';
                   5831:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   5832:                     $encresult.= unpack("H16",
                   5833:                                         $cipher->encrypt(substr($result,
                   5834:                                                                 $encidx,
                   5835:                                                                 8)));
                   5836:                 }
                   5837:                 &Reply( $client, "enc:$cmdlength:$encresult\n", $userinput);
                   5838:             } else {
                   5839:                 &Failure( $client, "error:no_key\n", $userinput);
                   5840:             }
                   5841:         } else {
                   5842:             &Reply($client, "$outcome\n", $userinput);
                   5843:         }
                   5844:     } else {
                   5845:         &Failure($client,"export_error\n",$userinput);
                   5846:     }
                   5847:     return 1;
                   5848: }
                   5849: &register_handler("autoexportgrades", \&auto_export_grades_handler,
1.536     raeburn  5850:                   1, 1, 0);
1.522     raeburn  5851: 
1.248     foxr     5852: #   Retrieve and remove temporary files created by/during autoenrollment.
                   5853: #
                   5854: # Formal Parameters:
                   5855: #    $cmd      - The command that got us dispatched.
                   5856: #    $tail     - The tail of the command.  In our case this is a colon 
                   5857: #                separated list that will be split into:
1.526     raeburn  5858: #                $filename - The name of the file to retrieve.
1.248     foxr     5859: #                            The filename is given as a path relative to
                   5860: #                            the LonCAPA temp file directory.
                   5861: #    $client   - Socket open on the client.
                   5862: #
                   5863: # Returns:
                   5864: #   1     - Continue processing.
                   5865: sub retrieve_auto_file_handler {
                   5866:     my ($cmd, $tail, $client)    = @_;
                   5867:     my $userinput                = "cmd:$tail";
                   5868: 
                   5869:     my ($filename)   = split(/:/, $tail);
                   5870: 
                   5871:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
1.521     raeburn  5872: 
                   5873:     if ($filename =~m{/\.\./}) {
                   5874:         &Failure($client, "refused\n", $userinput);
1.526     raeburn  5875:     } elsif ($filename !~ /^$LONCAPA::match_domain\_$LONCAPA::match_courseid\_.+_classlist\.xml$/) {
                   5876:         &Failure($client, "refused\n", $userinput);
1.521     raeburn  5877:     } elsif ( (-e $source) && ($filename ne '') ) {
1.248     foxr     5878: 	my $reply = '';
                   5879: 	if (open(my $fh,$source)) {
                   5880: 	    while (<$fh>) {
                   5881: 		chomp($_);
                   5882: 		$_ =~ s/^\s+//g;
                   5883: 		$_ =~ s/\s+$//g;
                   5884: 		$reply .= $_;
                   5885: 	    }
                   5886: 	    close($fh);
                   5887: 	    &Reply($client, &escape($reply)."\n", $userinput);
                   5888: 
                   5889: #   Does this have to be uncommented??!?  (RF).
                   5890: #
                   5891: #                                unlink($source);
                   5892: 	} else {
                   5893: 	    &Failure($client, "error\n", $userinput);
                   5894: 	}
                   5895:     } else {
                   5896: 	&Failure($client, "error\n", $userinput);
                   5897:     }
                   5898:     
                   5899: 
                   5900:     return 1;
                   5901: }
                   5902: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
                   5903: 
1.423     raeburn  5904: sub crsreq_checks_handler {
                   5905:     my ($cmd, $tail, $client) = @_;
                   5906:     my $userinput = "$cmd:$tail";
                   5907:     my $dom = $tail;
                   5908:     my $result;
1.519     raeburn  5909:     my @reqtypes = ('official','unofficial','community','textbook','placement');
1.423     raeburn  5910:     eval {
                   5911:         local($SIG{__DIE__})='DEFAULT';
                   5912:         my %validations;
1.424     raeburn  5913:         my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
                   5914:                                                    \%validations);
1.423     raeburn  5915:         if ($response eq 'ok') { 
                   5916:             foreach my $key (keys(%validations)) {
                   5917:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   5918:             }
                   5919:             $result =~ s/\&$//;
                   5920:         } else {
                   5921:             $result = 'error';
                   5922:         }
                   5923:     };
                   5924:     if (!$@) {
                   5925:         &Reply($client, \$result, $userinput);
                   5926:     } else {
                   5927:         &Failure($client,"unknown_cmd\n",$userinput);
                   5928:     }
                   5929:     return 1;
                   5930: }
                   5931: &register_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
                   5932: 
                   5933: sub validate_crsreq_handler {
                   5934:     my ($cmd, $tail, $client) = @_;
                   5935:     my $userinput = "$cmd:$tail";
1.508     raeburn  5936:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
1.423     raeburn  5937:     $instcode = &unescape($instcode);
                   5938:     $owner = &unescape($owner);
                   5939:     $crstype = &unescape($crstype);
                   5940:     $inststatuslist = &unescape($inststatuslist);
                   5941:     $instcode = &unescape($instcode);
                   5942:     $instseclist = &unescape($instseclist);
1.508     raeburn  5943:     my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
1.423     raeburn  5944:     my $outcome;
                   5945:     eval {
                   5946:         local($SIG{__DIE__})='DEFAULT';
                   5947:         $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
                   5948:                                                  $inststatuslist,$instcode,
1.508     raeburn  5949:                                                  $instseclist,$custominfo);
1.423     raeburn  5950:     };
                   5951:     if (!$@) {
                   5952:         &Reply($client, \$outcome, $userinput);
                   5953:     } else {
                   5954:         &Failure($client,"unknown_cmd\n",$userinput);
                   5955:     }
                   5956:     return 1;
                   5957: }
                   5958: &register_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
                   5959: 
1.506     raeburn  5960: sub crsreq_update_handler {
                   5961:     my ($cmd, $tail, $client) = @_;
                   5962:     my $userinput = "$cmd:$tail";
1.509     raeburn  5963:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
                   5964:         $accessstart,$accessend,$infohashref) =
1.506     raeburn  5965:         split(/:/, $tail);
                   5966:     $crstype = &unescape($crstype);
                   5967:     $action = &unescape($action);
                   5968:     $ownername = &unescape($ownername);
                   5969:     $ownerdomain = &unescape($ownerdomain);
                   5970:     $fullname = &unescape($fullname);
                   5971:     $title = &unescape($title);
                   5972:     $code = &unescape($code);
1.509     raeburn  5973:     $accessstart = &unescape($accessstart);
                   5974:     $accessend = &unescape($accessend);
1.506     raeburn  5975:     my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
                   5976:     my ($result,$outcome);
                   5977:     eval {
                   5978:         local($SIG{__DIE__})='DEFAULT';
                   5979:         my %rtnhash;
                   5980:         $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
                   5981:                                                 $ownername,$ownerdomain,$fullname,
1.509     raeburn  5982:                                                 $title,$code,$accessstart,$accessend,
                   5983:                                                 $incoming,\%rtnhash);
1.506     raeburn  5984:         if ($outcome eq 'ok') {
1.515     raeburn  5985:             my @posskeys = qw(createdweb createdmsg createdcustomized createdactions queuedweb queuedmsg formitems reviewweb validationjs onload javascript);
1.506     raeburn  5986:             foreach my $key (keys(%rtnhash)) {
                   5987:                 if (grep(/^\Q$key\E/,@posskeys)) {
                   5988:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   5989:                 }
                   5990:             }
                   5991:             $result =~ s/\&$//;
                   5992:         }
                   5993:     };
                   5994:     if (!$@) {
                   5995:         if ($outcome eq 'ok') {
                   5996:             &Reply($client, \$result, $userinput);
                   5997:         } else {
                   5998:             &Reply($client, "format_error\n", $userinput);
                   5999:         }
                   6000:     } else {
                   6001:         &Failure($client,"unknown_cmd\n",$userinput);
                   6002:     }
                   6003:     return 1;
                   6004: }
                   6005: &register_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
                   6006: 
1.248     foxr     6007: #
                   6008: #   Read and retrieve institutional code format (for support form).
                   6009: # Formal Parameters:
                   6010: #    $cmd        - Command that dispatched us.
                   6011: #    $tail       - Tail of the command.  In this case it conatins 
                   6012: #                  the course domain and the coursename.
                   6013: #    $client     - Socket open on the client.
                   6014: # Returns:
                   6015: #    1     - Continue processing.
                   6016: #
                   6017: sub get_institutional_code_format_handler {
                   6018:     my ($cmd, $tail, $client)   = @_;
                   6019:     my $userinput               = "$cmd:$tail";
                   6020: 
                   6021:     my $reply;
                   6022:     my($cdom,$course) = split(/:/,$tail);
                   6023:     my @pairs = split/\&/,$course;
                   6024:     my %instcodes = ();
                   6025:     my %codes = ();
                   6026:     my @codetitles = ();
                   6027:     my %cat_titles = ();
                   6028:     my %cat_order = ();
                   6029:     foreach (@pairs) {
                   6030: 	my ($key,$value) = split/=/,$_;
                   6031: 	$instcodes{&unescape($key)} = &unescape($value);
                   6032:     }
                   6033:     my $formatreply = &localenroll::instcode_format($cdom,
                   6034: 						    \%instcodes,
                   6035: 						    \%codes,
                   6036: 						    \@codetitles,
                   6037: 						    \%cat_titles,
                   6038: 						    \%cat_order);
                   6039:     if ($formatreply eq 'ok') {
1.365     albertel 6040: 	my $codes_str = &Apache::lonnet::hash2str(%codes);
                   6041: 	my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
                   6042: 	my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
                   6043: 	my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
1.248     foxr     6044: 	&Reply($client,
                   6045: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
                   6046: 	       .$cat_order_str."\n",
                   6047: 	       $userinput);
                   6048:     } else {
                   6049: 	# this else branch added by RF since if not ok, lonc will
                   6050: 	# hang waiting on reply until timeout.
                   6051: 	#
                   6052: 	&Reply($client, "format_error\n", $userinput);
                   6053:     }
                   6054:     
                   6055:     return 1;
                   6056: }
1.265     albertel 6057: &register_handler("autoinstcodeformat",
                   6058: 		  \&get_institutional_code_format_handler,0,1,0);
1.246     foxr     6059: 
1.345     raeburn  6060: sub get_institutional_defaults_handler {
                   6061:     my ($cmd, $tail, $client)   = @_;
                   6062:     my $userinput               = "$cmd:$tail";
                   6063: 
                   6064:     my $dom = $tail;
                   6065:     my %defaults_hash;
                   6066:     my @code_order;
                   6067:     my $outcome;
                   6068:     eval {
                   6069:         local($SIG{__DIE__})='DEFAULT';
                   6070:         $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
                   6071:                                                    \@code_order);
                   6072:     };
                   6073:     if (!$@) {
                   6074:         if ($outcome eq 'ok') {
                   6075:             my $result='';
                   6076:             while (my ($key,$value) = each(%defaults_hash)) {
                   6077:                 $result.=&escape($key).'='.&escape($value).'&';
                   6078:             }
                   6079:             $result .= 'code_order='.&escape(join('&',@code_order));
1.387     albertel 6080:             &Reply($client,\$result,$userinput);
1.345     raeburn  6081:         } else {
                   6082:             &Reply($client,"error\n", $userinput);
                   6083:         }
                   6084:     } else {
                   6085:         &Failure($client,"unknown_cmd\n",$userinput);
                   6086:     }
                   6087: }
                   6088: &register_handler("autoinstcodedefaults",
                   6089:                   \&get_institutional_defaults_handler,0,1,0);
                   6090: 
1.416     raeburn  6091: sub get_possible_instcodes_handler {
                   6092:     my ($cmd, $tail, $client)   = @_;
                   6093:     my $userinput               = "$cmd:$tail";
                   6094: 
                   6095:     my $reply;
                   6096:     my $cdom = $tail;
1.417     raeburn  6097:     my (@codetitles,%cat_titles,%cat_order,@code_order);
1.416     raeburn  6098:     my $formatreply = &localenroll::possible_instcodes($cdom,
                   6099:                                                        \@codetitles,
                   6100:                                                        \%cat_titles,
1.417     raeburn  6101:                                                        \%cat_order,
                   6102:                                                        \@code_order);
1.416     raeburn  6103:     if ($formatreply eq 'ok') {
                   6104:         my $result = join('&',map {&escape($_);} (@codetitles)).':';
1.417     raeburn  6105:         $result .= join('&',map {&escape($_);} (@code_order)).':';
1.416     raeburn  6106:         foreach my $key (keys(%cat_titles)) {
                   6107:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
                   6108:         }
                   6109:         $result =~ s/\&$//;
                   6110:         $result .= ':';
                   6111:         foreach my $key (keys(%cat_order)) {
                   6112:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
                   6113:         }
                   6114:         $result =~ s/\&$//;
                   6115:         &Reply($client,\$result,$userinput);
                   6116:     } else {
                   6117:         &Reply($client, "format_error\n", $userinput);
                   6118:     }
                   6119:     return 1;
                   6120: }
                   6121: &register_handler("autopossibleinstcodes",
                   6122:                   \&get_possible_instcodes_handler,0,1,0);
                   6123: 
1.381     raeburn  6124: sub get_institutional_user_rules {
                   6125:     my ($cmd, $tail, $client)   = @_;
                   6126:     my $userinput               = "$cmd:$tail";
                   6127:     my $dom = &unescape($tail);
                   6128:     my (%rules_hash,@rules_order);
                   6129:     my $outcome;
                   6130:     eval {
                   6131:         local($SIG{__DIE__})='DEFAULT';
                   6132:         $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
                   6133:     };
                   6134:     if (!$@) {
                   6135:         if ($outcome eq 'ok') {
                   6136:             my $result;
                   6137:             foreach my $key (keys(%rules_hash)) {
                   6138:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6139:             }
                   6140:             $result =~ s/\&$//;
                   6141:             $result .= ':';
                   6142:             if (@rules_order > 0) {
                   6143:                 foreach my $item (@rules_order) {
                   6144:                     $result .= &escape($item).'&';
                   6145:                 }
                   6146:             }
                   6147:             $result =~ s/\&$//;
1.387     albertel 6148:             &Reply($client,\$result,$userinput);
1.381     raeburn  6149:         } else {
                   6150:             &Reply($client,"error\n", $userinput);
                   6151:         }
                   6152:     } else {
                   6153:         &Failure($client,"unknown_cmd\n",$userinput);
                   6154:     }
                   6155: }
                   6156: &register_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
                   6157: 
1.389     raeburn  6158: sub get_institutional_id_rules {
                   6159:     my ($cmd, $tail, $client)   = @_;
                   6160:     my $userinput               = "$cmd:$tail";
                   6161:     my $dom = &unescape($tail);
                   6162:     my (%rules_hash,@rules_order);
                   6163:     my $outcome;
                   6164:     eval {
                   6165:         local($SIG{__DIE__})='DEFAULT';
                   6166:         $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
                   6167:     };
                   6168:     if (!$@) {
                   6169:         if ($outcome eq 'ok') {
                   6170:             my $result;
                   6171:             foreach my $key (keys(%rules_hash)) {
                   6172:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6173:             }
                   6174:             $result =~ s/\&$//;
                   6175:             $result .= ':';
                   6176:             if (@rules_order > 0) {
                   6177:                 foreach my $item (@rules_order) {
                   6178:                     $result .= &escape($item).'&';
                   6179:                 }
                   6180:             }
                   6181:             $result =~ s/\&$//;
                   6182:             &Reply($client,\$result,$userinput);
                   6183:         } else {
                   6184:             &Reply($client,"error\n", $userinput);
                   6185:         }
                   6186:     } else {
                   6187:         &Failure($client,"unknown_cmd\n",$userinput);
                   6188:     }
                   6189: }
                   6190: &register_handler("instidrules",\&get_institutional_id_rules,0,1,0);
                   6191: 
1.397     raeburn  6192: sub get_institutional_selfcreate_rules {
1.396     raeburn  6193:     my ($cmd, $tail, $client)   = @_;
                   6194:     my $userinput               = "$cmd:$tail";
                   6195:     my $dom = &unescape($tail);
                   6196:     my (%rules_hash,@rules_order);
                   6197:     my $outcome;
                   6198:     eval {
                   6199:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6200:         $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
1.396     raeburn  6201:     };
                   6202:     if (!$@) {
                   6203:         if ($outcome eq 'ok') {
                   6204:             my $result;
                   6205:             foreach my $key (keys(%rules_hash)) {
                   6206:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6207:             }
                   6208:             $result =~ s/\&$//;
                   6209:             $result .= ':';
                   6210:             if (@rules_order > 0) {
                   6211:                 foreach my $item (@rules_order) {
                   6212:                     $result .= &escape($item).'&';
                   6213:                 }
                   6214:             }
                   6215:             $result =~ s/\&$//;
                   6216:             &Reply($client,\$result,$userinput);
                   6217:         } else {
                   6218:             &Reply($client,"error\n", $userinput);
                   6219:         }
                   6220:     } else {
                   6221:         &Failure($client,"unknown_cmd\n",$userinput);
                   6222:     }
                   6223: }
1.397     raeburn  6224: &register_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
1.396     raeburn  6225: 
1.381     raeburn  6226: 
                   6227: sub institutional_username_check {
                   6228:     my ($cmd, $tail, $client)   = @_;
                   6229:     my $userinput               = "$cmd:$tail";
                   6230:     my %rulecheck;
                   6231:     my $outcome;
                   6232:     my ($udom,$uname,@rules) = split(/:/,$tail);
                   6233:     $udom = &unescape($udom);
                   6234:     $uname = &unescape($uname);
                   6235:     @rules = map {&unescape($_);} (@rules);
                   6236:     eval {
                   6237:         local($SIG{__DIE__})='DEFAULT';
                   6238:         $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
                   6239:     };
                   6240:     if (!$@) {
                   6241:         if ($outcome eq 'ok') {
                   6242:             my $result='';
                   6243:             foreach my $key (keys(%rulecheck)) {
                   6244:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6245:             }
1.387     albertel 6246:             &Reply($client,\$result,$userinput);
1.381     raeburn  6247:         } else {
                   6248:             &Reply($client,"error\n", $userinput);
                   6249:         }
                   6250:     } else {
                   6251:         &Failure($client,"unknown_cmd\n",$userinput);
                   6252:     }
                   6253: }
                   6254: &register_handler("instrulecheck",\&institutional_username_check,0,1,0);
                   6255: 
1.389     raeburn  6256: sub institutional_id_check {
                   6257:     my ($cmd, $tail, $client)   = @_;
                   6258:     my $userinput               = "$cmd:$tail";
                   6259:     my %rulecheck;
                   6260:     my $outcome;
                   6261:     my ($udom,$id,@rules) = split(/:/,$tail);
                   6262:     $udom = &unescape($udom);
                   6263:     $id = &unescape($id);
                   6264:     @rules = map {&unescape($_);} (@rules);
                   6265:     eval {
                   6266:         local($SIG{__DIE__})='DEFAULT';
                   6267:         $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
                   6268:     };
                   6269:     if (!$@) {
                   6270:         if ($outcome eq 'ok') {
                   6271:             my $result='';
                   6272:             foreach my $key (keys(%rulecheck)) {
                   6273:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6274:             }
                   6275:             &Reply($client,\$result,$userinput);
                   6276:         } else {
                   6277:             &Reply($client,"error\n", $userinput);
                   6278:         }
                   6279:     } else {
                   6280:         &Failure($client,"unknown_cmd\n",$userinput);
                   6281:     }
                   6282: }
                   6283: &register_handler("instidrulecheck",\&institutional_id_check,0,1,0);
1.345     raeburn  6284: 
1.397     raeburn  6285: sub institutional_selfcreate_check {
1.396     raeburn  6286:     my ($cmd, $tail, $client)   = @_;
                   6287:     my $userinput               = "$cmd:$tail";
                   6288:     my %rulecheck;
                   6289:     my $outcome;
                   6290:     my ($udom,$email,@rules) = split(/:/,$tail);
                   6291:     $udom = &unescape($udom);
                   6292:     $email = &unescape($email);
                   6293:     @rules = map {&unescape($_);} (@rules);
                   6294:     eval {
                   6295:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6296:         $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
1.396     raeburn  6297:     };
                   6298:     if (!$@) {
                   6299:         if ($outcome eq 'ok') {
                   6300:             my $result='';
                   6301:             foreach my $key (keys(%rulecheck)) {
                   6302:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6303:             }
                   6304:             &Reply($client,\$result,$userinput);
                   6305:         } else {
                   6306:             &Reply($client,"error\n", $userinput);
                   6307:         }
                   6308:     } else {
                   6309:         &Failure($client,"unknown_cmd\n",$userinput);
                   6310:     }
                   6311: }
1.397     raeburn  6312: &register_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
1.396     raeburn  6313: 
1.317     raeburn  6314: # Get domain specific conditions for import of student photographs to a course
                   6315: #
                   6316: # Retrieves information from photo_permission subroutine in localenroll.
                   6317: # Returns outcome (ok) if no processing errors, and whether course owner is 
                   6318: # required to accept conditions of use (yes/no).
                   6319: #
                   6320: #    
                   6321: sub photo_permission_handler {
                   6322:     my ($cmd, $tail, $client)   = @_;
                   6323:     my $userinput               = "$cmd:$tail";
                   6324:     my $cdom = $tail;
                   6325:     my ($perm_reqd,$conditions);
1.320     albertel 6326:     my $outcome;
                   6327:     eval {
                   6328: 	local($SIG{__DIE__})='DEFAULT';
                   6329: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
                   6330: 						  \$conditions);
                   6331:     };
                   6332:     if (!$@) {
                   6333: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
                   6334: 	       $userinput);
                   6335:     } else {
                   6336: 	&Failure($client,"unknown_cmd\n",$userinput);
                   6337:     }
                   6338:     return 1;
1.317     raeburn  6339: }
                   6340: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
                   6341: 
                   6342: #
                   6343: # Checks if student photo is available for a user in the domain, in the user's
                   6344: # directory (in /userfiles/internal/studentphoto.jpg).
                   6345: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
                   6346: # the student's photo.   
                   6347: 
                   6348: sub photo_check_handler {
                   6349:     my ($cmd, $tail, $client)   = @_;
                   6350:     my $userinput               = "$cmd:$tail";
                   6351:     my ($udom,$uname,$pid) = split(/:/,$tail);
                   6352:     $udom = &unescape($udom);
                   6353:     $uname = &unescape($uname);
                   6354:     $pid = &unescape($pid);
                   6355:     my $path=&propath($udom,$uname).'/userfiles/internal/';
                   6356:     if (!-e $path) {
                   6357:         &mkpath($path);
                   6358:     }
                   6359:     my $response;
                   6360:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
                   6361:     $result .= ':'.$response;
                   6362:     &Reply($client, &escape($result)."\n",$userinput);
1.320     albertel 6363:     return 1;
1.317     raeburn  6364: }
                   6365: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
                   6366: 
                   6367: #
                   6368: # Retrieve information from localenroll about whether to provide a button     
                   6369: # for users who have enbled import of student photos to initiate an 
                   6370: # update of photo files for registered students. Also include 
                   6371: # comment to display alongside button.  
                   6372: 
                   6373: sub photo_choice_handler {
                   6374:     my ($cmd, $tail, $client) = @_;
                   6375:     my $userinput             = "$cmd:$tail";
                   6376:     my $cdom                  = &unescape($tail);
1.320     albertel 6377:     my ($update,$comment);
                   6378:     eval {
                   6379: 	local($SIG{__DIE__})='DEFAULT';
                   6380: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
                   6381:     };
                   6382:     if (!$@) {
                   6383: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
                   6384:     } else {
                   6385: 	&Failure($client,"unknown_cmd\n",$userinput);
                   6386:     }
                   6387:     return 1;
1.317     raeburn  6388: }
                   6389: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
                   6390: 
1.265     albertel 6391: #
                   6392: # Gets a student's photo to exist (in the correct image type) in the user's 
                   6393: # directory.
                   6394: # Formal Parameters:
                   6395: #    $cmd     - The command request that got us dispatched.
                   6396: #    $tail    - A colon separated set of words that will be split into:
                   6397: #               $domain - student's domain
                   6398: #               $uname  - student username
                   6399: #               $type   - image type desired
                   6400: #    $client  - The socket open on the client.
                   6401: # Returns:
                   6402: #    1 - continue processing.
1.317     raeburn  6403: 
1.265     albertel 6404: sub student_photo_handler {
                   6405:     my ($cmd, $tail, $client) = @_;
1.317     raeburn  6406:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
1.265     albertel 6407: 
1.317     raeburn  6408:     my $path=&propath($domain,$uname). '/userfiles/internal/';
                   6409:     my $filename = 'studentphoto.'.$ext;
                   6410:     if ($type eq 'thumbnail') {
                   6411:         $filename = 'studentphoto_tn.'.$ext;
                   6412:     }
                   6413:     if (-e $path.$filename) {
1.265     albertel 6414: 	&Reply($client,"ok\n","$cmd:$tail");
                   6415: 	return 1;
                   6416:     }
                   6417:     &mkpath($path);
1.317     raeburn  6418:     my $file;
                   6419:     if ($type eq 'thumbnail') {
1.320     albertel 6420: 	eval {
                   6421: 	    local($SIG{__DIE__})='DEFAULT';
                   6422: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
                   6423: 	};
1.317     raeburn  6424:     } else {
                   6425:         $file=&localstudentphoto::fetch($domain,$uname);
                   6426:     }
1.265     albertel 6427:     if (!$file) {
                   6428: 	&Failure($client,"unavailable\n","$cmd:$tail");
                   6429: 	return 1;
                   6430:     }
1.317     raeburn  6431:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
                   6432:     if (-e $path.$filename) {
1.265     albertel 6433: 	&Reply($client,"ok\n","$cmd:$tail");
                   6434: 	return 1;
                   6435:     }
                   6436:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
                   6437:     return 1;
                   6438: }
                   6439: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246     foxr     6440: 
1.361     raeburn  6441: sub inst_usertypes_handler {
                   6442:     my ($cmd, $domain, $client) = @_;
                   6443:     my $res;
                   6444:     my $userinput = $cmd.":".$domain; # For logging purposes.
1.370     albertel 6445:     my (%typeshash,@order,$result);
                   6446:     eval {
                   6447: 	local($SIG{__DIE__})='DEFAULT';
                   6448: 	$result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
                   6449:     };
                   6450:     if ($result eq 'ok') {
1.361     raeburn  6451:         if (keys(%typeshash) > 0) {
                   6452:             foreach my $key (keys(%typeshash)) {
                   6453:                 $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
                   6454:             }
                   6455:         }
                   6456:         $res=~s/\&$//;
                   6457:         $res .= ':';
                   6458:         if (@order > 0) {
                   6459:             foreach my $item (@order) {
                   6460:                 $res .= &escape($item).'&';
                   6461:             }
                   6462:         }
                   6463:         $res=~s/\&$//;
                   6464:     }
1.387     albertel 6465:     &Reply($client, \$res, $userinput);
1.361     raeburn  6466:     return 1;
                   6467: }
                   6468: &register_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
                   6469: 
1.264     albertel 6470: # mkpath makes all directories for a file, expects an absolute path with a
                   6471: # file or a trailing / if just a dir is passed
                   6472: # returns 1 on success 0 on failure
                   6473: sub mkpath {
                   6474:     my ($file)=@_;
                   6475:     my @parts=split(/\//,$file,-1);
                   6476:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
                   6477:     for (my $i=3;$i<= ($#parts-1);$i++) {
1.265     albertel 6478: 	$now.='/'.$parts[$i]; 
1.264     albertel 6479: 	if (!-e $now) {
                   6480: 	    if  (!mkdir($now,0770)) { return 0; }
                   6481: 	}
                   6482:     }
                   6483:     return 1;
                   6484: }
                   6485: 
1.207     foxr     6486: #---------------------------------------------------------------
                   6487: #
                   6488: #   Getting, decoding and dispatching requests:
                   6489: #
                   6490: #
                   6491: #   Get a Request:
                   6492: #   Gets a Request message from the client.  The transaction
                   6493: #   is defined as a 'line' of text.  We remove the new line
                   6494: #   from the text line.  
1.226     foxr     6495: #
1.211     albertel 6496: sub get_request {
1.207     foxr     6497:     my $input = <$client>;
                   6498:     chomp($input);
1.226     foxr     6499: 
1.234     foxr     6500:     &Debug("get_request: Request = $input\n");
1.207     foxr     6501: 
                   6502:     &status('Processing '.$clientname.':'.$input);
                   6503: 
                   6504:     return $input;
                   6505: }
1.212     foxr     6506: #---------------------------------------------------------------
                   6507: #
                   6508: #  Process a request.  This sub should shrink as each action
                   6509: #  gets farmed out into a separat sub that is registered 
                   6510: #  with the dispatch hash.  
                   6511: #
                   6512: # Parameters:
                   6513: #    user_input   - The request received from the client (lonc).
1.525     raeburn  6514: #
1.212     foxr     6515: # Returns:
                   6516: #    true to keep processing, false if caller should exit.
                   6517: #
                   6518: sub process_request {
1.525     raeburn  6519:     my ($userinput) = @_; # Easier for now to break style than to
                   6520:                           # fix all the userinput -> user_input.
1.212     foxr     6521:     my $wasenc    = 0;		# True if request was encrypted.
                   6522: # ------------------------------------------------------------ See if encrypted
1.322     albertel 6523:     # for command
                   6524:     # sethost:<server>
                   6525:     # <command>:<args>
                   6526:     #   we just send it to the processor
                   6527:     # for
                   6528:     # sethost:<server>:<command>:<args>
                   6529:     #  we do the implict set host and then do the command
                   6530:     if ($userinput =~ /^sethost:/) {
                   6531: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
                   6532: 	if (defined($userinput)) {
                   6533: 	    &sethost("$cmd:$newid");
                   6534: 	} else {
                   6535: 	    $userinput = "$cmd:$newid";
                   6536: 	}
                   6537:     }
                   6538: 
1.212     foxr     6539:     if ($userinput =~ /^enc/) {
                   6540: 	$userinput = decipher($userinput);
                   6541: 	$wasenc=1;
                   6542: 	if(!$userinput) {	# Cipher not defined.
1.251     foxr     6543: 	    &Failure($client, "error: Encrypted data without negotated key\n");
1.212     foxr     6544: 	    return 0;
                   6545: 	}
                   6546:     }
                   6547:     Debug("process_request: $userinput\n");
                   6548:     
1.213     foxr     6549:     #  
                   6550:     #   The 'correct way' to add a command to lond is now to
                   6551:     #   write a sub to execute it and Add it to the command dispatch
                   6552:     #   hash via a call to register_handler..  The comments to that
                   6553:     #   sub should give you enough to go on to show how to do this
                   6554:     #   along with the examples that are building up as this code
                   6555:     #   is getting refactored.   Until all branches of the
                   6556:     #   if/elseif monster below have been factored out into
                   6557:     #   separate procesor subs, if the dispatch hash is missing
                   6558:     #   the command keyword, we will fall through to the remainder
                   6559:     #   of the if/else chain below in order to keep this thing in 
                   6560:     #   working order throughout the transmogrification.
                   6561: 
                   6562:     my ($command, $tail) = split(/:/, $userinput, 2);
                   6563:     chomp($command);
                   6564:     chomp($tail);
                   6565:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
1.214     foxr     6566:     $command =~ s/(\r)//;	# And this too for parameterless commands.
                   6567:     if(!$tail) {
                   6568: 	$tail ="";		# defined but blank.
                   6569:     }
1.213     foxr     6570: 
                   6571:     &Debug("Command received: $command, encoded = $wasenc");
                   6572: 
                   6573:     if(defined $Dispatcher{$command}) {
                   6574: 
                   6575: 	my $dispatch_info = $Dispatcher{$command};
                   6576: 	my $handler       = $$dispatch_info[0];
                   6577: 	my $need_encode   = $$dispatch_info[1];
                   6578: 	my $client_types  = $$dispatch_info[2];
                   6579: 	Debug("Matched dispatch hash: mustencode: $need_encode "
                   6580: 	      ."ClientType $client_types");
                   6581:       
                   6582: 	#  Validate the request:
                   6583:       
                   6584: 	my $ok = 1;
                   6585: 	my $requesterprivs = 0;
                   6586: 	if(&isClient()) {
                   6587: 	    $requesterprivs |= $CLIENT_OK;
                   6588: 	}
                   6589: 	if(&isManager()) {
                   6590: 	    $requesterprivs |= $MANAGER_OK;
                   6591: 	}
                   6592: 	if($need_encode && (!$wasenc)) {
                   6593: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
                   6594: 	    $ok = 0;
                   6595: 	}
                   6596: 	if(($client_types & $requesterprivs) == 0) {
                   6597: 	    Debug("Client not privileged to do this operation");
                   6598: 	    $ok = 0;
                   6599: 	}
1.525     raeburn  6600:         if ($ok) {
1.535     raeburn  6601:             my $realcommand = $command;
                   6602:             if ($command eq 'querysend') {
                   6603:                 my ($query,$rest)=split(/\:/,$tail,2);
                   6604:                 $query=~s/\n*$//g;
                   6605:                 my @possqueries = 
                   6606:                     qw(userlog courselog fetchenrollment institutionalphotos usersearch instdirsearch getinstuser getmultinstusers);
                   6607:                 if (grep(/^\Q$query\E$/,@possqueries)) {
                   6608:                     $command .= '_'.$query;
                   6609:                 } elsif ($query eq 'prepare activity log') {
                   6610:                     $command .= '_activitylog';
                   6611:                 }
                   6612:             }
1.525     raeburn  6613:             if (ref($trust{$command}) eq 'HASH') {
                   6614:                 my $donechecks;
                   6615:                 if ($trust{$command}{'anywhere'}) {
                   6616:                    $donechecks = 1;
                   6617:                 } elsif ($trust{$command}{'manageronly'}) {
                   6618:                     unless (&isManager()) {
                   6619:                         $ok = 0;
                   6620:                     }
                   6621:                     $donechecks = 1;
                   6622:                 } elsif ($trust{$command}{'institutiononly'}) {
                   6623:                     unless ($clientsameinst) {
                   6624:                         $ok = 0;
                   6625:                     }
                   6626:                     $donechecks = 1;
                   6627:                 } elsif ($clientsameinst) {
                   6628:                     $donechecks = 1;
                   6629:                 }
                   6630:                 unless ($donechecks) {
                   6631:                     foreach my $rule (keys(%{$trust{$command}})) {
                   6632:                         next if ($rule eq 'remote');
                   6633:                         if ($trust{$command}{$rule}) {
                   6634:                             if ($clientprohibited{$rule}) {
                   6635:                                 $ok = 0;
                   6636:                             } else {
                   6637:                                 $ok = 1;
                   6638:                                 $donechecks = 1;
                   6639:                                 last;
                   6640:                             }
                   6641:                         }
                   6642:                     }
                   6643:                 }
                   6644:                 unless ($donechecks) {
                   6645:                     if ($trust{$command}{'remote'}) {
                   6646:                         if ($clientremoteok) {
                   6647:                             $ok = 1;
                   6648:                         } else {
                   6649:                             $ok = 0;
                   6650:                         } 
                   6651:                     }
                   6652:                 }
                   6653:             }
1.535     raeburn  6654:             $command = $realcommand;
1.525     raeburn  6655:         }
1.213     foxr     6656: 
                   6657: 	if($ok) {
                   6658: 	    Debug("Dispatching to handler $command $tail");
                   6659: 	    my $keep_going = &$handler($command, $tail, $client);
                   6660: 	    return $keep_going;
                   6661: 	} else {
                   6662: 	    Debug("Refusing to dispatch because client did not match requirements");
                   6663: 	    Failure($client, "refused\n", $userinput);
                   6664: 	    return 1;
                   6665: 	}
1.525     raeburn  6666:     }
1.213     foxr     6667: 
1.262     foxr     6668:     print $client "unknown_cmd\n";
1.212     foxr     6669: # -------------------------------------------------------------------- complete
                   6670:     Debug("process_request - returning 1");
                   6671:     return 1;
                   6672: }
1.207     foxr     6673: #
                   6674: #   Decipher encoded traffic
                   6675: #  Parameters:
                   6676: #     input      - Encoded data.
                   6677: #  Returns:
                   6678: #     Decoded data or undef if encryption key was not yet negotiated.
                   6679: #  Implicit input:
                   6680: #     cipher  - This global holds the negotiated encryption key.
                   6681: #
1.211     albertel 6682: sub decipher {
1.207     foxr     6683:     my ($input)  = @_;
                   6684:     my $output = '';
1.212     foxr     6685:     
                   6686:     
1.207     foxr     6687:     if($cipher) {
                   6688: 	my($enc, $enclength, $encinput) = split(/:/, $input);
                   6689: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
                   6690: 	    $output .= 
                   6691: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
                   6692: 	}
                   6693: 	return substr($output, 0, $enclength);
                   6694:     } else {
                   6695: 	return undef;
                   6696:     }
                   6697: }
                   6698: 
                   6699: #
                   6700: #   Register a command processor.  This function is invoked to register a sub
                   6701: #   to process a request.  Once registered, the ProcessRequest sub can automatically
                   6702: #   dispatch requests to an appropriate sub, and do the top level validity checking
                   6703: #   as well:
                   6704: #    - Is the keyword recognized.
                   6705: #    - Is the proper client type attempting the request.
                   6706: #    - Is the request encrypted if it has to be.
                   6707: #   Parameters:
                   6708: #    $request_name         - Name of the request being registered.
                   6709: #                           This is the command request that will match
                   6710: #                           against the hash keywords to lookup the information
                   6711: #                           associated with the dispatch information.
                   6712: #    $procedure           - Reference to a sub to call to process the request.
                   6713: #                           All subs get called as follows:
                   6714: #                             Procedure($cmd, $tail, $replyfd, $key)
                   6715: #                             $cmd    - the actual keyword that invoked us.
                   6716: #                             $tail   - the tail of the request that invoked us.
                   6717: #                             $replyfd- File descriptor connected to the client
                   6718: #    $must_encode          - True if the request must be encoded to be good.
                   6719: #    $client_ok            - True if it's ok for a client to request this.
                   6720: #    $manager_ok           - True if it's ok for a manager to request this.
                   6721: # Side effects:
                   6722: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
                   6723: #      - On failure, the program will die as it's a bad internal bug to try to 
                   6724: #        register a duplicate command handler.
                   6725: #
1.211     albertel 6726: sub register_handler {
1.212     foxr     6727:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
1.207     foxr     6728: 
                   6729:     #  Don't allow duplication#
                   6730:    
                   6731:     if (defined $Dispatcher{$request_name}) {
                   6732: 	die "Attempting to define a duplicate request handler for $request_name\n";
                   6733:     }
                   6734:     #   Build the client type mask:
                   6735:     
                   6736:     my $client_type_mask = 0;
                   6737:     if($client_ok) {
                   6738: 	$client_type_mask  |= $CLIENT_OK;
                   6739:     }
                   6740:     if($manager_ok) {
                   6741: 	$client_type_mask  |= $MANAGER_OK;
                   6742:     }
                   6743:    
                   6744:     #  Enter the hash:
                   6745:       
                   6746:     my @entry = ($procedure, $must_encode, $client_type_mask);
                   6747:    
                   6748:     $Dispatcher{$request_name} = \@entry;
                   6749:    
                   6750: }
                   6751: 
                   6752: 
                   6753: #------------------------------------------------------------------
                   6754: 
                   6755: 
                   6756: 
                   6757: 
1.141     foxr     6758: #
1.96      foxr     6759: #  Convert an error return code from lcpasswd to a string value.
                   6760: #
                   6761: sub lcpasswdstrerror {
                   6762:     my $ErrorCode = shift;
1.97      foxr     6763:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     6764: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   6765:     } else {
1.98      foxr     6766: 	return $passwderrors[$ErrorCode];
1.96      foxr     6767:     }
                   6768: }
                   6769: 
1.23      harris41 6770: # grabs exception and records it to log before exiting
                   6771: sub catchexception {
1.27      albertel 6772:     my ($error)=@_;
1.25      www      6773:     $SIG{'QUIT'}='DEFAULT';
                   6774:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 6775:     &status("Catching exception");
1.190     albertel 6776:     &logthis("<font color='red'>CRITICAL: "
1.373     albertel 6777:      ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
1.27      albertel 6778:      ."a crash with this error msg->[$error]</font>");
1.57      www      6779:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 6780:     if ($client) { print $client "error: $error\n"; }
1.59      www      6781:     $server->close();
1.27      albertel 6782:     die($error);
1.23      harris41 6783: }
1.63      www      6784: sub timeout {
1.165     albertel 6785:     &status("Handling Timeout");
1.190     albertel 6786:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63      www      6787:     &catchexception('Timeout');
                   6788: }
1.22      harris41 6789: # -------------------------------- Set signal handlers to record abnormal exits
                   6790: 
1.226     foxr     6791: 
1.22      harris41 6792: $SIG{'QUIT'}=\&catchexception;
                   6793: $SIG{__DIE__}=\&catchexception;
                   6794: 
1.81      matthew  6795: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 6796: &status("Read loncapa.conf and loncapa_apache.conf");
                   6797: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     6798: %perlvar=%{$perlvarref};
1.80      harris41 6799: undef $perlvarref;
1.19      www      6800: 
1.35      harris41 6801: # ----------------------------- Make sure this process is running from user=www
                   6802: my $wwwid=getpwnam('www');
                   6803: if ($wwwid!=$<) {
1.134     albertel 6804:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   6805:    my $subj="LON: $currenthostid User ID mismatch";
1.37      harris41 6806:    system("echo 'User ID mismatch.  lond must be run as user www.' |\
1.35      harris41 6807:  mailto $emailto -s '$subj' > /dev/null");
                   6808:    exit 1;
                   6809: }
                   6810: 
1.19      www      6811: # --------------------------------------------- Check if other instance running
                   6812: 
                   6813: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   6814: 
                   6815: if (-e $pidfile) {
                   6816:    my $lfh=IO::File->new("$pidfile");
                   6817:    my $pide=<$lfh>;
                   6818:    chomp($pide);
1.29      harris41 6819:    if (kill 0 => $pide) { die "already running"; }
1.19      www      6820: }
1.1       albertel 6821: 
                   6822: # ------------------------------------------------------------- Read hosts file
                   6823: 
                   6824: 
                   6825: 
                   6826: # establish SERVER socket, bind and listen.
                   6827: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   6828:                                 Type      => SOCK_STREAM,
                   6829:                                 Proto     => 'tcp',
1.469     foxr     6830:                                 ReuseAddr     => 1,
1.1       albertel 6831:                                 Listen    => 10 )
1.29      harris41 6832:   or die "making socket: $@\n";
1.1       albertel 6833: 
                   6834: # --------------------------------------------------------- Do global variables
                   6835: 
                   6836: # global variables
                   6837: 
1.134     albertel 6838: my %children               = ();       # keys are current child process IDs
1.1       albertel 6839: 
                   6840: sub REAPER {                        # takes care of dead children
                   6841:     $SIG{CHLD} = \&REAPER;
1.165     albertel 6842:     &status("Handling child death");
1.178     foxr     6843:     my $pid;
                   6844:     do {
                   6845: 	$pid = waitpid(-1,&WNOHANG());
                   6846: 	if (defined($children{$pid})) {
                   6847: 	    &logthis("Child $pid died");
                   6848: 	    delete($children{$pid});
1.183     albertel 6849: 	} elsif ($pid > 0) {
1.178     foxr     6850: 	    &logthis("Unknown Child $pid died");
                   6851: 	}
                   6852:     } while ( $pid > 0 );
                   6853:     foreach my $child (keys(%children)) {
                   6854: 	$pid = waitpid($child,&WNOHANG());
                   6855: 	if ($pid > 0) {
                   6856: 	    &logthis("Child $child - $pid looks like we missed it's death");
                   6857: 	    delete($children{$pid});
                   6858: 	}
1.176     albertel 6859:     }
1.165     albertel 6860:     &status("Finished Handling child death");
1.1       albertel 6861: }
                   6862: 
                   6863: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 6864:     &status("Killing children (INT)");
1.1       albertel 6865:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   6866:     kill 'INT' => keys %children;
1.59      www      6867:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 6868:     my $execdir=$perlvar{'lonDaemons'};
                   6869:     unlink("$execdir/logs/lond.pid");
1.190     albertel 6870:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165     albertel 6871:     &status("Done killing children");
1.1       albertel 6872:     exit;                           # clean up with dignity
                   6873: }
                   6874: 
                   6875: sub HUPSMAN {                      # signal handler for SIGHUP
                   6876:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 6877:     &status("Killing children for restart (HUP)");
1.1       albertel 6878:     kill 'INT' => keys %children;
1.59      www      6879:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190     albertel 6880:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134     albertel 6881:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 6882:     unlink("$execdir/logs/lond.pid");
1.165     albertel 6883:     &status("Restarting self (HUP)");
1.1       albertel 6884:     exec("$execdir/lond");         # here we go again
                   6885: }
                   6886: 
1.144     foxr     6887: #
1.148     foxr     6888: #  Reload the Apache daemon's state.
1.150     foxr     6889: #  This is done by invoking /home/httpd/perl/apachereload
                   6890: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     6891: #
                   6892: sub ReloadApache {
1.473     raeburn  6893: # --------------------------- Handle case of another apachereload process (locking)
1.474     raeburn  6894:     if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
                   6895:         my $execdir = $perlvar{'lonDaemons'};
                   6896:         my $script  = $execdir."/apachereload";
                   6897:         system($script);
                   6898:         unlink('/tmp/lock_apachereload'); #  Remove the lock file.
                   6899:     }
1.148     foxr     6900: }
                   6901: 
                   6902: #
1.144     foxr     6903: #   Called in response to a USR2 signal.
                   6904: #   - Reread hosts.tab
                   6905: #   - All children connected to hosts that were removed from hosts.tab
                   6906: #     are killed via SIGINT
                   6907: #   - All children connected to previously existing hosts are sent SIGUSR1
                   6908: #   - Our internal hosts hash is updated to reflect the new contents of
                   6909: #     hosts.tab causing connections from hosts added to hosts.tab to
                   6910: #     now be honored.
                   6911: #
                   6912: sub UpdateHosts {
1.165     albertel 6913:     &status("Reload hosts.tab");
1.147     foxr     6914:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     6915:     #
                   6916:     #  The %children hash has the set of IP's we currently have children
                   6917:     #  on.  These need to be matched against records in the hosts.tab
                   6918:     #  Any ip's no longer in the table get killed off they correspond to
                   6919:     #  either dropped or changed hosts.  Note that the re-read of the table
                   6920:     #  will take care of new and changed hosts as connections come into being.
                   6921: 
1.371     albertel 6922:     &Apache::lonnet::reset_hosts_info();
1.532     raeburn  6923:     my %active;
1.148     foxr     6924: 
1.368     albertel 6925:     foreach my $child (keys(%children)) {
1.148     foxr     6926: 	my $childip = $children{$child};
1.374     albertel 6927: 	if ($childip ne '127.0.0.1'
                   6928: 	    && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
1.149     foxr     6929: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   6930: 		    ." $child for ip $childip </font>");
1.148     foxr     6931: 	    kill('INT', $child);
1.149     foxr     6932: 	} else {
1.532     raeburn  6933:             $active{$child} = $childip;
1.149     foxr     6934: 	    logthis('<font color="green"> keeping child for ip '
                   6935: 		    ." $childip (pid=$child) </font>");
1.148     foxr     6936: 	}
                   6937:     }
1.532     raeburn  6938: 
                   6939:     my %oldconf = %secureconf;
                   6940:     my %connchange;
                   6941:     if (lonssl::Read_Connect_Config(\%secureconf,\%perlvar) eq 'ok') {
                   6942:         logthis('<font color="blue"> Reloaded SSL connection rules </font>');
                   6943:     } else {
                   6944:         logthis('<font color="yellow"> Failed to reload SSL connection rules </font>');
                   6945:     }
                   6946:     if ((ref($oldconf{'connfrom'}) eq 'HASH') && (ref($secureconf{'connfrom'}) eq 'HASH')) {
                   6947:         foreach my $type ('dom','intdom','other') {
                   6948:             if ((($oldconf{'connfrom'}{$type} eq 'no') && ($secureconf{'connfrom'}{$type} eq 'req')) ||
                   6949:                 (($oldconf{'connfrom'}{$type} eq 'req') && ($secureconf{'connfrom'}{$type} eq 'no'))) {
                   6950:                 $connchange{$type} = 1;
                   6951:             }
                   6952:         }
                   6953:     }
                   6954:     if (keys(%connchange)) {
                   6955:         foreach my $child (keys(%active)) {
                   6956:             my $childip = $active{$child};
                   6957:             if ($childip ne '127.0.0.1') {
                   6958:                 my $childhostname  = gethostbyaddr(Socket::inet_aton($childip),AF_INET);
                   6959:                 if ($childhostname ne '') {
                   6960:                     my $childlonhost = &Apache::lonnet::get_server_homeID($childhostname);
                   6961:                     my ($samedom,$sameinst) = &set_client_info($childlonhost);
                   6962:                     if ($samedom) {
                   6963:                         if ($connchange{'dom'}) {
                   6964:                             logthis('<font color="blue"> UpdateHosts killing child '
                   6965:                                    ." $child for ip $childip </font>");
                   6966:                             kill('INT', $child);
                   6967:                         }
                   6968:                     } elsif ($sameinst) {
                   6969:                         if ($connchange{'intdom'}) {
                   6970:                             logthis('<font color="blue"> UpdateHosts killing child '
                   6971:                                    ." $child for ip $childip </font>");
                   6972:                            kill('INT', $child);
                   6973:                         }
                   6974:                     } else {
                   6975:                         if ($connchange{'other'}) {
                   6976:                             logthis('<font color="blue"> UpdateHosts killing child '
                   6977:                                    ." $child for ip $childip </font>");
                   6978:                             kill('INT', $child);
                   6979:                         }
                   6980:                     }
                   6981:                 }
                   6982:             }
                   6983:         }
                   6984:     }
1.148     foxr     6985:     ReloadApache;
1.165     albertel 6986:     &status("Finished reloading hosts.tab");
1.144     foxr     6987: }
                   6988: 
1.57      www      6989: sub checkchildren {
1.165     albertel 6990:     &status("Checking on the children (sending signals)");
1.57      www      6991:     &initnewstatus();
                   6992:     &logstatus();
                   6993:     &logthis('Going to check on the children');
1.134     albertel 6994:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 6995:     foreach (sort keys %children) {
1.221     albertel 6996: 	#sleep 1;
1.57      www      6997:         unless (kill 'USR1' => $_) {
                   6998: 	    &logthis ('Child '.$_.' is dead');
                   6999:             &logstatus($$.' is dead');
1.221     albertel 7000: 	    delete($children{$_});
1.57      www      7001:         } 
1.61      harris41 7002:     }
1.63      www      7003:     sleep 5;
1.212     foxr     7004:     $SIG{ALRM} = sub { Debug("timeout"); 
                   7005: 		       die "timeout";  };
1.113     albertel 7006:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 7007:     &status("Checking on the children (waiting for reports)");
1.63      www      7008:     foreach (sort keys %children) {
                   7009:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 7010:           eval {
                   7011:             alarm(300);
1.63      www      7012: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 7013: 	    kill 9 => $_;
1.131     albertel 7014: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   7015: 	    #$subj="LON: $currenthostid killed lond process $_";
                   7016: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   7017: 	    #$execdir=$perlvar{'lonDaemons'};
                   7018: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221     albertel 7019: 	    delete($children{$_});
1.113     albertel 7020: 	    alarm(0);
                   7021: 	  }
1.63      www      7022:         }
                   7023:     }
1.113     albertel 7024:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 7025:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 7026:     &status("Finished checking children");
1.221     albertel 7027:     &logthis('Finished Checking children');
1.57      www      7028: }
                   7029: 
1.1       albertel 7030: # --------------------------------------------------------------------- Logging
                   7031: 
                   7032: sub logthis {
                   7033:     my $message=shift;
                   7034:     my $execdir=$perlvar{'lonDaemons'};
                   7035:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   7036:     my $now=time;
                   7037:     my $local=localtime($now);
1.58      www      7038:     $lastlog=$local.': '.$message;
1.1       albertel 7039:     print $fh "$local ($$): $message\n";
                   7040: }
                   7041: 
1.77      foxr     7042: # ------------------------- Conditional log if $DEBUG true.
                   7043: sub Debug {
                   7044:     my $message = shift;
                   7045:     if($DEBUG) {
                   7046: 	&logthis($message);
                   7047:     }
                   7048: }
1.161     foxr     7049: 
                   7050: #
                   7051: #   Sub to do replies to client.. this gives a hook for some
                   7052: #   debug tracing too:
                   7053: #  Parameters:
                   7054: #     fd      - File open on client.
                   7055: #     reply   - Text to send to client.
                   7056: #     request - Original request from client.
                   7057: #
1.490     droeschl 7058: #NOTE $reply must be terminated by exactly *one* \n. If $reply is a reference
                   7059: #this is done automatically ($$reply must not contain any \n in this case). 
                   7060: #If $reply is a string the caller has to ensure this.
1.161     foxr     7061: sub Reply {
1.192     foxr     7062:     my ($fd, $reply, $request) = @_;
1.387     albertel 7063:     if (ref($reply)) {
                   7064: 	print $fd $$reply;
                   7065: 	print $fd "\n";
                   7066: 	if ($DEBUG) { Debug("Request was $request  Reply was $$reply"); }
                   7067:     } else {
                   7068: 	print $fd $reply;
                   7069: 	if ($DEBUG) { Debug("Request was $request  Reply was $reply"); }
                   7070:     }
1.212     foxr     7071:     $Transactions++;
                   7072: }
                   7073: 
                   7074: 
                   7075: #
                   7076: #    Sub to report a failure.
                   7077: #    This function:
                   7078: #     -   Increments the failure statistic counters.
                   7079: #     -   Invokes Reply to send the error message to the client.
                   7080: # Parameters:
                   7081: #    fd       - File descriptor open on the client
                   7082: #    reply    - Reply text to emit.
                   7083: #    request  - The original request message (used by Reply
                   7084: #               to debug if that's enabled.
                   7085: # Implicit outputs:
                   7086: #    $Failures- The number of failures is incremented.
                   7087: #    Reply (invoked here) sends a message to the 
                   7088: #    client:
                   7089: #
                   7090: sub Failure {
                   7091:     my $fd      = shift;
                   7092:     my $reply   = shift;
                   7093:     my $request = shift;
                   7094:    
                   7095:     $Failures++;
                   7096:     Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     7097: }
1.57      www      7098: # ------------------------------------------------------------------ Log status
                   7099: 
                   7100: sub logstatus {
1.178     foxr     7101:     &status("Doing logging");
                   7102:     my $docdir=$perlvar{'lonDocRoot'};
                   7103:     {
                   7104: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200     matthew  7105:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178     foxr     7106:         $fh->close();
                   7107:     }
1.221     albertel 7108:     &status("Finished $$.txt");
                   7109:     {
                   7110: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
                   7111: 	flock(LOG,LOCK_EX);
                   7112: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
                   7113: 	    .$status."\t".$lastlog."\t $keymode\n";
1.275     albertel 7114: 	flock(LOG,LOCK_UN);
1.221     albertel 7115: 	close(LOG);
                   7116:     }
1.178     foxr     7117:     &status("Finished logging");
1.57      www      7118: }
                   7119: 
                   7120: sub initnewstatus {
                   7121:     my $docdir=$perlvar{'lonDocRoot'};
                   7122:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
1.460     foxr     7123:     my $now=time();
1.57      www      7124:     my $local=localtime($now);
                   7125:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      7126:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 7127:     while (my $filename=readdir(DIR)) {
1.64      www      7128:         unlink("$docdir/lon-status/londchld/$filename");
                   7129:     }
                   7130:     closedir(DIR);
1.57      www      7131: }
                   7132: 
                   7133: # -------------------------------------------------------------- Status setting
                   7134: 
                   7135: sub status {
                   7136:     my $what=shift;
                   7137:     my $now=time;
                   7138:     my $local=localtime($now);
1.178     foxr     7139:     $status=$local.': '.$what;
                   7140:     $0='lond: '.$what.' '.$local;
1.57      www      7141: }
1.11      www      7142: 
1.13      www      7143: # -------------------------------------------------------------- Talk to lonsql
                   7144: 
1.234     foxr     7145: sub sql_reply {
1.12      harris41 7146:     my ($cmd)=@_;
1.234     foxr     7147:     my $answer=&sub_sql_reply($cmd);
                   7148:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12      harris41 7149:     return $answer;
                   7150: }
                   7151: 
1.234     foxr     7152: sub sub_sql_reply {
1.12      harris41 7153:     my ($cmd)=@_;
                   7154:     my $unixsock="mysqlsock";
                   7155:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   7156:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   7157:                                       Type    => SOCK_STREAM,
                   7158:                                       Timeout => 10)
                   7159:        or return "con_lost";
1.319     www      7160:     print $sclient "$cmd:$currentdomainid\n";
1.12      harris41 7161:     my $answer=<$sclient>;
                   7162:     chomp($answer);
                   7163:     if (!$answer) { $answer="con_lost"; }
                   7164:     return $answer;
                   7165: }
                   7166: 
1.1       albertel 7167: # --------------------------------------- Is this the home server of an author?
1.11      www      7168: 
1.1       albertel 7169: sub ishome {
                   7170:     my $author=shift;
                   7171:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   7172:     my ($udom,$uname)=split(/\//,$author);
                   7173:     my $proname=propath($udom,$uname);
                   7174:     if (-e $proname) {
                   7175: 	return 'owner';
                   7176:     } else {
                   7177:         return 'not_owner';
                   7178:     }
                   7179: }
                   7180: 
                   7181: # ======================================================= Continue main program
                   7182: # ---------------------------------------------------- Fork once and dissociate
                   7183: 
1.134     albertel 7184: my $fpid=fork;
1.1       albertel 7185: exit if $fpid;
1.29      harris41 7186: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 7187: 
1.29      harris41 7188: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 7189: 
                   7190: # ------------------------------------------------------- Write our PID on disk
                   7191: 
1.134     albertel 7192: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 7193: open (PIDSAVE,">$execdir/logs/lond.pid");
                   7194: print PIDSAVE "$$\n";
                   7195: close(PIDSAVE);
1.190     albertel 7196: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57      www      7197: &status('Starting');
1.1       albertel 7198: 
1.106     foxr     7199: 
1.1       albertel 7200: 
                   7201: # ----------------------------------------------------- Install signal handlers
                   7202: 
1.57      www      7203: 
1.1       albertel 7204: $SIG{CHLD} = \&REAPER;
                   7205: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   7206: $SIG{HUP}  = \&HUPSMAN;
1.57      www      7207: $SIG{USR1} = \&checkchildren;
1.144     foxr     7208: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     7209: 
1.148     foxr     7210: #  Read the host hashes:
1.368     albertel 7211: &Apache::lonnet::load_hosts_tab();
1.447     raeburn  7212: my %iphost = &Apache::lonnet::get_iphost(1);
1.106     foxr     7213: 
1.480     raeburn  7214: $dist=`$perlvar{'lonDaemons'}/distprobe`;
1.286     albertel 7215: 
1.471     raeburn  7216: my $arch = `uname -i`;
1.475     raeburn  7217: chomp($arch);
1.471     raeburn  7218: if ($arch eq 'unknown') {
                   7219:     $arch = `uname -m`;
1.475     raeburn  7220:     chomp($arch);
1.471     raeburn  7221: }
                   7222: 
1.532     raeburn  7223: unless (lonssl::Read_Connect_Config(\%secureconf,\%perlvar) eq 'ok') {
                   7224:     &logthis('<font color="blue">No connectionrules table. Will fallback to loncapa.conf</font>');
                   7225: }
                   7226: 
1.106     foxr     7227: # --------------------------------------------------------------
                   7228: #   Accept connections.  When a connection comes in, it is validated
                   7229: #   and if good, a child process is created to process transactions
                   7230: #   along the connection.
                   7231: 
1.1       albertel 7232: while (1) {
1.165     albertel 7233:     &status('Starting accept');
1.106     foxr     7234:     $client = $server->accept() or next;
1.165     albertel 7235:     &status('Accepted '.$client.' off to spawn');
1.386     albertel 7236:     make_new_child($client);
1.165     albertel 7237:     &status('Finished spawning');
1.1       albertel 7238: }
                   7239: 
1.212     foxr     7240: sub make_new_child {
                   7241:     my $pid;
                   7242: #    my $cipher;     # Now global
                   7243:     my $sigset;
1.178     foxr     7244: 
1.212     foxr     7245:     $client = shift;
                   7246:     &status('Starting new child '.$client);
                   7247:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   7248: 	     ")</font>");    
                   7249:     # block signal for fork
                   7250:     $sigset = POSIX::SigSet->new(SIGINT);
                   7251:     sigprocmask(SIG_BLOCK, $sigset)
                   7252:         or die "Can't block SIGINT for fork: $!\n";
1.178     foxr     7253: 
1.212     foxr     7254:     die "fork: $!" unless defined ($pid = fork);
1.178     foxr     7255: 
1.212     foxr     7256:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   7257: 	                               # connection liveness.
1.178     foxr     7258: 
1.212     foxr     7259:     #
                   7260:     #  Figure out who we're talking to so we can record the peer in 
                   7261:     #  the pid hash.
                   7262:     #
                   7263:     my $caller = getpeername($client);
                   7264:     my ($port,$iaddr);
                   7265:     if (defined($caller) && length($caller) > 0) {
                   7266: 	($port,$iaddr)=unpack_sockaddr_in($caller);
                   7267:     } else {
                   7268: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
                   7269:     }
                   7270:     if (defined($iaddr)) {
                   7271: 	$clientip  = inet_ntoa($iaddr);
                   7272: 	Debug("Connected with $clientip");
                   7273:     } else {
                   7274: 	&logthis("Unable to determine clientip");
                   7275: 	$clientip='Unavailable';
                   7276:     }
                   7277:     
                   7278:     if ($pid) {
                   7279:         # Parent records the child's birth and returns.
                   7280:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7281:             or die "Can't unblock SIGINT for fork: $!\n";
                   7282:         $children{$pid} = $clientip;
                   7283:         &status('Started child '.$pid);
1.462     foxr     7284: 	close($client);
1.212     foxr     7285:         return;
                   7286:     } else {
                   7287:         # Child can *not* return from this subroutine.
                   7288:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                   7289:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   7290:                                 #don't get intercepted
                   7291:         $SIG{USR1}= \&logstatus;
                   7292:         $SIG{ALRM}= \&timeout;
1.468     foxr     7293: 	#
                   7294: 	# Block sigpipe as it gets thrownon socket disconnect and we want to 
                   7295: 	# deal with that as a read faiure instead.
                   7296: 	#
                   7297: 	my $blockset = POSIX::SigSet->new(SIGPIPE);
                   7298: 	sigprocmask(SIG_BLOCK, $blockset);
                   7299: 
1.212     foxr     7300:         $lastlog='Forked ';
                   7301:         $status='Forked';
1.178     foxr     7302: 
1.212     foxr     7303:         # unblock signals
                   7304:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7305:             or die "Can't unblock SIGINT for fork: $!\n";
1.178     foxr     7306: 
1.212     foxr     7307: #        my $tmpsnum=0;            # Now global
                   7308: #---------------------------------------------------- kerberos 5 initialization
                   7309:         &Authen::Krb5::init_context();
1.511     raeburn  7310: 
                   7311:         my $no_ets;
1.514     raeburn  7312:         if ($dist =~ /^(?:centos|rhes|scientific)(\d+)$/) {
1.511     raeburn  7313:             if ($1 >= 7) {
                   7314:                 $no_ets = 1;
                   7315:             }
                   7316:         } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
                   7317:             if (($1 eq '9.3') || ($1 >= 12.2)) {
                   7318:                 $no_ets = 1; 
                   7319:             }
1.514     raeburn  7320:         } elsif ($dist =~ /^sles(\d+)$/) {
                   7321:             if ($1 > 11) {
                   7322:                 $no_ets = 1;
                   7323:             }
1.511     raeburn  7324:         } elsif ($dist =~ /^fedora(\d+)$/) {
                   7325:             if ($1 < 7) {
                   7326:                 $no_ets = 1;
                   7327:             }
                   7328:         }
                   7329:         unless ($no_ets) {
1.286     albertel 7330: 	    &Authen::Krb5::init_ets();
                   7331: 	}
1.209     albertel 7332: 
1.212     foxr     7333: 	&status('Accepted connection');
                   7334: # =============================================================================
                   7335:             # do something with the connection
                   7336: # -----------------------------------------------------------------------------
                   7337: 	# see if we know client and 'check' for spoof IP by ineffective challenge
1.178     foxr     7338: 
1.278     albertel 7339: 	my $outsideip=$clientip;
                   7340: 	if ($clientip eq '127.0.0.1') {
1.368     albertel 7341: 	    $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
1.278     albertel 7342: 	}
1.412     foxr     7343: 	&ReadManagerTable();
1.368     albertel 7344: 	my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
1.278     albertel 7345: 	my $ismanager=($managers{$outsideip}    ne undef);
1.432     raeburn  7346: 	$clientname  = "[unknown]";
1.212     foxr     7347: 	if($clientrec) {	# Establish client type.
                   7348: 	    $ConnectionType = "client";
1.368     albertel 7349: 	    $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
1.212     foxr     7350: 	    if($ismanager) {
                   7351: 		$ConnectionType = "both";
                   7352: 	    }
                   7353: 	} else {
                   7354: 	    $ConnectionType = "manager";
1.278     albertel 7355: 	    $clientname = $managers{$outsideip};
1.212     foxr     7356: 	}
1.532     raeburn  7357: 	my ($clientok,$clientinfoset);
1.178     foxr     7358: 
1.212     foxr     7359: 	if ($clientrec || $ismanager) {
                   7360: 	    &status("Waiting for init from $clientip $clientname");
                   7361: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   7362: 		     $clientip.
                   7363: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   7364: 	    &status("Connecting $clientip  ($clientname))"); 
                   7365: 	    my $remotereq=<$client>;
                   7366: 	    chomp($remotereq);
                   7367: 	    Debug("Got init: $remotereq");
1.337     albertel 7368: 
1.212     foxr     7369: 	    if ($remotereq =~ /^init/) {
                   7370: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   7371: 		#
                   7372: 		#  If the remote is attempting a local init... give that a try:
                   7373: 		#
1.432     raeburn  7374: 		(my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
1.492     droeschl 7375:         # For LON-CAPA 2.9, the  client session will have sent its LON-CAPA
                   7376:         # version when initiating the connection. For LON-CAPA 2.8 and older,
                   7377:         # the version is retrieved from the global %loncaparevs in lonnet.pm.            
1.494     droeschl 7378:         # $clientversion contains path to keyfile if $inittype eq 'local'
                   7379:         # it's overridden below in this case
1.492     droeschl 7380:         $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
1.209     albertel 7381: 
1.212     foxr     7382: 		# If the connection type is ssl, but I didn't get my
                   7383: 		# certificate files yet, then I'll drop  back to 
                   7384: 		# insecure (if allowed).
1.532     raeburn  7385: 
                   7386:                 if ($inittype eq "ssl") {
                   7387:                     my $context;
                   7388:                     if ($clientsamedom) {
                   7389:                         $context = 'dom';
                   7390:                         if ($secureconf{'connfrom'}{'dom'} eq 'no') {
                   7391:                             $inittype = "";
                   7392:                         }
                   7393:                     } elsif ($clientsameinst) {
                   7394:                         $context = 'intdom';
                   7395:                         if ($secureconf{'connfrom'}{'intdom'} eq 'no') {
                   7396:                             $inittype = "";
                   7397:                         }
                   7398:                     } else {
                   7399:                         $context = 'other';
                   7400:                         if ($secureconf{'connfrom'}{'other'} eq 'no') {
                   7401:                             $inittype = "";
                   7402:                         }
                   7403:                     }
                   7404:                     if ($inittype eq '') {
                   7405:                         &logthis("<font color=\"blue\"> Domain config set "
                   7406:                                 ."to no ssl for $clientname (context: $context)"
                   7407:                                 ." -- trying insecure auth</font>");
                   7408:                     }
                   7409:                 }
                   7410: 
1.212     foxr     7411: 		if($inittype eq "ssl") {
                   7412: 		    my ($ca, $cert) = lonssl::CertificateFile;
                   7413: 		    my $kfile       = lonssl::KeyFile;
                   7414: 		    if((!$ca)   || 
                   7415: 		       (!$cert) || 
                   7416: 		       (!$kfile)) {
                   7417: 			$inittype = ""; # This forces insecure attempt.
                   7418: 			&logthis("<font color=\"blue\"> Certificates not "
                   7419: 				 ."installed -- trying insecure auth</font>");
1.224     foxr     7420: 		    } else {	# SSL certificates are in place so
1.212     foxr     7421: 		    }		# Leave the inittype alone.
                   7422: 		}
                   7423: 
                   7424: 		if($inittype eq "local") {
1.432     raeburn  7425:                     $clientversion = $perlvar{'lonVersion'};
1.212     foxr     7426: 		    my $key = LocalConnection($client, $remotereq);
                   7427: 		    if($key) {
                   7428: 			Debug("Got local key $key");
                   7429: 			$clientok     = 1;
                   7430: 			my $cipherkey = pack("H32", $key);
                   7431: 			$cipher       = new IDEA($cipherkey);
                   7432: 			print $client "ok:local\n";
1.442     www      7433: 			&logthis('<font color="green">'
1.212     foxr     7434: 				 . "Successful local authentication </font>");
                   7435: 			$keymode = "local"
1.178     foxr     7436: 		    } else {
1.212     foxr     7437: 			Debug("Failed to get local key");
                   7438: 			$clientok = 0;
                   7439: 			shutdown($client, 3);
                   7440: 			close $client;
1.178     foxr     7441: 		    }
1.212     foxr     7442: 		} elsif ($inittype eq "ssl") {
1.532     raeburn  7443: 		    my $key = SSLConnection($client,$clientname);
1.212     foxr     7444: 		    if ($key) {
                   7445: 			$clientok = 1;
                   7446: 			my $cipherkey = pack("H32", $key);
                   7447: 			$cipher       = new IDEA($cipherkey);
                   7448: 			&logthis('<font color="green">'
                   7449: 				 ."Successfull ssl authentication with $clientname </font>");
                   7450: 			$keymode = "ssl";
                   7451: 	     
1.178     foxr     7452: 		    } else {
1.212     foxr     7453: 			$clientok = 0;
                   7454: 			close $client;
1.178     foxr     7455: 		    }
1.212     foxr     7456: 	   
                   7457: 		} else {
1.532     raeburn  7458:                     $clientinfoset = &set_client_info();
1.212     foxr     7459: 		    my $ok = InsecureConnection($client);
                   7460: 		    if($ok) {
                   7461: 			$clientok = 1;
                   7462: 			&logthis('<font color="green">'
                   7463: 				 ."Successful insecure authentication with $clientname </font>");
                   7464: 			print $client "ok\n";
                   7465: 			$keymode = "insecure";
1.178     foxr     7466: 		    } else {
1.212     foxr     7467: 			&logthis('<font color="yellow">'
                   7468: 				  ."Attempted insecure connection disallowed </font>");
                   7469: 			close $client;
                   7470: 			$clientok = 0;
1.178     foxr     7471: 		    }
                   7472: 		}
1.212     foxr     7473: 	    } else {
                   7474: 		&logthis(
                   7475: 			 "<font color='blue'>WARNING: "
                   7476: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   7477: 		&status('No init '.$clientip);
                   7478: 	    }
                   7479: 	} else {
                   7480: 	    &logthis(
                   7481: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
                   7482: 	    &status('Hung up on '.$clientip);
                   7483: 	}
                   7484:  
                   7485: 	if ($clientok) {
                   7486: # ---------------- New known client connecting, could mean machine online again
1.368     albertel 7487: 	    if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip 
1.367     albertel 7488: 		&& $clientip ne '127.0.0.1') {
1.375     albertel 7489: 		&Apache::lonnet::reconlonc($clientname);
1.212     foxr     7490: 	    }
                   7491: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
                   7492: 	    &status('Will listen to '.$clientname);
                   7493: # ------------------------------------------------------------ Process requests
                   7494: 	    my $keep_going = 1;
                   7495: 	    my $user_input;
1.532     raeburn  7496:             unless ($clientinfoset) {
                   7497:                 $clientinfoset = &set_client_info();
1.525     raeburn  7498:             }
                   7499:             $clientremoteok = 0;
                   7500:             unless ($clientsameinst) {
                   7501:                 $clientremoteok = 1;
                   7502:                 my $defdom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   7503:                 %clientprohibited = &get_prohibited($defdom);
                   7504:                 if ($clientintdom) {
                   7505:                     my $remsessconf = &get_usersession_config($defdom,'remotesession');
                   7506:                     if (ref($remsessconf) eq 'HASH') {
                   7507:                         if (ref($remsessconf->{'remote'}) eq 'HASH') {
                   7508:                             if (ref($remsessconf->{'remote'}->{'excludedomain'}) eq 'ARRAY') {
                   7509:                                 if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'excludedomain'}})) {
                   7510:                                     $clientremoteok = 0;
                   7511:                                 }
                   7512:                             }
                   7513:                             if (ref($remsessconf->{'remote'}->{'includedomain'}) eq 'ARRAY') {
                   7514:                                 if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'includedomain'}})) {
                   7515:                                     $clientremoteok = 1;
                   7516:                                 } else {
                   7517:                                     $clientremoteok = 0;
                   7518:                                 }
                   7519:                             }
                   7520:                         }
                   7521:                     }
                   7522:                 }
                   7523:             }
1.212     foxr     7524: 	    while(($user_input = get_request) && $keep_going) {
                   7525: 		alarm(120);
                   7526: 		Debug("Main: Got $user_input\n");
                   7527: 		$keep_going = &process_request($user_input);
1.178     foxr     7528: 		alarm(0);
1.212     foxr     7529: 		&status('Listening to '.$clientname." ($keymode)");	   
1.161     foxr     7530: 	    }
1.212     foxr     7531: 
1.59      www      7532: # --------------------------------------------- client unknown or fishy, refuse
1.212     foxr     7533: 	}  else {
1.161     foxr     7534: 	    print $client "refused\n";
                   7535: 	    $client->close();
1.190     albertel 7536: 	    &logthis("<font color='blue'>WARNING: "
1.161     foxr     7537: 		     ."Rejected client $clientip, closing connection</font>");
                   7538: 	}
1.525     raeburn  7539:     }
1.161     foxr     7540:     
1.1       albertel 7541: # =============================================================================
1.161     foxr     7542:     
1.190     albertel 7543:     &logthis("<font color='red'>CRITICAL: "
1.161     foxr     7544: 	     ."Disconnect from $clientip ($clientname)</font>");    
                   7545:     
                   7546:     
                   7547:     # this exit is VERY important, otherwise the child will become
                   7548:     # a producer of more and more children, forking yourself into
                   7549:     # process death.
                   7550:     exit;
1.106     foxr     7551:     
1.78      foxr     7552: }
1.532     raeburn  7553: 
                   7554: #
                   7555: #  Used to determine if a particular client is from the same domain
                   7556: #  as the current server, or from the same internet domain.
                   7557: #
                   7558: #  Optional input -- the client to check for domain and internet domain.
                   7559: #  If not specified, defaults to the package variable: $clientname
                   7560: #
                   7561: #  If called in array context will not set package variables, but will
                   7562: #  instead return an array of two values - (a) true if client is in the
                   7563: #  same domain as the server, and (b) true if client is in the same internet
                   7564: #  domain.
                   7565: #
                   7566: #  If called in scalar context, sets package variables for current client:
                   7567: #
                   7568: #  $clienthomedom  - LonCAPA domain of homeID for client.
                   7569: #  $clientsamedom  - LonCAPA domain same for this host and client.
                   7570: #  $clientintdom   - LonCAPA "internet domain" for client.
                   7571: #  $clientsameinst - LonCAPA "internet domain" same for this host & client.
                   7572: #
                   7573: #  returns 1 to indicate package variables have been set for current client.
                   7574: #
                   7575: 
                   7576: sub set_client_info {
                   7577:     my ($lonhost) = @_;
                   7578:     $lonhost ||= $clientname;
                   7579:     my $clienthost = &Apache::lonnet::hostname($lonhost);
                   7580:     my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
                   7581:     my $homedom = &Apache::lonnet::host_domain($clientserverhomeID);
                   7582:     my $samedom = 0;
                   7583:     if ($perlvar{'lonDefDom'} eq $homedom) {
                   7584:         $samedom = 1;
                   7585:     }
                   7586:     my $intdom = &Apache::lonnet::internet_dom($clientserverhomeID);
                   7587:     my $sameinst = 0;
                   7588:     if ($intdom ne '') {
                   7589:         my $internet_names = &Apache::lonnet::get_internet_names($currenthostid);
                   7590:         if (ref($internet_names) eq 'ARRAY') {
                   7591:             if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   7592:                 $sameinst = 1;
                   7593:             }
                   7594:         }
                   7595:     }
                   7596:     if (wantarray) {
                   7597:         return ($samedom,$sameinst);
                   7598:     } else {
                   7599:         $clienthomedom = $homedom;
                   7600:         $clientsamedom = $samedom;
                   7601:         $clientintdom = $intdom;
                   7602:         $clientsameinst = $sameinst;
                   7603:         return 1;
                   7604:     }
                   7605: }
                   7606: 
1.261     foxr     7607: #
                   7608: #   Determine if a user is an author for the indicated domain.
                   7609: #
                   7610: # Parameters:
                   7611: #    domain          - domain to check in .
                   7612: #    user            - Name of user to check.
                   7613: #
                   7614: # Return:
                   7615: #     1             - User is an author for domain.
                   7616: #     0             - User is not an author for domain.
                   7617: sub is_author {
                   7618:     my ($domain, $user) = @_;
                   7619: 
                   7620:     &Debug("is_author: $user @ $domain");
                   7621: 
                   7622:     my $hashref = &tie_user_hash($domain, $user, "roles",
                   7623: 				 &GDBM_READER());
                   7624: 
                   7625:     #  Author role should show up as a key /domain/_au
1.78      foxr     7626: 
1.321     albertel 7627:     my $value;
1.487     foxr     7628:     if ($hashref) {
1.78      foxr     7629: 
1.487     foxr     7630: 	my $key    = "/$domain/_au";
                   7631: 	if (defined($hashref)) {
                   7632: 	    $value = $hashref->{$key};
                   7633: 	    if(!untie_user_hash($hashref)) {
                   7634: 		return 'error: ' .  ($!+0)." untie (GDBM) Failed";
                   7635: 	    }
                   7636: 	}
                   7637: 	
                   7638: 	if(defined($value)) {
                   7639: 	    &Debug("$user @ $domain is an author");
                   7640: 	}
                   7641:     } else {
                   7642: 	return 'error: '.($!+0)." tie (GDBM) Failed";
1.261     foxr     7643:     }
                   7644: 
                   7645:     return defined($value);
                   7646: }
1.78      foxr     7647: #
                   7648: #   Checks to see if the input roleput request was to set
1.482     www      7649: # an author role.  If so, creates construction space 
1.78      foxr     7650: # Parameters:
                   7651: #    request   - The request sent to the rolesput subchunk.
                   7652: #                We're looking for  /domain/_au
                   7653: #    domain    - The domain in which the user is having roles doctored.
                   7654: #    user      - Name of the user for which the role is being put.
                   7655: #    authtype  - The authentication type associated with the user.
                   7656: #
1.289     albertel 7657: sub manage_permissions {
1.192     foxr     7658:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     7659:     # See if the request is of the form /$domain/_au
1.289     albertel 7660:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.484     raeburn  7661:         my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
1.482     www      7662:         unless (-e $path) {        
                   7663:            mkdir($path);
                   7664:         }
                   7665:         unless (-e $path.'/'.$user) {
                   7666:            mkdir($path.'/'.$user);
                   7667:         }
1.78      foxr     7668:     }
                   7669: }
1.222     foxr     7670: 
                   7671: 
                   7672: #
                   7673: #  Return the full path of a user password file, whether it exists or not.
                   7674: # Parameters:
                   7675: #   domain     - Domain in which the password file lives.
                   7676: #   user       - name of the user.
                   7677: # Returns:
                   7678: #    Full passwd path:
                   7679: #
                   7680: sub password_path {
                   7681:     my ($domain, $user) = @_;
1.264     albertel 7682:     return &propath($domain, $user).'/passwd';
1.222     foxr     7683: }
                   7684: 
                   7685: #   Password Filename
                   7686: #   Returns the path to a passwd file given domain and user... only if
                   7687: #  it exists.
                   7688: # Parameters:
                   7689: #   domain    - Domain in which to search.
                   7690: #   user      - username.
                   7691: # Returns:
                   7692: #   - If the password file exists returns its path.
                   7693: #   - If the password file does not exist, returns undefined.
                   7694: #
                   7695: sub password_filename {
                   7696:     my ($domain, $user) = @_;
                   7697: 
                   7698:     Debug ("PasswordFilename called: dom = $domain user = $user");
                   7699: 
                   7700:     my $path  = &password_path($domain, $user);
                   7701:     Debug("PasswordFilename got path: $path");
                   7702:     if(-e $path) {
                   7703: 	return $path;
                   7704:     } else {
                   7705: 	return undef;
                   7706:     }
                   7707: }
                   7708: 
                   7709: #
                   7710: #   Rewrite the contents of the user's passwd file.
                   7711: #  Parameters:
                   7712: #    domain    - domain of the user.
                   7713: #    name      - User's name.
                   7714: #    contents  - New contents of the file.
1.533     raeburn  7715: #    saveold   - (optional). If true save old file in a passwd.bak file.
1.222     foxr     7716: # Returns:
                   7717: #   0    - Failed.
                   7718: #   1    - Success.
                   7719: #
                   7720: sub rewrite_password_file {
1.533     raeburn  7721:     my ($domain, $user, $contents, $saveold) = @_;
1.222     foxr     7722: 
                   7723:     my $file = &password_filename($domain, $user);
                   7724:     if (defined $file) {
1.533     raeburn  7725:         if ($saveold) {
                   7726:             my $bakfile = $file.'.bak';
                   7727:             if (CopyFile($file,$bakfile)) {
                   7728:                 chmod(0400,$bakfile);
                   7729:                 &logthis("Old password saved in passwd.bak for internally authenticated user: $user:$domain");
                   7730:             } else {
                   7731:                 &logthis("Failed to save old password in passwd.bak for internally authenticated user: $user:$domain");
                   7732:             }
                   7733:         }
1.222     foxr     7734: 	my $pf = IO::File->new(">$file");
                   7735: 	if($pf) {
                   7736: 	    print $pf "$contents\n";
                   7737: 	    return 1;
                   7738: 	} else {
                   7739: 	    return 0;
                   7740: 	}
                   7741:     } else {
                   7742: 	return 0;
                   7743:     }
                   7744: 
                   7745: }
                   7746: 
1.78      foxr     7747: #
1.222     foxr     7748: #   get_auth_type - Determines the authorization type of a user in a domain.
1.78      foxr     7749: 
                   7750: #     Returns the authorization type or nouser if there is no such user.
                   7751: #
1.436     raeburn  7752: sub get_auth_type {
1.192     foxr     7753:     my ($domain, $user)  = @_;
1.78      foxr     7754: 
1.222     foxr     7755:     Debug("get_auth_type( $domain, $user ) \n");
1.78      foxr     7756:     my $proname    = &propath($domain, $user); 
                   7757:     my $passwdfile = "$proname/passwd";
                   7758:     if( -e $passwdfile ) {
                   7759: 	my $pf = IO::File->new($passwdfile);
                   7760: 	my $realpassword = <$pf>;
                   7761: 	chomp($realpassword);
1.79      foxr     7762: 	Debug("Password info = $realpassword\n");
1.78      foxr     7763: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     7764: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.259     raeburn  7765: 	return "$authtype:$contentpwd";     
1.224     foxr     7766:     } else {
1.79      foxr     7767: 	Debug("Returning nouser");
1.78      foxr     7768: 	return "nouser";
                   7769:     }
1.1       albertel 7770: }
                   7771: 
1.220     foxr     7772: #
                   7773: #  Validate a user given their domain, name and password.  This utility
                   7774: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
                   7775: #  to validate the login credentials of a user.
                   7776: # Parameters:
                   7777: #    $domain    - The domain being logged into (this is required due to
                   7778: #                 the capability for multihomed systems.
                   7779: #    $user      - The name of the user being validated.
                   7780: #    $password  - The user's propoposed password.
                   7781: #
                   7782: # Returns:
                   7783: #     1        - The domain,user,pasword triplet corresponds to a valid
                   7784: #                user.
                   7785: #     0        - The domain,user,password triplet is not a valid user.
                   7786: #
                   7787: sub validate_user {
1.396     raeburn  7788:     my ($domain, $user, $password, $checkdefauth) = @_;
1.220     foxr     7789: 
                   7790:     # Why negative ~pi you may well ask?  Well this function is about
                   7791:     # authentication, and therefore very important to get right.
                   7792:     # I've initialized the flag that determines whether or not I've 
                   7793:     # validated correctly to a value it's not supposed to get.
                   7794:     # At the end of this function. I'll ensure that it's not still that
                   7795:     # value so we don't just wind up returning some accidental value
                   7796:     # as a result of executing an unforseen code path that
1.249     foxr     7797:     # did not set $validated.  At the end of valid execution paths,
                   7798:     # validated shoule be 1 for success or 0 for failuer.
1.220     foxr     7799: 
                   7800:     my $validated = -3.14159;
                   7801: 
                   7802:     #  How we authenticate is determined by the type of authentication
                   7803:     #  the user has been assigned.  If the authentication type is
                   7804:     #  "nouser", the user does not exist so we will return 0.
                   7805: 
1.222     foxr     7806:     my $contents = &get_auth_type($domain, $user);
1.220     foxr     7807:     my ($howpwd, $contentpwd) = split(/:/, $contents);
                   7808: 
                   7809:     my $null = pack("C",0);	# Used by kerberos auth types.
                   7810: 
1.395     raeburn  7811:     if ($howpwd eq 'nouser') {
1.396     raeburn  7812:         if ($checkdefauth) {
                   7813:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   7814:             if ($domdefaults{'auth_def'} eq 'localauth') {
                   7815:                 $howpwd = $domdefaults{'auth_def'};
                   7816:                 $contentpwd = $domdefaults{'auth_arg_def'};
                   7817:             } elsif ((($domdefaults{'auth_def'} eq 'krb4') || 
                   7818:                       ($domdefaults{'auth_def'} eq 'krb5')) &&
                   7819:                      ($domdefaults{'auth_arg_def'} ne '')) {
                   7820:                 $howpwd = $domdefaults{'auth_def'};
                   7821:                 $contentpwd = $domdefaults{'auth_arg_def'}; 
                   7822:             }
1.395     raeburn  7823:         }
1.533     raeburn  7824:     }
1.220     foxr     7825:     if ($howpwd ne 'nouser') {
                   7826: 	if($howpwd eq "internal") { # Encrypted is in local password file.
1.518     raeburn  7827:             if (length($contentpwd) == 13) {
                   7828:                 $validated = (crypt($password,$contentpwd) eq $contentpwd);
                   7829:                 if ($validated) {
1.533     raeburn  7830:                     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   7831:                     if ($domdefaults{'intauth_switch'}) {
                   7832:                         my $ncpass = &hash_passwd($domain,$password);
                   7833:                         my $saveold;
                   7834:                         if ($domdefaults{'intauth_switch'} == 2) {
                   7835:                             $saveold = 1;
                   7836:                         }
                   7837:                         if (&rewrite_password_file($domain,$user,"$howpwd:$ncpass",$saveold)) {
                   7838:                             &update_passwd_history($user,$domain,$howpwd,'conversion');
                   7839:                             &logthis("Validated password hashed with bcrypt for $user:$domain");
                   7840:                         }
1.518     raeburn  7841:                     }
                   7842:                 }
                   7843:             } else {
1.533     raeburn  7844:                 $validated = &check_internal_passwd($password,$contentpwd,$domain,$user);
1.518     raeburn  7845:             }
1.220     foxr     7846: 	}
                   7847: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
                   7848: 	    $contentpwd = (getpwnam($user))[1];
                   7849: 	    if($contentpwd) {
                   7850: 		if($contentpwd eq 'x') { # Shadow password file...
                   7851: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
                   7852: 		    open PWAUTH,  "|$pwauth_path" or
                   7853: 			die "Cannot invoke authentication";
                   7854: 		    print PWAUTH "$user\n$password\n";
                   7855: 		    close PWAUTH;
                   7856: 		    $validated = ! $?;
                   7857: 
                   7858: 		} else { 	         # Passwords in /etc/passwd. 
                   7859: 		    $validated = (crypt($password,
                   7860: 					$contentpwd) eq $contentpwd);
                   7861: 		}
                   7862: 	    } else {
                   7863: 		$validated = 0;
                   7864: 	    }
1.439     raeburn  7865: 	} elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
                   7866:             my $checkwithkrb5 = 0;
                   7867:             if ($dist =~/^fedora(\d+)$/) {
                   7868:                 if ($1 > 11) {
                   7869:                     $checkwithkrb5 = 1;
                   7870:                 }
                   7871:             } elsif ($dist =~ /^suse([\d.]+)$/) {
                   7872:                 if ($1 > 11.1) {
                   7873:                     $checkwithkrb5 = 1; 
                   7874:                 }
                   7875:             }
                   7876:             if ($checkwithkrb5) {
                   7877:                 $validated = &krb5_authen($password,$null,$user,$contentpwd);
                   7878:             } else {
                   7879:                 $validated = &krb4_authen($password,$null,$user,$contentpwd);
                   7880:             }
1.224     foxr     7881: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.439     raeburn  7882:             $validated = &krb5_authen($password,$null,$user,$contentpwd);
1.224     foxr     7883: 	} elsif ($howpwd eq "localauth") { 
1.220     foxr     7884: 	    #  Authenticate via installation specific authentcation method:
                   7885: 	    $validated = &localauth::localauth($user, 
                   7886: 					       $password, 
1.353     albertel 7887: 					       $contentpwd,
                   7888: 					       $domain);
1.358     albertel 7889: 	    if ($validated < 0) {
1.357     albertel 7890: 		&logthis("localauth for $contentpwd $user:$domain returned a $validated");
                   7891: 		$validated = 0;
                   7892: 	    }
1.224     foxr     7893: 	} else {			# Unrecognized auth is also bad.
1.220     foxr     7894: 	    $validated = 0;
                   7895: 	}
                   7896:     } else {
                   7897: 	$validated = 0;
                   7898:     }
                   7899:     #
                   7900:     #  $validated has the correct stat of the authentication:
                   7901:     #
                   7902: 
                   7903:     unless ($validated != -3.14159) {
1.249     foxr     7904: 	#  I >really really< want to know if this happens.
                   7905: 	#  since it indicates that user authentication is badly
                   7906: 	#  broken in some code path.
                   7907:         #
                   7908: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220     foxr     7909:     }
                   7910:     return $validated;
                   7911: }
                   7912: 
1.518     raeburn  7913: sub check_internal_passwd {
1.533     raeburn  7914:     my ($plainpass,$stored,$domain,$user) = @_;
1.518     raeburn  7915:     my (undef,$method,@rest) = split(/!/,$stored);
1.533     raeburn  7916:     if ($method eq 'bcrypt') {
1.518     raeburn  7917:         my $result = &hash_passwd($domain,$plainpass,@rest);
                   7918:         if ($result ne $stored) {
                   7919:             return 0;
                   7920:         }
1.533     raeburn  7921:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   7922:         if ($domdefaults{'intauth_check'}) {
                   7923:             # Upgrade to a larger number of rounds if necessary
                   7924:             my $defaultcost = $domdefaults{'intauth_cost'};
                   7925:             if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   7926:                 $defaultcost = 10;
                   7927:             }
                   7928:             if (int($rest[0])<int($defaultcost)) {
                   7929:                 if ($domdefaults{'intauth_check'} == 1) { 
                   7930:                     my $ncpass = &hash_passwd($domain,$plainpass);
                   7931:                     if (&rewrite_password_file($domain,$user,"internal:$ncpass")) {
                   7932:                         &update_passwd_history($user,$domain,'internal','update cost');
                   7933:                         &logthis("Validated password hashed with bcrypt for $user:$domain");
                   7934:                     }
                   7935:                     return 1;
                   7936:                 } elsif ($domdefaults{'intauth_check'} == 2) {
                   7937:                     return 0;
                   7938:                 }
                   7939:             }
                   7940:         } else {
                   7941:             return 1;
1.518     raeburn  7942:         }
                   7943:     }
                   7944:     return 0;
                   7945: }
                   7946: 
                   7947: sub get_last_authchg {
                   7948:     my ($domain,$user) = @_;
                   7949:     my $lastmod;
                   7950:     my $logname = &propath($domain,$user).'/passwd.log';
                   7951:     if (-e "$logname") {
                   7952:         $lastmod = (stat("$logname"))[9];
                   7953:     }
                   7954:     return $lastmod;
                   7955: }
                   7956: 
1.439     raeburn  7957: sub krb4_authen {
                   7958:     my ($password,$null,$user,$contentpwd) = @_;
                   7959:     my $validated = 0;
                   7960:     if (!($password =~ /$null/) ) {  # Null password not allowed.
                   7961:         eval {
                   7962:             require Authen::Krb4;
                   7963:         };
                   7964:         if (!$@) {
                   7965:             my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
                   7966:                                                        "",
                   7967:                                                        $contentpwd,,
                   7968:                                                        'krbtgt',
                   7969:                                                        $contentpwd,
                   7970:                                                        1,
                   7971:                                                        $password);
                   7972:             if(!$k4error) {
                   7973:                 $validated = 1;
                   7974:             } else {
                   7975:                 $validated = 0;
                   7976:                 &logthis('krb4: '.$user.', '.$contentpwd.', '.
                   7977:                           &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   7978:             }
                   7979:         } else {
                   7980:             $validated = krb5_authen($password,$null,$user,$contentpwd);
                   7981:         }
                   7982:     }
                   7983:     return $validated;
                   7984: }
                   7985: 
                   7986: sub krb5_authen {
                   7987:     my ($password,$null,$user,$contentpwd) = @_;
                   7988:     my $validated = 0;
                   7989:     if(!($password =~ /$null/)) { # Null password not allowed.
                   7990:         my $krbclient = &Authen::Krb5::parse_name($user.'@'
                   7991:                                                   .$contentpwd);
                   7992:         my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
                   7993:         my $krbserver  = &Authen::Krb5::parse_name($krbservice);
                   7994:         my $credentials= &Authen::Krb5::cc_default();
                   7995:         $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
                   7996:                                                             .$contentpwd));
                   7997:         my $krbreturn;
                   7998:         if (exists(&Authen::Krb5::get_init_creds_password)) {
                   7999:             $krbreturn =
                   8000:                 &Authen::Krb5::get_init_creds_password($krbclient,$password,
                   8001:                                                           $krbservice);
                   8002:             $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
                   8003:         } else {
                   8004:             $krbreturn  =
                   8005:                 &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
                   8006:                                                          $password,$credentials);
                   8007:             $validated = ($krbreturn == 1);
                   8008:         }
                   8009:         if (!$validated) {
                   8010:             &logthis('krb5: '.$user.', '.$contentpwd.', '.
                   8011:                      &Authen::Krb5::error());
                   8012:         }
                   8013:     }
                   8014:     return $validated;
                   8015: }
1.220     foxr     8016: 
1.84      albertel 8017: sub addline {
                   8018:     my ($fname,$hostid,$ip,$newline)=@_;
                   8019:     my $contents;
                   8020:     my $found=0;
1.355     albertel 8021:     my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
1.134     albertel 8022:     my $sh;
1.84      albertel 8023:     if ($sh=IO::File->new("$fname.subscription")) {
                   8024: 	while (my $subline=<$sh>) {
                   8025: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   8026: 	}
                   8027: 	$sh->close();
                   8028:     }
                   8029:     $sh=IO::File->new(">$fname.subscription");
                   8030:     if ($contents) { print $sh $contents; }
                   8031:     if ($newline) { print $sh $newline; }
                   8032:     $sh->close();
                   8033:     return $found;
1.86      www      8034: }
                   8035: 
1.234     foxr     8036: sub get_chat {
1.324     raeburn  8037:     my ($cdom,$cname,$udom,$uname,$group)=@_;
1.310     albertel 8038: 
1.87      www      8039:     my @entries=();
1.324     raeburn  8040:     my $namespace = 'nohist_chatroom';
                   8041:     my $namespace_inroom = 'nohist_inchatroom';
1.335     albertel 8042:     if ($group ne '') {
1.324     raeburn  8043:         $namespace .= '_'.$group;
                   8044:         $namespace_inroom .= '_'.$group;
                   8045:     }
                   8046:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8047: 				 &GDBM_READER());
                   8048:     if ($hashref) {
                   8049: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.311     albertel 8050: 	&untie_user_hash($hashref);
1.123     www      8051:     }
1.124     www      8052:     my @participants=();
1.134     albertel 8053:     my $cutoff=time-60;
1.324     raeburn  8054:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
1.310     albertel 8055: 			      &GDBM_WRCREAT());
                   8056:     if ($hashref) {
                   8057:         $hashref->{$uname.':'.$udom}=time;
                   8058:         foreach my $user (sort(keys(%$hashref))) {
                   8059: 	    if ($hashref->{$user}>$cutoff) {
                   8060: 		push(@participants, 'active_participant:'.$user);
1.123     www      8061:             }
                   8062:         }
1.311     albertel 8063:         &untie_user_hash($hashref);
1.86      www      8064:     }
1.124     www      8065:     return (@participants,@entries);
1.86      www      8066: }
                   8067: 
1.234     foxr     8068: sub chat_add {
1.324     raeburn  8069:     my ($cdom,$cname,$newchat,$group)=@_;
1.88      albertel 8070:     my @entries=();
1.142     www      8071:     my $time=time;
1.324     raeburn  8072:     my $namespace = 'nohist_chatroom';
                   8073:     my $logfile = 'chatroom.log';
1.335     albertel 8074:     if ($group ne '') {
1.324     raeburn  8075:         $namespace .= '_'.$group;
                   8076:         $logfile = 'chatroom_'.$group.'.log';
                   8077:     }
                   8078:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8079: 				 &GDBM_WRCREAT());
                   8080:     if ($hashref) {
                   8081: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.88      albertel 8082: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   8083: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   8084: 	my $newid=$time.'_000000';
                   8085: 	if ($thentime==$time) {
                   8086: 	    $idnum=~s/^0+//;
                   8087: 	    $idnum++;
                   8088: 	    $idnum=substr('000000'.$idnum,-6,6);
                   8089: 	    $newid=$time.'_'.$idnum;
                   8090: 	}
1.310     albertel 8091: 	$hashref->{$newid}=$newchat;
1.88      albertel 8092: 	my $expired=$time-3600;
1.310     albertel 8093: 	foreach my $comment (keys(%$hashref)) {
                   8094: 	    my ($thistime) = ($comment=~/(\d+)\_/);
1.88      albertel 8095: 	    if ($thistime<$expired) {
1.310     albertel 8096: 		delete $hashref->{$comment};
1.88      albertel 8097: 	    }
                   8098: 	}
1.310     albertel 8099: 	{
                   8100: 	    my $proname=&propath($cdom,$cname);
1.324     raeburn  8101: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
1.310     albertel 8102: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
                   8103: 	    }
                   8104: 	    close(CHATLOG);
1.142     www      8105: 	}
1.311     albertel 8106: 	&untie_user_hash($hashref);
1.86      www      8107:     }
1.84      albertel 8108: }
                   8109: 
                   8110: sub unsub {
                   8111:     my ($fname,$clientip)=@_;
                   8112:     my $result;
1.188     foxr     8113:     my $unsubs = 0;		# Number of successful unsubscribes:
                   8114: 
                   8115: 
                   8116:     # An old way subscriptions were handled was to have a 
                   8117:     # subscription marker file:
                   8118: 
                   8119:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     8120:     if (unlink("$fname.$clientname")) {
1.188     foxr     8121: 	$unsubs++;		# Successful unsub via marker file.
                   8122:     } 
                   8123: 
                   8124:     # The more modern way to do it is to have a subscription list
                   8125:     # file:
                   8126: 
1.84      albertel 8127:     if (-e "$fname.subscription") {
1.161     foxr     8128: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     8129: 	if ($found) { 
                   8130: 	    $unsubs++;
                   8131: 	}
                   8132:     } 
                   8133: 
                   8134:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   8135:     #  resource we can return ok:
                   8136: 
                   8137:     if($unsubs) {
                   8138: 	$result = "ok\n";
1.84      albertel 8139:     } else {
1.188     foxr     8140: 	$result = "not_subscribed\n";
1.84      albertel 8141:     }
1.188     foxr     8142: 
1.84      albertel 8143:     return $result;
                   8144: }
                   8145: 
1.101     www      8146: sub currentversion {
                   8147:     my $fname=shift;
                   8148:     my $version=-1;
                   8149:     my $ulsdir='';
                   8150:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   8151:        $ulsdir=$1;
                   8152:     }
1.114     albertel 8153:     my ($fnamere1,$fnamere2);
                   8154:     # remove version if already specified
1.101     www      8155:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 8156:     # get the bits that go before and after the version number
                   8157:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   8158: 	$fnamere1=$1;
                   8159: 	$fnamere2='.'.$2;
                   8160:     }
1.101     www      8161:     if (-e $fname) { $version=1; }
                   8162:     if (-e $ulsdir) {
1.134     albertel 8163: 	if(-d $ulsdir) {
                   8164: 	    if (opendir(LSDIR,$ulsdir)) {
                   8165: 		my $ulsfn;
                   8166: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      8167: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 8168: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   8169: 		    unless (-l $thisfile) {
1.160     www      8170: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 8171: 			    if ($1>$version) { $version=$1; }
                   8172: 			}
                   8173: 		    }
                   8174: 		}
                   8175: 		closedir(LSDIR);
                   8176: 		$version++;
                   8177: 	    }
                   8178: 	}
                   8179:     }
                   8180:     return $version;
1.101     www      8181: }
                   8182: 
                   8183: sub thisversion {
                   8184:     my $fname=shift;
                   8185:     my $version=-1;
                   8186:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   8187: 	$version=$1;
                   8188:     }
                   8189:     return $version;
                   8190: }
                   8191: 
1.84      albertel 8192: sub subscribe {
                   8193:     my ($userinput,$clientip)=@_;
                   8194:     my $result;
1.293     albertel 8195:     my ($cmd,$fname)=split(/:/,$userinput,2);
1.84      albertel 8196:     my $ownership=&ishome($fname);
                   8197:     if ($ownership eq 'owner') {
1.101     www      8198: # explitly asking for the current version?
                   8199:         unless (-e $fname) {
                   8200:             my $currentversion=&currentversion($fname);
                   8201: 	    if (&thisversion($fname)==$currentversion) {
                   8202:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   8203: 		    my $root=$1;
                   8204:                     my $extension=$2;
                   8205:                     symlink($root.'.'.$extension,
                   8206:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      8207:                     unless ($extension=~/\.meta$/) {
                   8208:                        symlink($root.'.'.$extension.'.meta',
                   8209:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   8210: 		    }
1.101     www      8211:                 }
                   8212:             }
                   8213:         }
1.84      albertel 8214: 	if (-e $fname) {
                   8215: 	    if (-d $fname) {
                   8216: 		$result="directory\n";
                   8217: 	    } else {
1.161     foxr     8218: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 8219: 		my $now=time;
1.161     foxr     8220: 		my $found=&addline($fname,$clientname,$clientip,
                   8221: 				   "$clientname:$clientip:$now\n");
1.84      albertel 8222: 		if ($found) { $result="$fname\n"; }
                   8223: 		# if they were subscribed to only meta data, delete that
                   8224:                 # subscription, when you subscribe to a file you also get
                   8225:                 # the metadata
                   8226: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   8227: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
1.476     raeburn  8228:                 my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
                   8229:                 $protocol = 'http' if ($protocol ne 'https');
                   8230: 		$fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
1.84      albertel 8231: 		$result="$fname\n";
                   8232: 	    }
                   8233: 	} else {
                   8234: 	    $result="not_found\n";
                   8235: 	}
                   8236:     } else {
                   8237: 	$result="rejected\n";
                   8238:     }
                   8239:     return $result;
                   8240: }
1.287     foxr     8241: #  Change the passwd of a unix user.  The caller must have
                   8242: #  first verified that the user is a loncapa user.
                   8243: #
                   8244: # Parameters:
                   8245: #    user      - Unix user name to change.
                   8246: #    pass      - New password for the user.
                   8247: # Returns:
                   8248: #    ok    - if success
                   8249: #    other - Some meaningfule error message string.
                   8250: # NOTE:
                   8251: #    invokes a setuid script to change the passwd.
                   8252: sub change_unix_password {
                   8253:     my ($user, $pass) = @_;
                   8254: 
                   8255:     &Debug("change_unix_password");
                   8256:     my $execdir=$perlvar{'lonDaemons'};
                   8257:     &Debug("Opening lcpasswd pipeline");
                   8258:     my $pf = IO::File->new("|$execdir/lcpasswd > "
                   8259: 			   ."$perlvar{'lonDaemons'}"
                   8260: 			   ."/logs/lcpasswd.log");
                   8261:     print $pf "$user\n$pass\n$pass\n";
                   8262:     close $pf;
                   8263:     my $err = $?;
                   8264:     return ($err < @passwderrors) ? $passwderrors[$err] : 
                   8265: 	"pwchange_falure - unknown error";
                   8266: 
                   8267:     
                   8268: }
                   8269: 
1.91      albertel 8270: 
                   8271: sub make_passwd_file {
1.518     raeburn  8272:     my ($uname,$udom,$umode,$npass,$passfilename,$action)=@_;
1.390     raeburn  8273:     my $result="ok";
1.91      albertel 8274:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   8275: 	{
                   8276: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8277: 	    if ($pf) {
                   8278: 		print $pf "$umode:$npass\n";
1.518     raeburn  8279:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     8280: 	    } else {
                   8281: 		$result = "pass_file_failed_error";
                   8282: 	    }
1.91      albertel 8283: 	}
                   8284:     } elsif ($umode eq 'internal') {
1.518     raeburn  8285:         my $ncpass = &hash_passwd($udom,$npass);
1.91      albertel 8286: 	{
                   8287: 	    &Debug("Creating internal auth");
                   8288: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8289: 	    if($pf) {
1.518     raeburn  8290: 		print $pf "internal:$ncpass\n";
                   8291:                 &update_passwd_history($uname,$udom,$umode,$action); 
1.261     foxr     8292: 	    } else {
                   8293: 		$result = "pass_file_failed_error";
                   8294: 	    }
1.91      albertel 8295: 	}
                   8296:     } elsif ($umode eq 'localauth') {
                   8297: 	{
                   8298: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8299: 	    if($pf) {
                   8300: 		print $pf "localauth:$npass\n";
1.524     raeburn  8301:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     8302: 	    } else {
                   8303: 		$result = "pass_file_failed_error";
                   8304: 	    }
1.91      albertel 8305: 	}
                   8306:     } elsif ($umode eq 'unix') {
1.502     raeburn  8307: 	&logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
                   8308: 	$result="no_new_unix_accounts";
1.91      albertel 8309:     } elsif ($umode eq 'none') {
                   8310: 	{
1.223     foxr     8311: 	    my $pf = IO::File->new("> $passfilename");
1.261     foxr     8312: 	    if($pf) {
                   8313: 		print $pf "none:\n";
                   8314: 	    } else {
                   8315: 		$result = "pass_file_failed_error";
                   8316: 	    }
1.91      albertel 8317: 	}
                   8318:     } else {
1.390     raeburn  8319: 	$result="auth_mode_error";
1.91      albertel 8320:     }
                   8321:     return $result;
1.121     albertel 8322: }
                   8323: 
1.265     albertel 8324: sub convert_photo {
                   8325:     my ($start,$dest)=@_;
                   8326:     system("convert $start $dest");
                   8327: }
                   8328: 
1.121     albertel 8329: sub sethost {
                   8330:     my ($remotereq) = @_;
                   8331:     my (undef,$hostid)=split(/:/,$remotereq);
1.322     albertel 8332:     # ignore sethost if we are already correct
                   8333:     if ($hostid eq $currenthostid) {
                   8334: 	return 'ok';
                   8335:     }
                   8336: 
1.121     albertel 8337:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
1.368     albertel 8338:     if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'}) 
                   8339: 	eq &Apache::lonnet::get_host_ip($hostid)) {
1.200     matthew  8340: 	$currenthostid  =$hostid;
1.369     albertel 8341: 	$currentdomainid=&Apache::lonnet::host_domain($hostid);
1.443     www      8342: #	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
1.121     albertel 8343:     } else {
                   8344: 	&logthis("Requested host id $hostid not an alias of ".
                   8345: 		 $perlvar{'lonHostID'}." refusing connection");
                   8346: 	return 'unable_to_set';
                   8347:     }
                   8348:     return 'ok';
                   8349: }
                   8350: 
                   8351: sub version {
                   8352:     my ($userinput)=@_;
                   8353:     $remoteVERSION=(split(/:/,$userinput))[1];
                   8354:     return "version:$VERSION";
1.127     albertel 8355: }
1.178     foxr     8356: 
1.447     raeburn  8357: sub get_usersession_config {
                   8358:     my ($dom,$name) = @_;
                   8359:     my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8360:     if (defined($cached)) {
                   8361:         return $usersessionconf;
                   8362:     } else {
                   8363:         my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
1.525     raeburn  8364:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
                   8365:         return $domconfig{'usersessions'};
1.447     raeburn  8366:     }
                   8367:     return;
                   8368: }
1.200     matthew  8369: 
1.534     raeburn  8370: sub get_usersearch_config {
                   8371:     my ($dom,$name) = @_;
                   8372:     my ($usersearchconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8373:     if (defined($cached)) {
                   8374:         return $usersearchconf;
                   8375:     } else {
                   8376:         my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$dom);
                   8377:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'directorysrch'},600);
                   8378:         return $domconfig{'directorysrch'};
                   8379:     }
                   8380:     return;
                   8381: }
                   8382: 
1.525     raeburn  8383: sub get_prohibited {
                   8384:     my ($dom) = @_;
                   8385:     my $name = 'trust';
                   8386:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8387:     unless (defined($cached)) {
                   8388:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$dom);
                   8389:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'trust'},3600);
                   8390:         $trustconfig = $domconfig{'trust'};
                   8391:     }
                   8392:     my %prohibited;
                   8393:     if (ref($trustconfig)) {
                   8394:         foreach my $prefix (keys(%{$trustconfig})) {
                   8395:             if (ref($trustconfig->{$prefix}) eq 'HASH') {
                   8396:                 my $reject;
                   8397:                 if (ref($trustconfig->{$prefix}->{'exc'}) eq 'ARRAY') {
                   8398:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'exc'}})) {
                   8399:                         $reject = 1;
                   8400:                     }
                   8401:                 }
                   8402:                 if (ref($trustconfig->{$prefix}->{'inc'}) eq 'ARRAY') {
                   8403:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'inc'}})) {
                   8404:                         $reject = 0;
                   8405:                     } else {
                   8406:                         $reject = 1;
                   8407:                     }
                   8408:                 }
                   8409:                 if ($reject) {
                   8410:                     $prohibited{$prefix} = 1;
                   8411:                 }
                   8412:             }
                   8413:         }
                   8414:     }
                   8415:     return %prohibited;
                   8416: }
1.450     raeburn  8417: 
1.471     raeburn  8418: sub distro_and_arch {
                   8419:     return $dist.':'.$arch;
                   8420: }
                   8421: 
1.61      harris41 8422: # ----------------------------------- POD (plain old documentation, CPAN style)
                   8423: 
                   8424: =head1 NAME
                   8425: 
                   8426: lond - "LON Daemon" Server (port "LOND" 5663)
                   8427: 
                   8428: =head1 SYNOPSIS
                   8429: 
1.74      harris41 8430: Usage: B<lond>
                   8431: 
                   8432: Should only be run as user=www.  This is a command-line script which
                   8433: is invoked by B<loncron>.  There is no expectation that a typical user
                   8434: will manually start B<lond> from the command-line.  (In other words,
                   8435: DO NOT START B<lond> YOURSELF.)
1.61      harris41 8436: 
                   8437: =head1 DESCRIPTION
                   8438: 
1.74      harris41 8439: There are two characteristics associated with the running of B<lond>,
                   8440: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   8441: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   8442: subscriptions, etc).  These are described in two large
                   8443: sections below.
                   8444: 
                   8445: B<PROCESS MANAGEMENT>
                   8446: 
1.61      harris41 8447: Preforker - server who forks first. Runs as a daemon. HUPs.
                   8448: Uses IDEA encryption
                   8449: 
1.74      harris41 8450: B<lond> forks off children processes that correspond to the other servers
                   8451: in the network.  Management of these processes can be done at the
                   8452: parent process level or the child process level.
                   8453: 
                   8454: B<logs/lond.log> is the location of log messages.
                   8455: 
                   8456: The process management is now explained in terms of linux shell commands,
                   8457: subroutines internal to this code, and signal assignments:
                   8458: 
                   8459: =over 4
                   8460: 
                   8461: =item *
                   8462: 
                   8463: PID is stored in B<logs/lond.pid>
                   8464: 
                   8465: This is the process id number of the parent B<lond> process.
                   8466: 
                   8467: =item *
                   8468: 
                   8469: SIGTERM and SIGINT
                   8470: 
                   8471: Parent signal assignment:
                   8472:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   8473: 
                   8474: Child signal assignment:
                   8475:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   8476: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   8477:  to restart a new child.)
                   8478: 
                   8479: Command-line invocations:
                   8480:  B<kill> B<-s> SIGTERM I<PID>
                   8481:  B<kill> B<-s> SIGINT I<PID>
                   8482: 
                   8483: Subroutine B<HUNTSMAN>:
                   8484:  This is only invoked for the B<lond> parent I<PID>.
                   8485: This kills all the children, and then the parent.
                   8486: The B<lonc.pid> file is cleared.
                   8487: 
                   8488: =item *
                   8489: 
                   8490: SIGHUP
                   8491: 
                   8492: Current bug:
                   8493:  This signal can only be processed the first time
                   8494: on the parent process.  Subsequent SIGHUP signals
                   8495: have no effect.
                   8496: 
                   8497: Parent signal assignment:
                   8498:  $SIG{HUP}  = \&HUPSMAN;
                   8499: 
                   8500: Child signal assignment:
                   8501:  none (nothing happens)
                   8502: 
                   8503: Command-line invocations:
                   8504:  B<kill> B<-s> SIGHUP I<PID>
                   8505: 
                   8506: Subroutine B<HUPSMAN>:
                   8507:  This is only invoked for the B<lond> parent I<PID>,
                   8508: This kills all the children, and then the parent.
                   8509: The B<lond.pid> file is cleared.
                   8510: 
                   8511: =item *
                   8512: 
                   8513: SIGUSR1
                   8514: 
                   8515: Parent signal assignment:
                   8516:  $SIG{USR1} = \&USRMAN;
                   8517: 
                   8518: Child signal assignment:
                   8519:  $SIG{USR1}= \&logstatus;
                   8520: 
                   8521: Command-line invocations:
                   8522:  B<kill> B<-s> SIGUSR1 I<PID>
                   8523: 
                   8524: Subroutine B<USRMAN>:
                   8525:  When invoked for the B<lond> parent I<PID>,
                   8526: SIGUSR1 is sent to all the children, and the status of
                   8527: each connection is logged.
1.144     foxr     8528: 
                   8529: =item *
                   8530: 
                   8531: SIGUSR2
                   8532: 
                   8533: Parent Signal assignment:
                   8534:     $SIG{USR2} = \&UpdateHosts
                   8535: 
                   8536: Child signal assignment:
                   8537:     NONE
                   8538: 
1.74      harris41 8539: 
                   8540: =item *
                   8541: 
                   8542: SIGCHLD
                   8543: 
                   8544: Parent signal assignment:
                   8545:  $SIG{CHLD} = \&REAPER;
                   8546: 
                   8547: Child signal assignment:
                   8548:  none
                   8549: 
                   8550: Command-line invocations:
                   8551:  B<kill> B<-s> SIGCHLD I<PID>
                   8552: 
                   8553: Subroutine B<REAPER>:
                   8554:  This is only invoked for the B<lond> parent I<PID>.
                   8555: Information pertaining to the child is removed.
                   8556: The socket port is cleaned up.
                   8557: 
                   8558: =back
                   8559: 
                   8560: B<SERVER-SIDE ACTIVITIES>
                   8561: 
                   8562: Server-side information can be accepted in an encrypted or non-encrypted
                   8563: method.
                   8564: 
                   8565: =over 4
                   8566: 
                   8567: =item ping
                   8568: 
                   8569: Query a client in the hosts.tab table; "Are you there?"
                   8570: 
                   8571: =item pong
                   8572: 
                   8573: Respond to a ping query.
                   8574: 
                   8575: =item ekey
                   8576: 
                   8577: Read in encrypted key, make cipher.  Respond with a buildkey.
                   8578: 
                   8579: =item load
                   8580: 
                   8581: Respond with CPU load based on a computation upon /proc/loadavg.
                   8582: 
                   8583: =item currentauth
                   8584: 
                   8585: Reply with current authentication information (only over an
                   8586: encrypted channel).
                   8587: 
                   8588: =item auth
                   8589: 
                   8590: Only over an encrypted channel, reply as to whether a user's
                   8591: authentication information can be validated.
                   8592: 
                   8593: =item passwd
                   8594: 
                   8595: Allow for a password to be set.
                   8596: 
                   8597: =item makeuser
                   8598: 
                   8599: Make a user.
                   8600: 
1.517     raeburn  8601: =item changeuserauth
1.74      harris41 8602: 
                   8603: Allow for authentication mechanism and password to be changed.
                   8604: 
                   8605: =item home
1.61      harris41 8606: 
1.74      harris41 8607: Respond to a question "are you the home for a given user?"
                   8608: 
                   8609: =item update
                   8610: 
                   8611: Update contents of a subscribed resource.
                   8612: 
                   8613: =item unsubscribe
                   8614: 
                   8615: The server is unsubscribing from a resource.
                   8616: 
                   8617: =item subscribe
                   8618: 
                   8619: The server is subscribing to a resource.
                   8620: 
                   8621: =item log
                   8622: 
                   8623: Place in B<logs/lond.log>
                   8624: 
                   8625: =item put
                   8626: 
                   8627: stores hash in namespace
                   8628: 
1.496     raeburn  8629: =item rolesput
1.74      harris41 8630: 
                   8631: put a role into a user's environment
                   8632: 
                   8633: =item get
                   8634: 
                   8635: returns hash with keys from array
                   8636: reference filled in from namespace
                   8637: 
                   8638: =item eget
                   8639: 
                   8640: returns hash with keys from array
                   8641: reference filled in from namesp (encrypts the return communication)
                   8642: 
                   8643: =item rolesget
                   8644: 
                   8645: get a role from a user's environment
                   8646: 
                   8647: =item del
                   8648: 
                   8649: deletes keys out of array from namespace
                   8650: 
                   8651: =item keys
                   8652: 
                   8653: returns namespace keys
                   8654: 
                   8655: =item dump
                   8656: 
                   8657: dumps the complete (or key matching regexp) namespace into a hash
                   8658: 
                   8659: =item store
                   8660: 
                   8661: stores hash permanently
                   8662: for this url; hashref needs to be given and should be a \%hashname; the
                   8663: remaining args aren't required and if they aren't passed or are '' they will
                   8664: be derived from the ENV
                   8665: 
                   8666: =item restore
                   8667: 
                   8668: returns a hash for a given url
                   8669: 
                   8670: =item querysend
                   8671: 
                   8672: Tells client about the lonsql process that has been launched in response
                   8673: to a sent query.
                   8674: 
                   8675: =item queryreply
                   8676: 
                   8677: Accept information from lonsql and make appropriate storage in temporary
                   8678: file space.
                   8679: 
                   8680: =item idput
                   8681: 
                   8682: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   8683: for each student, defined perhaps by the institutional Registrar.)
                   8684: 
                   8685: =item idget
                   8686: 
                   8687: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   8688: for each student, defined perhaps by the institutional Registrar.)
                   8689: 
1.517     raeburn  8690: =item iddel
                   8691: 
                   8692: Deletes one or more ids in a domain's id database.
                   8693: 
1.74      harris41 8694: =item tmpput
                   8695: 
                   8696: Accept and store information in temporary space.
                   8697: 
                   8698: =item tmpget
                   8699: 
                   8700: Send along temporarily stored information.
                   8701: 
                   8702: =item ls
                   8703: 
                   8704: List part of a user's directory.
                   8705: 
1.135     foxr     8706: =item pushtable
                   8707: 
                   8708: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   8709: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   8710: must be restored manually in case of a problem with the new table file.
                   8711: pushtable requires that the request be encrypted and validated via
                   8712: ValidateManager.  The form of the command is:
                   8713: enc:pushtable tablename <tablecontents> \n
                   8714: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   8715: cleartext newline.
                   8716: 
1.74      harris41 8717: =item Hanging up (exit or init)
                   8718: 
                   8719: What to do when a client tells the server that they (the client)
                   8720: are leaving the network.
                   8721: 
                   8722: =item unknown command
                   8723: 
                   8724: If B<lond> is sent an unknown command (not in the list above),
                   8725: it replys to the client "unknown_cmd".
1.135     foxr     8726: 
1.74      harris41 8727: 
                   8728: =item UNKNOWN CLIENT
                   8729: 
                   8730: If the anti-spoofing algorithm cannot verify the client,
                   8731: the client is rejected (with a "refused" message sent
                   8732: to the client, and the connection is closed.
                   8733: 
                   8734: =back
1.61      harris41 8735: 
                   8736: =head1 PREREQUISITES
                   8737: 
                   8738: IO::Socket
                   8739: IO::File
                   8740: Apache::File
                   8741: POSIX
                   8742: Crypt::IDEA
                   8743: GDBM_File
                   8744: Authen::Krb4
1.91      albertel 8745: Authen::Krb5
1.61      harris41 8746: 
                   8747: =head1 COREQUISITES
                   8748: 
1.490     droeschl 8749: none
                   8750: 
1.61      harris41 8751: =head1 OSNAMES
                   8752: 
                   8753: linux
                   8754: 
                   8755: =head1 SCRIPT CATEGORIES
                   8756: 
                   8757: Server/Process
                   8758: 
                   8759: =cut
1.409     foxr     8760: 
                   8761: 
                   8762: =pod
                   8763: 
                   8764: =head1 LOG MESSAGES
                   8765: 
                   8766: The messages below can be emitted in the lond log.  This log is located
                   8767: in ~httpd/perl/logs/lond.log  Many log messages have HTML encapsulation
                   8768: to provide coloring if examined from inside a web page. Some do not.
                   8769: Where color is used, the colors are; Red for sometihhng to get excited
                   8770: about and to follow up on. Yellow for something to keep an eye on to
                   8771: be sure it does not get worse, Green,and Blue for informational items.
                   8772: 
                   8773: In the discussions below, sometimes reference is made to ~httpd
                   8774: when describing file locations.  There isn't really an httpd 
                   8775: user, however there is an httpd directory that gets installed in the
                   8776: place that user home directories go.  On linux, this is usually
                   8777: (always?) /home/httpd.
                   8778: 
                   8779: 
                   8780: Some messages are colorless.  These are usually (not always)
                   8781: Green/Blue color level messages.
                   8782: 
                   8783: =over 2
                   8784: 
                   8785: =item (Red)  LocalConnection rejecting non local: <ip> ne 127.0.0.1
                   8786: 
                   8787: A local connection negotiation was attempted by
                   8788: a host whose IP address was not 127.0.0.1.
                   8789: The socket is closed and the child will exit.
                   8790: lond has three ways to establish an encyrption
                   8791: key with a client:
                   8792: 
                   8793: =over 2
                   8794: 
                   8795: =item local 
                   8796: 
                   8797: The key is written and read from a file.
                   8798: This is only valid for connections from localhost.
                   8799: 
                   8800: =item insecure 
                   8801: 
                   8802: The key is generated by the server and
                   8803: transmitted to the client.
                   8804: 
                   8805: =item  ssl (secure)
                   8806: 
                   8807: An ssl connection is negotiated with the client,
                   8808: the key is generated by the server and sent to the 
                   8809: client across this ssl connection before the
                   8810: ssl connectionis terminated and clear text
                   8811: transmission resumes.
                   8812: 
                   8813: =back
                   8814: 
                   8815: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
                   8816: 
                   8817: The client is local but has not sent an initialization
                   8818: string that is the literal "init:local"  The connection
                   8819: is closed and the child exits.
                   8820: 
                   8821: =item Red CRITICAL Can't get key file <error>        
                   8822: 
                   8823: SSL key negotiation is being attempted but the call to
                   8824: lonssl::KeyFile  failed.  This usually means that the
                   8825: configuration file is not correctly defining or protecting
                   8826: the directories/files lonCertificateDirectory or
                   8827: lonnetPrivateKey
                   8828: <error> is a string that describes the reason that
                   8829: the key file could not be located.
                   8830: 
                   8831: =item (Red) CRITICAL  Can't get certificates <error>  
                   8832: 
                   8833: SSL key negotiation failed because we were not able to retrives our certificate
                   8834: or the CA's certificate in the call to lonssl::CertificateFile
                   8835: <error> is the textual reason this failed.  Usual reasons:
                   8836: 
                   8837: =over 2
1.490     droeschl 8838: 
1.409     foxr     8839: =item Apache config file for loncapa  incorrect:
1.490     droeschl 8840: 
1.409     foxr     8841: one of the variables 
                   8842: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
                   8843: undefined or incorrect
                   8844: 
                   8845: =item Permission error:
                   8846: 
                   8847: The directory pointed to by lonCertificateDirectory is not readable by lond
                   8848: 
                   8849: =item Permission error:
                   8850: 
                   8851: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
                   8852: 
                   8853: =item Installation error:                         
                   8854: 
                   8855: Either the certificate authority file or the certificate have not
                   8856: been installed in lonCertificateDirectory.
                   8857: 
                   8858: =item (Red) CRITICAL SSL Socket promotion failed:  <err> 
                   8859: 
                   8860: The promotion of the connection from plaintext to SSL failed
                   8861: <err> is the reason for the failure.  There are two
                   8862: system calls involved in the promotion (one of which failed), 
                   8863: a dup to produce
                   8864: a second fd on the raw socket over which the encrypted data
                   8865: will flow and IO::SOcket::SSL->new_from_fd which creates
                   8866: the SSL connection on the duped fd.
                   8867: 
                   8868: =item (Blue)   WARNING client did not respond to challenge 
                   8869: 
                   8870: This occurs on an insecure (non SSL) connection negotiation request.
                   8871: lond generates some number from the time, the PID and sends it to
                   8872: the client.  The client must respond by echoing this information back.
                   8873: If the client does not do so, that's a violation of the challenge
                   8874: protocols and the connection will be failed.
                   8875: 
                   8876: =item (Red) No manager table. Nobody can manage!!    
                   8877: 
                   8878: lond has the concept of privileged hosts that
                   8879: can perform remote management function such
                   8880: as update the hosts.tab.   The manager hosts
                   8881: are described in the 
                   8882: ~httpd/lonTabs/managers.tab file.
                   8883: this message is logged if this file is missing.
                   8884: 
                   8885: 
                   8886: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
                   8887: 
                   8888: Reports the successful parse and registration
                   8889: of a specific manager. 
                   8890: 
                   8891: =item Green existing host <clustername:dnsname>  
                   8892: 
                   8893: The manager host is already defined in the hosts.tab
                   8894: the information in that table, rather than the info in the
                   8895: manager table will be used to determine the manager's ip.
                   8896: 
                   8897: =item (Red) Unable to craete <filename>                 
                   8898: 
                   8899: lond has been asked to create new versions of an administrative
                   8900: file (by a manager).  When this is done, the new file is created
                   8901: in a temp file and then renamed into place so that there are always
                   8902: usable administrative files, even if the update fails.  This failure
                   8903: message means that the temp file could not be created.
                   8904: The update is abandoned, and the old file is available for use.
                   8905: 
                   8906: =item (Green) CopyFile from <oldname> to <newname> failed
                   8907: 
                   8908: In an update of administrative files, the copy of the existing file to a
                   8909: backup file failed.  The installation of the new file may still succeed,
                   8910: but there will not be a back up file to rever to (this should probably
                   8911: be yellow).
                   8912: 
                   8913: =item (Green) Pushfile: backed up <oldname> to <newname>
                   8914: 
                   8915: See above, the backup of the old administrative file succeeded.
                   8916: 
                   8917: =item (Red)  Pushfile: Unable to install <filename> <reason>
                   8918: 
                   8919: The new administrative file could not be installed.  In this case,
                   8920: the old administrative file is still in use.
                   8921: 
                   8922: =item (Green) Installed new < filename>.                      
                   8923: 
                   8924: The new administrative file was successfullly installed.                                               
                   8925: 
                   8926: =item (Red) Reinitializing lond pid=<pid>                    
                   8927: 
                   8928: The lonc child process <pid> will be sent a USR2 
                   8929: signal.
                   8930: 
                   8931: =item (Red) Reinitializing self                                    
                   8932: 
                   8933: We've been asked to re-read our administrative files,and
                   8934: are doing so.
                   8935: 
                   8936: =item (Yellow) error:Invalid process identifier <ident>  
                   8937: 
                   8938: A reinit command was received, but the target part of the 
                   8939: command was not valid.  It must be either
                   8940: 'lond' or 'lonc' but was <ident>
                   8941: 
                   8942: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
                   8943: 
                   8944: Checking to see if lond has been handed a valid edit
                   8945: command.  It is possible the edit command is not valid
                   8946: in that case there are no log messages to indicate that.
                   8947: 
                   8948: =item Result of password change for  <username> pwchange_success
                   8949: 
                   8950: The password for <username> was
                   8951: successfully changed.
                   8952: 
                   8953: =item Unable to open <user> passwd to change password
                   8954: 
                   8955: Could not rewrite the 
                   8956: internal password file for a user
                   8957: 
                   8958: =item Result of password change for <user> : <result>
1.490     droeschl 8959: 
1.409     foxr     8960: A unix password change for <user> was attempted 
                   8961: and the pipe returned <result>  
                   8962: 
                   8963: =item LWP GET: <message> for <fname> (<remoteurl>)
                   8964: 
                   8965: The lightweight process fetch for a resource failed
                   8966: with <message> the local filename that should
                   8967: have existed/been created was  <fname> the
                   8968: corresponding URI: <remoteurl>  This is emitted in several
                   8969: places.
                   8970: 
                   8971: =item Unable to move <transname> to <destname>     
                   8972: 
                   8973: From fetch_user_file_handler - the user file was replicated but could not
                   8974: be mv'd to its final location.
                   8975: 
                   8976: =item Looking for <domain> <username>              
                   8977: 
                   8978: From user_has_session_handler - This should be a Debug call instead
                   8979: it indicates lond is about to check whether the specified user has a 
                   8980: session active on the specified domain on the local host.
                   8981: 
                   8982: =item Client <ip> (<name>) hanging up: <input>     
                   8983: 
                   8984: lond has been asked to exit by its client.  The <ip> and <name> identify the
                   8985: client systemand <input> is the full exit command sent to the server.
                   8986: 
                   8987: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
1.490     droeschl 8988: 
1.409     foxr     8989: A lond child terminated.  NOte that this termination can also occur when the
                   8990: child receives the QUIT or DIE signals.  <pid> is the process id of the child,
                   8991: <hostname> the host lond is working for, and <message> the reason the child died
                   8992: to the best of our ability to get it (I would guess that any numeric value
                   8993: represents and errno value).  This is immediately followed by
                   8994: 
                   8995: =item  Famous last words: Catching exception - <log> 
                   8996: 
                   8997: Where log is some recent information about the state of the child.
                   8998: 
                   8999: =item Red CRITICAL: TIME OUT <pid>                     
                   9000: 
                   9001: Some timeout occured for server <pid>.  THis is normally a timeout on an LWP
                   9002: doing an HTTP::GET.
                   9003: 
                   9004: =item child <pid> died                              
                   9005: 
                   9006: The reaper caught a SIGCHILD for the lond child process <pid>
                   9007: This should be modified to also display the IP of the dying child
                   9008: $children{$pid}
                   9009: 
                   9010: =item Unknown child 0 died                           
                   9011: A child died but the wait for it returned a pid of zero which really should not
                   9012: ever happen. 
                   9013: 
                   9014: =item Child <which> - <pid> looks like we missed it's death 
                   9015: 
                   9016: When a sigchild is received, the reaper process checks all children to see if they are
                   9017: alive.  If children are dying quite quickly, the lack of signal queuing can mean
                   9018: that a signal hearalds the death of more than one child.  If so this message indicates
                   9019: which other one died. <which> is the ip of a dead child
                   9020: 
                   9021: =item Free socket: <shutdownretval>                
                   9022: 
                   9023: The HUNTSMAN sub was called due to a SIGINT in a child process.  The socket is being shutdown.
                   9024: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
                   9025: to return anything. This is followed by: 
                   9026: 
                   9027: =item Red CRITICAL: Shutting down                       
                   9028: 
                   9029: Just prior to exit.
                   9030: 
                   9031: =item Free socket: <shutdownretval>                 
                   9032: 
                   9033: The HUPSMAN sub was called due to a SIGHUP.  all children get killsed, and lond execs itself.
                   9034: This is followed by:
                   9035: 
                   9036: =item (Red) CRITICAL: Restarting                         
                   9037: 
                   9038: lond is about to exec itself to restart.
                   9039: 
                   9040: =item (Blue) Updating connections                        
                   9041: 
                   9042: (In response to a USR2).  All the children (except the one for localhost)
                   9043: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
                   9044: 
                   9045: =item (Blue) UpdateHosts killing child <pid> for ip <ip>   
                   9046: 
                   9047: Due to USR2 as above.
                   9048: 
                   9049: =item (Green) keeping child for ip <ip> (pid = <pid>)    
                   9050: 
                   9051: In response to USR2 as above, the child indicated is not being restarted because
                   9052: it's assumed that we'll always need a child for the localhost.
                   9053: 
                   9054: 
                   9055: =item Going to check on the children                
                   9056: 
                   9057: Parent is about to check on the health of the child processes.
                   9058: Note that this is in response to a USR1 sent to the parent lond.
                   9059: there may be one or more of the next two messages:
                   9060: 
                   9061: =item <pid> is dead                                 
                   9062: 
                   9063: A child that we have in our child hash as alive has evidently died.
                   9064: 
                   9065: =item  Child <pid> did not respond                   
                   9066: 
                   9067: In the health check the child <pid> did not update/produce a pid_.txt
                   9068: file when sent it's USR1 signal.  That process is killed with a 9 signal, as it's
                   9069: assumed to be hung in some un-fixable way.
                   9070: 
                   9071: =item Finished checking children                   
1.490     droeschl 9072: 
1.409     foxr     9073: Master processs's USR1 processing is cojmplete.
                   9074: 
                   9075: =item (Red) CRITICAL: ------- Starting ------            
                   9076: 
                   9077: (There are more '-'s on either side).  Lond has forked itself off to 
                   9078: form a new session and is about to start actual initialization.
                   9079: 
                   9080: =item (Green) Attempting to start child (<client>)       
                   9081: 
                   9082: Started a new child process for <client>.  Client is IO::Socket object
                   9083: connected to the child.  This was as a result of a TCP/IP connection from a client.
                   9084: 
                   9085: =item Unable to determine who caller was, getpeername returned nothing
1.490     droeschl 9086: 
1.409     foxr     9087: In child process initialization.  either getpeername returned undef or
                   9088: a zero sized object was returned.  Processing continues, but in my opinion,
                   9089: this should be cause for the child to exit.
                   9090: 
                   9091: =item Unable to determine clientip                  
                   9092: 
                   9093: In child process initialization.  The peer address from getpeername was not defined.
                   9094: The client address is stored as "Unavailable" and processing continues.
                   9095: 
                   9096: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
1.490     droeschl 9097: 
1.409     foxr     9098: In child initialization.  A good connectionw as received from <ip>.
                   9099: 
                   9100: =over 2
                   9101: 
                   9102: =item <name> 
                   9103: 
                   9104: is the name of the client from hosts.tab.
                   9105: 
                   9106: =item <type> 
                   9107: 
                   9108: Is the connection type which is either 
                   9109: 
                   9110: =over 2
                   9111: 
                   9112: =item manager 
                   9113: 
                   9114: The connection is from a manager node, not in hosts.tab
                   9115: 
                   9116: =item client  
                   9117: 
                   9118: the connection is from a non-manager in the hosts.tab
                   9119: 
                   9120: =item both
                   9121: 
                   9122: The connection is from a manager in the hosts.tab.
                   9123: 
                   9124: =back
                   9125: 
                   9126: =back
                   9127: 
                   9128: =item (Blue) Certificates not installed -- trying insecure auth
                   9129: 
                   9130: One of the certificate file, key file or
                   9131: certificate authority file could not be found for a client attempting
                   9132: SSL connection intiation.  COnnection will be attemptied in in-secure mode.
                   9133: (this would be a system with an up to date lond that has not gotten a 
                   9134: certificate from us).
                   9135: 
                   9136: =item (Green)  Successful local authentication            
                   9137: 
                   9138: A local connection successfully negotiated the encryption key. 
                   9139: In this case the IDEA key is in a file (that is hopefully well protected).
                   9140: 
                   9141: =item (Green) Successful ssl authentication with <client>  
                   9142: 
                   9143: The client (<client> is the peer's name in hosts.tab), has successfully
                   9144: negotiated an SSL connection with this child process.
                   9145: 
                   9146: =item (Green) Successful insecure authentication with <client>
1.490     droeschl 9147: 
1.409     foxr     9148: 
                   9149: The client has successfully negotiated an  insecure connection withthe child process.
                   9150: 
                   9151: =item (Yellow) Attempted insecure connection disallowed    
                   9152: 
                   9153: The client attempted and failed to successfully negotiate a successful insecure
                   9154: connection.  This can happen either because the variable londAllowInsecure is false
                   9155: or undefined, or becuse the child did not successfully echo back the challenge
                   9156: string.
                   9157: 
                   9158: 
                   9159: =back
                   9160: 
1.441     raeburn  9161: =back
                   9162: 
1.409     foxr     9163: 
                   9164: =cut

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