Annotation of loncom/lond, revision 1.541

1.1       albertel    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60      www         4: #
1.541   ! raeburn     5: # $Id: lond,v 1.540 2017/06/06 20:03:24 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.541   ! raeburn    68: my $VERSION='$Revision: 1.540 $'; #' stupid emacs
1.121     albertel   69: my $remoteVERSION;
1.214     foxr       70: my $currenthostid="default";
1.115     albertel   71: my $currentdomainid;
1.134     albertel   72: 
                     73: my $client;
1.200     matthew    74: my $clientip;			# IP address of client.
                     75: my $clientname;			# LonCAPA name of client.
1.448     raeburn    76: my $clientversion;              # LonCAPA version running on client.
                     77: my $clienthomedom;              # LonCAPA domain of homeID for client. 
1.525     raeburn    78: my $clientintdom;               # LonCAPA "internet domain" for client.
1.532     raeburn    79: my $clientsamedom;              # LonCAPA domain same for this host 
                     80:                                 # and client.
1.525     raeburn    81: my $clientsameinst;             # LonCAPA "internet domain" same for 
                     82:                                 # this host and client.
                     83: my $clientremoteok;             # Client allowed to host domain's users.
                     84:                                 # (version constraints ignored), not set
                     85:                                 # if this host and client share "internet domain". 
                     86: my %clientprohibited;           # Actions prohibited on client;
                     87:  
1.134     albertel   88: my $server;
1.200     matthew    89: 
                     90: my $keymode;
1.198     foxr       91: 
1.207     foxr       92: my $cipher;			# Cipher key negotiated with client
                     93: my $tmpsnum = 0;		# Id of tmpputs.
                     94: 
1.178     foxr       95: # 
                     96: #   Connection type is:
                     97: #      client                   - All client actions are allowed
                     98: #      manager                  - only management functions allowed.
                     99: #      both                     - Both management and client actions are allowed
                    100: #
1.161     foxr      101: 
1.178     foxr      102: my $ConnectionType;
1.161     foxr      103: 
1.178     foxr      104: my %managers;			# Ip -> manager names
1.161     foxr      105: 
1.178     foxr      106: my %perlvar;			# Will have the apache conf defined perl vars.
1.134     albertel  107: 
1.532     raeburn   108: my %secureconf;                 # Will have requirements for security 
                    109:                                 # of lond connections
                    110: 
1.480     raeburn   111: my $dist;
                    112: 
1.178     foxr      113: #
1.207     foxr      114: #   The hash below is used for command dispatching, and is therefore keyed on the request keyword.
                    115: #    Each element of the hash contains a reference to an array that contains:
                    116: #          A reference to a sub that executes the request corresponding to the keyword.
                    117: #          A flag that is true if the request must be encoded to be acceptable.
                    118: #          A mask with bits as follows:
                    119: #                      CLIENT_OK    - Set when the function is allowed by ordinary clients
                    120: #                      MANAGER_OK   - Set when the function is allowed to manager clients.
                    121: #
                    122: my $CLIENT_OK  = 1;
                    123: my $MANAGER_OK = 2;
                    124: my %Dispatcher;
                    125: 
                    126: 
                    127: #
1.178     foxr      128: #  The array below are password error strings."
                    129: #
                    130: my $lastpwderror    = 13;		# Largest error number from lcpasswd.
                    131: my @passwderrors = ("ok",
1.287     foxr      132: 		   "pwchange_failure - lcpasswd must be run as user 'www'",
                    133: 		   "pwchange_failure - lcpasswd got incorrect number of arguments",
                    134: 		   "pwchange_failure - lcpasswd did not get the right nubmer of input text lines",
                    135: 		   "pwchange_failure - lcpasswd too many simultaneous pwd changes in progress",
                    136: 		   "pwchange_failure - lcpasswd User does not exist.",
                    137: 		   "pwchange_failure - lcpasswd Incorrect current passwd",
                    138: 		   "pwchange_failure - lcpasswd Unable to su to root.",
                    139: 		   "pwchange_failure - lcpasswd Cannot set new passwd.",
                    140: 		   "pwchange_failure - lcpasswd Username has invalid characters",
                    141: 		   "pwchange_failure - lcpasswd Invalid characters in password",
                    142: 		   "pwchange_failure - lcpasswd User already exists", 
                    143:                    "pwchange_failure - lcpasswd Something went wrong with user addition.",
                    144: 		   "pwchange_failure - lcpasswd Password mismatch",
                    145: 		   "pwchange_failure - lcpasswd Error filename is invalid");
1.97      foxr      146: 
                    147: 
1.412     foxr      148: # This array are the errors from lcinstallfile:
                    149: 
                    150: my @installerrors = ("ok",
                    151: 		     "Initial user id of client not that of www",
                    152: 		     "Usage error, not enough command line arguments",
1.500     bisitz    153: 		     "Source filename does not exist",
                    154: 		     "Destination filename does not exist",
1.412     foxr      155: 		     "Some file operation failed",
                    156: 		     "Invalid table filename."
                    157: 		     );
1.207     foxr      158: 
                    159: #
1.525     raeburn   160: # The %trust hash classifies commands according to type of trust 
                    161: # required for execution of the command.
                    162: #
                    163: # When clients from a different institution request execution of a
                    164: # particular command, the trust settings for that institution set
                    165: # for this domain (or default domain for a multi-domain server) will
                    166: # be checked to see if running the command is allowed.
                    167: #
                    168: # Trust types which depend on the "Trust" domain configuration
                    169: # for the machine's default domain are:
                    170: #
                    171: # content   ("Access to this domain's content by others")
                    172: # shared    ("Access to other domain's content by this domain")
                    173: # enroll    ("Enrollment in this domain's courses by others")
                    174: # coaurem   ("Co-author roles for this domain's users elsewhere")
                    175: # domroles  ("Domain roles in this domain assignable to others")
                    176: # catalog   ("Course Catalog for this domain displayed elsewhere")
                    177: # reqcrs    ("Requests for creation of courses in this domain by others")
                    178: # msg       ("Users in other domains can send messages to this domain")
                    179: # 
                    180: # Trust type which depends on the User Session Hosting (remote) 
                    181: # domain configuration for machine's default domain is: "remote".
                    182: #
                    183: # Trust types which depend on contents of manager.tab in 
                    184: # /home/httpd/lonTabs is: "manageronly".
                    185: # 
                    186: # Trust type which requires client to share the same LON-CAPA
                    187: # "internet domain" (i.e., same institution as this server) is:
                    188: # "institutiononly".
                    189: #
                    190: 
                    191: my %trust = (
                    192:                auth => {remote => 1},
                    193:                autocreatepassword => {remote => 1},
                    194:                autocrsreqchecks => {remote => 1, reqcrs => 1},
                    195:                autocrsrequpdate => {remote => 1},
                    196:                autocrsreqvalidation => {remote => 1},
                    197:                autogetsections => {remote => 1},
                    198:                autoinstcodedefaults => {remote => 1, catalog => 1},
                    199:                autoinstcodeformat => {remote => 1, catalog => 1},
                    200:                autonewcourse => {remote => 1, reqcrs => 1},
                    201:                autophotocheck => {remote => 1, enroll => 1},
                    202:                autophotochoice => {remote => 1},
                    203:                autophotopermission => {remote => 1, enroll => 1},
                    204:                autopossibleinstcodes => {remote => 1, reqcrs => 1},
                    205:                autoretrieve => {remote => 1, enroll => 1, catalog => 1},
                    206:                autorun => {remote => 1, enroll => 1, reqcrs => 1},
                    207:                autovalidateclass_sec => {catalog => 1},
                    208:                autovalidatecourse => {remote => 1, enroll => 1},
                    209:                autovalidateinstcode => {domroles => 1, remote => 1, enroll => 1},
                    210:                changeuserauth => {remote => 1, domroles => 1},
                    211:                chatretr => {remote => 1, enroll => 1},
                    212:                chatsend => {remote => 1, enroll => 1},
                    213:                courseiddump => {remote => 1, domroles => 1, enroll => 1},
                    214:                courseidput => {remote => 1, domroles => 1, enroll => 1},
                    215:                courseidputhash => {remote => 1, domroles => 1, enroll => 1},
                    216:                courselastaccess => {remote => 1, domroles => 1, enroll => 1},
                    217:                currentauth => {remote => 1, domroles => 1, enroll => 1},
                    218:                currentdump => {remote => 1, enroll => 1},
                    219:                currentversion => {remote=> 1, content => 1},
                    220:                dcmaildump => {remote => 1, domroles => 1},
                    221:                dcmailput => {remote => 1, domroles => 1},
                    222:                del => {remote => 1, domroles => 1, enroll => 1, content => 1},
                    223:                deldom => {remote => 1, domroles => 1}, # not currently used
                    224:                devalidatecache => {institutiononly => 1},
                    225:                domroleput => {remote => 1, enroll => 1},
                    226:                domrolesdump => {remote => 1, catalog => 1},
                    227:                du => {remote => 1, enroll => 1},
                    228:                du2 => {remote => 1, enroll => 1},
                    229:                dump => {remote => 1, enroll => 1, domroles => 1},
                    230:                edit => {institutiononly => 1},  #not used currently
                    231:                eget => {remote => 1, domroles => 1, enroll => 1}, #not used currently
1.536     raeburn   232:                egetdom => {remote => 1, domroles => 1, enroll => 1, },
1.525     raeburn   233:                ekey => {}, #not used currently
                    234:                exit => {anywhere => 1},
                    235:                fetchuserfile => {remote => 1, enroll => 1},
                    236:                get => {remote => 1, domroles => 1, enroll => 1},
                    237:                getdom => {anywhere => 1},
                    238:                home => {anywhere => 1},
                    239:                iddel => {remote => 1, enroll => 1},
                    240:                idget => {remote => 1, enroll => 1},
                    241:                idput => {remote => 1, domroles => 1, enroll => 1},
                    242:                inc => {remote => 1, enroll => 1},
                    243:                init => {anywhere => 1},
                    244:                inst_usertypes => {remote => 1, domroles => 1, enroll => 1},
                    245:                instemailrules => {remote => 1, domroles => 1},
                    246:                instidrulecheck => {remote => 1, domroles => 1,},
                    247:                instidrules => {remote => 1, domroles => 1,},
                    248:                instrulecheck => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
                    249:                instselfcreatecheck => {institutiononly => 1},
                    250:                instuserrules => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
                    251:                keys => {remote => 1,},
                    252:                load => {anywhere => 1},
                    253:                log => {anywhere => 1},
                    254:                ls => {remote => 1, enroll => 1, content => 1,},
                    255:                ls2 => {remote => 1, enroll => 1, content => 1,},
                    256:                ls3 => {remote => 1, enroll => 1, content => 1,},
                    257:                makeuser => {remote => 1, enroll => 1, domroles => 1,},
                    258:                mkdiruserfile => {remote => 1, enroll => 1,},
                    259:                newput => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1,},
                    260:                passwd => {remote => 1},
                    261:                ping => {anywhere => 1},
                    262:                pong => {anywhere => 1},
                    263:                pushfile => {manageronly => 1},
                    264:                put => {remote => 1, enroll => 1, domroles => 1, msg => 1, content => 1, shared => 1},
                    265:                putdom => {remote => 1, domroles => 1,},
                    266:                putstore => {remote => 1, enroll => 1},
                    267:                queryreply => {anywhere => 1},
                    268:                querysend => {anywhere => 1},
1.535     raeburn   269:                querysend_activitylog => {remote => 1},
                    270:                querysend_allusers => {remote => 1, domroles => 1},
                    271:                querysend_courselog => {remote => 1},
                    272:                querysend_fetchenrollment => {remote => 1},
                    273:                querysend_getinstuser => {remote => 1},
                    274:                querysend_getmultinstusers => {remote => 1},
                    275:                querysend_instdirsearch => {remote => 1, domroles => 1, coaurem => 1},
                    276:                querysend_institutionalphotos => {remote => 1},
                    277:                querysend_portfolio_metadata => {remote => 1, content => 1},
                    278:                querysend_userlog => {remote => 1, domroles => 1},
                    279:                querysend_usersearch => {remote => 1, enroll => 1, coaurem => 1},
1.525     raeburn   280:                quit => {anywhere => 1},
                    281:                readlonnetglobal => {institutiononly => 1},
                    282:                reinit => {manageronly => 1}, #not used currently
                    283:                removeuserfile => {remote => 1, enroll => 1},
                    284:                renameuserfile => {remote => 1,},
                    285:                restore => {remote => 1, enroll => 1, reqcrs => 1,},
                    286:                rolesdel => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
                    287:                rolesput => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
1.527     raeburn   288:                servercerts => {institutiononly => 1},
1.528     raeburn   289:                serverdistarch => {anywhere => 1},
1.525     raeburn   290:                serverhomeID => {anywhere => 1},
                    291:                serverloncaparev => {anywhere => 1},
                    292:                servertimezone => {remote => 1, enroll => 1},
                    293:                setannounce => {remote => 1, domroles => 1},
                    294:                sethost => {anywhere => 1},
                    295:                store => {remote => 1, enroll => 1, reqcrs => 1,},
                    296:                studentphoto => {remote => 1, enroll => 1},
                    297:                sub => {content => 1,},
                    298:                tmpdel => {anywhere => 1},
                    299:                tmpget => {anywhere => 1},
                    300:                tmpput => {anywhere => 1},
                    301:                tokenauthuserfile => {anywhere => 1},
                    302:                unsub => {content => 1,},
                    303:                update => {shared => 1},
                    304:                updateclickers => {remote => 1},
                    305:                userhassession => {anywhere => 1},
                    306:                userload => {anywhere => 1},
                    307:                version => {anywhere => 1}, #not used
                    308:             );
                    309: 
                    310: #
1.207     foxr      311: #   Statistics that are maintained and dislayed in the status line.
                    312: #
1.212     foxr      313: my $Transactions = 0;		# Number of attempted transactions.
                    314: my $Failures     = 0;		# Number of transcations failed.
1.207     foxr      315: 
                    316: #   ResetStatistics: 
                    317: #      Resets the statistics counters:
                    318: #
                    319: sub ResetStatistics {
                    320:     $Transactions = 0;
                    321:     $Failures     = 0;
                    322: }
                    323: 
1.200     matthew   324: #------------------------------------------------------------------------
                    325: #
                    326: #   LocalConnection
                    327: #     Completes the formation of a locally authenticated connection.
                    328: #     This function will ensure that the 'remote' client is really the
                    329: #     local host.  If not, the connection is closed, and the function fails.
                    330: #     If so, initcmd is parsed for the name of a file containing the
                    331: #     IDEA session key.  The fie is opened, read, deleted and the session
                    332: #     key returned to the caller.
                    333: #
                    334: # Parameters:
                    335: #   $Socket      - Socket open on client.
                    336: #   $initcmd     - The full text of the init command.
                    337: #
                    338: # Returns:
                    339: #     IDEA session key on success.
                    340: #     undef on failure.
                    341: #
                    342: sub LocalConnection {
                    343:     my ($Socket, $initcmd) = @_;
1.373     albertel  344:     Debug("Attempting local connection: $initcmd client: $clientip");
1.277     albertel  345:     if($clientip ne "127.0.0.1") {
1.200     matthew   346: 	&logthis('<font color="red"> LocalConnection rejecting non local: '
1.373     albertel  347: 		 ."$clientip ne 127.0.0.1 </font>");
1.200     matthew   348: 	close $Socket;
                    349: 	return undef;
1.224     foxr      350:     }  else {
1.200     matthew   351: 	chomp($initcmd);	# Get rid of \n in filename.
                    352: 	my ($init, $type, $name) = split(/:/, $initcmd);
                    353: 	Debug(" Init command: $init $type $name ");
                    354: 
                    355: 	# Require that $init = init, and $type = local:  Otherwise
                    356: 	# the caller is insane:
                    357: 
                    358: 	if(($init ne "init") && ($type ne "local")) {
                    359: 	    &logthis('<font color = "red"> LocalConnection: caller is insane! '
                    360: 		     ."init = $init, and type = $type </font>");
                    361: 	    close($Socket);;
                    362: 	    return undef;
                    363: 		
                    364: 	}
                    365: 	#  Now get the key filename:
                    366: 
                    367: 	my $IDEAKey = lonlocal::ReadKeyFile($name);
                    368: 	return $IDEAKey;
                    369:     }
                    370: }
                    371: #------------------------------------------------------------------------------
                    372: #
                    373: #  SSLConnection
                    374: #   Completes the formation of an ssh authenticated connection. The
                    375: #   socket is promoted to an ssl socket.  If this promotion and the associated
                    376: #   certificate exchange are successful, the IDEA key is generated and sent
                    377: #   to the remote peer via the SSL tunnel. The IDEA key is also returned to
                    378: #   the caller after the SSL tunnel is torn down.
                    379: #
                    380: # Parameters:
                    381: #   Name              Type             Purpose
                    382: #   $Socket          IO::Socket::INET  Plaintext socket.
                    383: #
                    384: # Returns:
                    385: #    IDEA key on success.
                    386: #    undef on failure.
                    387: #
                    388: sub SSLConnection {
                    389:     my $Socket   = shift;
                    390: 
                    391:     Debug("SSLConnection: ");
                    392:     my $KeyFile         = lonssl::KeyFile();
                    393:     if(!$KeyFile) {
                    394: 	my $err = lonssl::LastError();
                    395: 	&logthis("<font color=\"red\"> CRITICAL"
                    396: 		 ."Can't get key file $err </font>");
                    397: 	return undef;
                    398:     }
                    399:     my ($CACertificate,
                    400: 	$Certificate) = lonssl::CertificateFile();
                    401: 
                    402: 
                    403:     # If any of the key, certificate or certificate authority 
                    404:     # certificate filenames are not defined, this can't work.
                    405: 
                    406:     if((!$Certificate) || (!$CACertificate)) {
                    407: 	my $err = lonssl::LastError();
                    408: 	&logthis("<font color=\"red\"> CRITICAL"
                    409: 		 ."Can't get certificates: $err </font>");
                    410: 
                    411: 	return undef;
                    412:     }
                    413:     Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
                    414: 
                    415:     # Indicate to our peer that we can procede with
                    416:     # a transition to ssl authentication:
                    417: 
                    418:     print $Socket "ok:ssl\n";
                    419: 
                    420:     Debug("Approving promotion -> ssl");
                    421:     #  And do so:
                    422: 
                    423:     my $SSLSocket = lonssl::PromoteServerSocket($Socket,
                    424: 						$CACertificate,
                    425: 						$Certificate,
                    426: 						$KeyFile);
                    427:     if(! ($SSLSocket) ) {	# SSL socket promotion failed.
                    428: 	my $err = lonssl::LastError();
                    429: 	&logthis("<font color=\"red\"> CRITICAL "
                    430: 		 ."SSL Socket promotion failed: $err </font>");
                    431: 	return undef;
                    432:     }
                    433:     Debug("SSL Promotion successful");
                    434: 
                    435:     # 
                    436:     #  The only thing we'll use the socket for is to send the IDEA key
                    437:     #  to the peer:
                    438: 
                    439:     my $Key = lonlocal::CreateCipherKey();
                    440:     print $SSLSocket "$Key\n";
                    441: 
                    442:     lonssl::Close($SSLSocket); 
                    443: 
                    444:     Debug("Key exchange complete: $Key");
                    445: 
                    446:     return $Key;
                    447: }
                    448: #
                    449: #     InsecureConnection: 
                    450: #        If insecure connections are allowd,
                    451: #        exchange a challenge with the client to 'validate' the
                    452: #        client (not really, but that's the protocol):
                    453: #        We produce a challenge string that's sent to the client.
                    454: #        The client must then echo the challenge verbatim to us.
                    455: #
                    456: #  Parameter:
                    457: #      Socket      - Socket open on the client.
                    458: #  Returns:
                    459: #      1           - success.
                    460: #      0           - failure (e.g.mismatch or insecure not allowed).
                    461: #
                    462: sub InsecureConnection {
                    463:     my $Socket  =  shift;
                    464: 
                    465:     #   Don't even start if insecure connections are not allowed.
1.532     raeburn   466:     #   return 0 if Insecure connections not allowed.
                    467:     #
                    468:     if (ref($secureconf{'connfrom'}) eq 'HASH') {
                    469:         if ($clientsamedom) {
                    470:             if ($secureconf{'connfrom'}{'dom'} eq 'req') {
                    471:                 return 0;
                    472:             } 
                    473:         } elsif ($clientsameinst) {
                    474:             if ($secureconf{'connfrom'}{'intdom'} eq 'req') {
                    475:                 return 0;
                    476:             }
                    477:         } else {
                    478:             if ($secureconf{'connfrom'}{'other'} eq 'req') {
                    479:                 return 0;
                    480:             }
                    481:         }
                    482:     } elsif (!$perlvar{londAllowInsecure}) {
1.200     matthew   483: 	return 0;
                    484:     }
                    485: 
                    486:     #   Fabricate a challenge string and send it..
                    487: 
                    488:     my $challenge = "$$".time;	# pid + time.
                    489:     print $Socket "$challenge\n";
                    490:     &status("Waiting for challenge reply");
                    491: 
                    492:     my $answer = <$Socket>;
                    493:     $answer    =~s/\W//g;
                    494:     if($challenge eq $answer) {
                    495: 	return 1;
1.224     foxr      496:     } else {
1.200     matthew   497: 	logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
                    498: 	&status("No challenge reqply");
                    499: 	return 0;
                    500:     }
                    501:     
                    502: 
                    503: }
1.251     foxr      504: #
                    505: #   Safely execute a command (as long as it's not a shel command and doesn
                    506: #   not require/rely on shell escapes.   The function operates by doing a
                    507: #   a pipe based fork and capturing stdout and stderr  from the pipe.
                    508: #
                    509: # Formal Parameters:
                    510: #     $line                    - A line of text to be executed as a command.
                    511: # Returns:
                    512: #     The output from that command.  If the output is multiline the caller
                    513: #     must know how to split up the output.
                    514: #
                    515: #
                    516: sub execute_command {
                    517:     my ($line)    = @_;
                    518:     my @words     = split(/\s/, $line);	# Bust the command up into words.
                    519:     my $output    = "";
                    520: 
                    521:     my $pid = open(CHILD, "-|");
                    522:     
                    523:     if($pid) {			# Parent process
                    524: 	Debug("In parent process for execute_command");
                    525: 	my @data = <CHILD>;	# Read the child's outupt...
                    526: 	close CHILD;
                    527: 	foreach my $output_line (@data) {
                    528: 	    Debug("Adding $output_line");
                    529: 	    $output .= $output_line; # Presumably has a \n on it.
                    530: 	}
                    531: 
                    532:     } else {			# Child process
                    533: 	close (STDERR);
                    534: 	open  (STDERR, ">&STDOUT");# Combine stderr, and stdout...
                    535: 	exec(@words);		# won't return.
                    536:     }
                    537:     return $output;
                    538: }
                    539: 
1.200     matthew   540: 
1.140     foxr      541: #   GetCertificate: Given a transaction that requires a certificate,
                    542: #   this function will extract the certificate from the transaction
                    543: #   request.  Note that at this point, the only concept of a certificate
                    544: #   is the hostname to which we are connected.
                    545: #
                    546: #   Parameter:
                    547: #      request   - The request sent by our client (this parameterization may
                    548: #                  need to change when we really use a certificate granting
                    549: #                  authority.
                    550: #
                    551: sub GetCertificate {
                    552:     my $request = shift;
                    553: 
                    554:     return $clientip;
                    555: }
1.161     foxr      556: 
1.178     foxr      557: #
                    558: #   Return true if client is a manager.
                    559: #
                    560: sub isManager {
                    561:     return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
                    562: }
                    563: #
                    564: #   Return tru if client can do client functions
                    565: #
                    566: sub isClient {
                    567:     return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
                    568: }
1.161     foxr      569: 
                    570: 
1.156     foxr      571: #
                    572: #   ReadManagerTable: Reads in the current manager table. For now this is
                    573: #                     done on each manager authentication because:
                    574: #                     - These authentications are not frequent
                    575: #                     - This allows dynamic changes to the manager table
                    576: #                       without the need to signal to the lond.
                    577: #
                    578: sub ReadManagerTable {
                    579: 
1.412     foxr      580:     &Debug("Reading manager table");
1.156     foxr      581:     #   Clean out the old table first..
                    582: 
1.166     foxr      583:    foreach my $key (keys %managers) {
                    584:       delete $managers{$key};
                    585:    }
                    586: 
                    587:    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
                    588:    if (!open (MANAGERS, $tablename)) {
1.473     raeburn   589:        my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
                    590:        if (&Apache::lonnet::is_LC_dns($hostname)) {
1.472     raeburn   591:            &logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
                    592:        }
                    593:        return;
1.166     foxr      594:    }
                    595:    while(my $host = <MANAGERS>) {
                    596:       chomp($host);
                    597:       if ($host =~ "^#") {                  # Comment line.
                    598:          next;
                    599:       }
1.368     albertel  600:       if (!defined &Apache::lonnet::get_host_ip($host)) { # This is a non cluster member
1.161     foxr      601: 	    #  The entry is of the form:
                    602: 	    #    cluname:hostname
                    603: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
                    604: 	    #            the host key.
                    605: 	    #  hostname- The dns name of the host.
                    606: 	    #
1.166     foxr      607:           my($cluname, $dnsname) = split(/:/, $host);
                    608:           
                    609:           my $ip = gethostbyname($dnsname);
                    610:           if(defined($ip)) {                 # bad names don't deserve entry.
                    611:             my $hostip = inet_ntoa($ip);
                    612:             $managers{$hostip} = $cluname;
                    613:             logthis('<font color="green"> registering manager '.
                    614:                     "$dnsname as $cluname with $hostip </font>\n");
                    615:          }
                    616:       } else {
                    617:          logthis('<font color="green"> existing host'." $host</font>\n");
1.472     raeburn   618:          $managers{&Apache::lonnet::get_host_ip($host)} = $host;  # Use info from cluster tab if cluster memeber
1.166     foxr      619:       }
                    620:    }
1.156     foxr      621: }
1.140     foxr      622: 
                    623: #
                    624: #  ValidManager: Determines if a given certificate represents a valid manager.
                    625: #                in this primitive implementation, the 'certificate' is
                    626: #                just the connecting loncapa client name.  This is checked
                    627: #                against a valid client list in the configuration.
                    628: #
                    629: #                  
                    630: sub ValidManager {
                    631:     my $certificate = shift; 
                    632: 
1.163     foxr      633:     return isManager;
1.140     foxr      634: }
                    635: #
1.143     foxr      636: #  CopyFile:  Called as part of the process of installing a 
                    637: #             new configuration file.  This function copies an existing
                    638: #             file to a backup file.
                    639: # Parameters:
                    640: #     oldfile  - Name of the file to backup.
                    641: #     newfile  - Name of the backup file.
                    642: # Return:
                    643: #     0   - Failure (errno has failure reason).
                    644: #     1   - Success.
                    645: #
                    646: sub CopyFile {
1.192     foxr      647: 
                    648:     my ($oldfile, $newfile) = @_;
1.143     foxr      649: 
1.281     matthew   650:     if (! copy($oldfile,$newfile)) {
                    651:         return 0;
1.143     foxr      652:     }
1.281     matthew   653:     chmod(0660, $newfile);
                    654:     return 1;
1.143     foxr      655: }
1.157     foxr      656: #
                    657: #  Host files are passed out with externally visible host IPs.
                    658: #  If, for example, we are behind a fire-wall or NAT host, our 
                    659: #  internally visible IP may be different than the externally
                    660: #  visible IP.  Therefore, we always adjust the contents of the
                    661: #  host file so that the entry for ME is the IP that we believe
                    662: #  we have.  At present, this is defined as the entry that
                    663: #  DNS has for us.  If by some chance we are not able to get a
                    664: #  DNS translation for us, then we assume that the host.tab file
                    665: #  is correct.  
                    666: #    BUGBUGBUG - in the future, we really should see if we can
                    667: #       easily query the interface(s) instead.
                    668: # Parameter(s):
                    669: #     contents    - The contents of the host.tab to check.
                    670: # Returns:
                    671: #     newcontents - The adjusted contents.
                    672: #
                    673: #
                    674: sub AdjustHostContents {
                    675:     my $contents  = shift;
                    676:     my $adjusted;
                    677:     my $me        = $perlvar{'lonHostID'};
                    678: 
1.354     albertel  679:     foreach my $line (split(/\n/,$contents)) {
1.472     raeburn   680: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/) ||
                    681:              ($line =~ /^\s*\^/))) {
1.157     foxr      682: 	    chomp($line);
                    683: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
                    684: 	    if ($id eq $me) {
1.354     albertel  685: 		my $ip = gethostbyname($name);
                    686: 		my $ipnew = inet_ntoa($ip);
                    687: 		$ip = $ipnew;
1.157     foxr      688: 		#  Reconstruct the host line and append to adjusted:
                    689: 		
1.354     albertel  690: 		my $newline = "$id:$domain:$role:$name:$ip";
                    691: 		if($maxcon ne "") { # Not all hosts have loncnew tuning params
                    692: 		    $newline .= ":$maxcon:$idleto:$mincon";
                    693: 		}
                    694: 		$adjusted .= $newline."\n";
1.157     foxr      695: 		
1.354     albertel  696: 	    } else {		# Not me, pass unmodified.
                    697: 		$adjusted .= $line."\n";
                    698: 	    }
1.157     foxr      699: 	} else {                  # Blank or comment never re-written.
                    700: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
                    701: 	}
1.354     albertel  702:     }
                    703:     return $adjusted;
1.157     foxr      704: }
1.143     foxr      705: #
                    706: #   InstallFile: Called to install an administrative file:
1.412     foxr      707: #       - The file is created int a temp directory called <name>.tmp
                    708: #       - lcinstall file is called to install the file.
                    709: #         since the web app has no direct write access to the table directory
1.143     foxr      710: #
                    711: #  Parameters:
                    712: #       Name of the file
                    713: #       File Contents.
                    714: #  Return:
                    715: #      nonzero - success.
                    716: #      0       - failure and $! has an errno.
1.412     foxr      717: # Assumptions:
                    718: #    File installtion is a relatively infrequent
1.143     foxr      719: #
                    720: sub InstallFile {
1.192     foxr      721: 
                    722:     my ($Filename, $Contents) = @_;
1.412     foxr      723: #     my $TempFile = $Filename.".tmp";
                    724:     my $exedir = $perlvar{'lonDaemons'};
                    725:     my $tmpdir = $exedir.'/tmp/';
                    726:     my $TempFile = $tmpdir."TempTableFile.tmp";
1.143     foxr      727: 
                    728:     #  Open the file for write:
                    729: 
                    730:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
                    731:     if(!(defined $fh)) {
                    732: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
                    733: 	return 0;
                    734:     }
                    735:     #  write the contents of the file:
                    736: 
                    737:     print $fh ($Contents); 
                    738:     $fh->close;			# In case we ever have a filesystem w. locking
                    739: 
1.412     foxr      740:     chmod(0664, $TempFile);	# Everyone can write it.
                    741: 
                    742:     # Use lcinstall file to put the file in the table directory...
                    743: 
                    744:     &Debug("Opening pipe to $exedir/lcinstallfile $TempFile $Filename");
                    745:     my $pf = IO::File->new("| $exedir/lcinstallfile   $TempFile $Filename > $exedir/logs/lcinstallfile.log");
                    746:     close $pf;
                    747:     my $err = $?;
                    748:     &Debug("Status is $err");
                    749:     if ($err != 0) {
                    750: 	my $msg = $err;
                    751: 	if ($err < @installerrors) {
                    752: 	    $msg = $installerrors[$err];
                    753: 	}
                    754: 	&logthis("Install failed for table file $Filename : $msg");
                    755: 	return 0;
                    756:     }
                    757: 
                    758:     # Remove the temp file:
1.143     foxr      759: 
1.412     foxr      760:     unlink($TempFile);
1.143     foxr      761: 
                    762:     return 1;
                    763: }
1.200     matthew   764: 
                    765: 
1.169     foxr      766: #
                    767: #   ConfigFileFromSelector: converts a configuration file selector
1.411     foxr      768: #                 into a configuration file pathname.
1.472     raeburn   769: #                 Supports the following file selectors: 
                    770: #                 hosts, domain, dns_hosts, dns_domain  
1.411     foxr      771: #
1.169     foxr      772: #
                    773: #  Parameters:
                    774: #      selector  - Configuration file selector.
                    775: #  Returns:
                    776: #      Full path to the file or undef if the selector is invalid.
                    777: #
                    778: sub ConfigFileFromSelector {
                    779:     my $selector   = shift;
                    780:     my $tablefile;
                    781: 
                    782:     my $tabledir = $perlvar{'lonTabDir'}.'/';
1.472     raeburn   783:     if (($selector eq "hosts") || ($selector eq "domain") || 
                    784:         ($selector eq "dns_hosts") || ($selector eq "dns_domain")) {
1.411     foxr      785: 	$tablefile =  $tabledir.$selector.'.tab';
1.169     foxr      786:     }
                    787:     return $tablefile;
                    788: }
1.143     foxr      789: #
1.141     foxr      790: #   PushFile:  Called to do an administrative push of a file.
                    791: #              - Ensure the file being pushed is one we support.
                    792: #              - Backup the old file to <filename.saved>
                    793: #              - Separate the contents of the new file out from the
                    794: #                rest of the request.
                    795: #              - Write the new file.
                    796: #  Parameter:
                    797: #     Request - The entire user request.  This consists of a : separated
                    798: #               string pushfile:tablename:contents.
                    799: #     NOTE:  The contents may have :'s in it as well making things a bit
                    800: #            more interesting... but not much.
                    801: #  Returns:
                    802: #     String to send to client ("ok" or "refused" if bad file).
                    803: #
                    804: sub PushFile {
1.510     raeburn   805:     my $request = shift;
1.141     foxr      806:     my ($command, $filename, $contents) = split(":", $request, 3);
1.412     foxr      807:     &Debug("PushFile");
1.141     foxr      808:     
                    809:     #  At this point in time, pushes for only the following tables are
                    810:     #  supported:
                    811:     #   hosts.tab  ($filename eq host).
                    812:     #   domain.tab ($filename eq domain).
1.472     raeburn   813:     #   dns_hosts.tab ($filename eq dns_host).
                    814:     #   dns_domain.tab ($filename eq dns_domain). 
1.141     foxr      815:     # Construct the destination filename or reject the request.
                    816:     #
                    817:     # lonManage is supposed to ensure this, however this session could be
                    818:     # part of some elaborate spoof that managed somehow to authenticate.
                    819:     #
                    820: 
1.169     foxr      821: 
                    822:     my $tablefile = ConfigFileFromSelector($filename);
                    823:     if(! (defined $tablefile)) {
1.141     foxr      824: 	return "refused";
                    825:     }
1.412     foxr      826: 
1.157     foxr      827:     #  If the file being pushed is the host file, we adjust the entry for ourself so that the
                    828:     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
                    829:     #  to conceive of conditions where we don't have a DNS entry locally.  This is possible in a 
                    830:     #  network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
                    831:     #  that possibilty.
                    832: 
                    833:     if($filename eq "host") {
                    834: 	$contents = AdjustHostContents($contents);
1.510     raeburn   835:     } elsif ($filename eq 'dns_host' || $filename eq 'dns_domain') {
                    836:         if ($contents eq '') {
                    837:             &logthis('<font color="red"> Pushfile: unable to install '
                    838:                     .$tablefile." - no data received from push. </font>");
                    839:             return 'error: push had no data';
                    840:         }
                    841:         if (&Apache::lonnet::get_host_ip($clientname)) {
                    842:             my $clienthost = &Apache::lonnet::hostname($clientname);
                    843:             if ($managers{$clientip} eq $clientname) {
                    844:                 my $clientprotocol = $Apache::lonnet::protocol{$clientname};
                    845:                 $clientprotocol = 'http' if ($clientprotocol ne 'https');
                    846:                 my $url = '/adm/'.$filename;
                    847:                 $url =~ s{_}{/};
                    848:                 my $request=new HTTP::Request('GET',"$clientprotocol://$clienthost$url");
1.523     raeburn   849:                 my $response = LONCAPA::LWPReq::makerequest($clientname,$request,'',\%perlvar,60,0);
1.510     raeburn   850:                 if ($response->is_error()) {
                    851:                     &logthis('<font color="red"> Pushfile: unable to install '
                    852:                             .$tablefile." - error attempting to pull data. </font>");
                    853:                     return 'error: pull failed';
                    854:                 } else {
                    855:                     my $result = $response->content;
                    856:                     chomp($result);
                    857:                     unless ($result eq $contents) {
                    858:                         &logthis('<font color="red"> Pushfile: unable to install '
                    859:                                 .$tablefile." - pushed data and pulled data differ. </font>");
                    860:                         my $pushleng = length($contents);
                    861:                         my $pullleng = length($result);
                    862:                         if ($pushleng != $pullleng) {
                    863:                             return "error: $pushleng vs $pullleng bytes";
                    864:                         } else {
                    865:                             return "error: mismatch push and pull";
                    866:                         }
                    867:                     }
                    868:                 }
                    869:             }
                    870:         }
1.157     foxr      871:     }
                    872: 
1.141     foxr      873:     #  Install the new file:
                    874: 
1.412     foxr      875:     &logthis("Installing new $tablefile contents:\n$contents");
1.143     foxr      876:     if(!InstallFile($tablefile, $contents)) {
                    877: 	&logthis('<font color="red"> Pushfile: unable to install '
1.145     foxr      878: 	 .$tablefile." $! </font>");
1.143     foxr      879: 	return "error:$!";
1.224     foxr      880:     } else {
1.143     foxr      881: 	&logthis('<font color="green"> Installed new '.$tablefile
1.473     raeburn   882: 		 ." - transaction by: $clientname ($clientip)</font>");
1.472     raeburn   883:         my $adminmail = $perlvar{'lonAdmEMail'};
                    884:         my $admindom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                    885:         if ($admindom ne '') {
                    886:             my %domconfig =
                    887:                 &Apache::lonnet::get_dom('configuration',['contacts'],$admindom);
                    888:             if (ref($domconfig{'contacts'}) eq 'HASH') {
                    889:                 if ($domconfig{'contacts'}{'adminemail'} ne '') {
                    890:                     $adminmail = $domconfig{'contacts'}{'adminemail'};
                    891:                 }
                    892:             }
                    893:         }
                    894:         if ($adminmail =~ /^[^\@]+\@[^\@]+$/) {
                    895:             my $msg = new Mail::Send;
                    896:             $msg->to($adminmail);
                    897:             $msg->subject('LON-CAPA DNS update on '.$perlvar{'lonHostID'});
                    898:             $msg->add('Content-type','text/plain; charset=UTF-8');
                    899:             if (my $fh = $msg->open()) {
                    900:                 print $fh 'Update to '.$tablefile.' from Cluster Manager '.
1.473     raeburn   901:                           "$clientname ($clientip)\n";
1.472     raeburn   902:                 $fh->close;
                    903:             }
                    904:         }
1.143     foxr      905:     }
                    906: 
1.141     foxr      907:     #  Indicate success:
                    908:  
                    909:     return "ok";
                    910: 
                    911: }
1.145     foxr      912: 
                    913: #
                    914: #  Called to re-init either lonc or lond.
                    915: #
                    916: #  Parameters:
                    917: #    request   - The full request by the client.  This is of the form
                    918: #                reinit:<process>  
                    919: #                where <process> is allowed to be either of 
                    920: #                lonc or lond
                    921: #
                    922: #  Returns:
                    923: #     The string to be sent back to the client either:
                    924: #   ok         - Everything worked just fine.
                    925: #   error:why  - There was a failure and why describes the reason.
                    926: #
                    927: #
                    928: sub ReinitProcess {
                    929:     my $request = shift;
                    930: 
1.146     foxr      931: 
                    932:     # separate the request (reinit) from the process identifier and
                    933:     # validate it producing the name of the .pid file for the process.
                    934:     #
                    935:     #
                    936:     my ($junk, $process) = split(":", $request);
1.147     foxr      937:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
1.146     foxr      938:     if($process eq 'lonc') {
                    939: 	$processpidfile = $processpidfile."lonc.pid";
1.147     foxr      940: 	if (!open(PIDFILE, "< $processpidfile")) {
                    941: 	    return "error:Open failed for $processpidfile";
                    942: 	}
                    943: 	my $loncpid = <PIDFILE>;
                    944: 	close(PIDFILE);
                    945: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
                    946: 		."</font>");
                    947: 	kill("USR2", $loncpid);
1.146     foxr      948:     } elsif ($process eq 'lond') {
1.147     foxr      949: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
                    950: 	&UpdateHosts;			# Lond is us!!
1.146     foxr      951:     } else {
                    952: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
                    953: 		 ."</font>");
                    954: 	return "error:Invalid process identifier $process";
                    955:     }
1.145     foxr      956:     return 'ok';
                    957: }
1.168     foxr      958: #   Validate a line in a configuration file edit script:
                    959: #   Validation includes:
                    960: #     - Ensuring the command is valid.
                    961: #     - Ensuring the command has sufficient parameters
                    962: #   Parameters:
                    963: #     scriptline - A line to validate (\n has been stripped for what it's worth).
1.167     foxr      964: #
1.168     foxr      965: #   Return:
                    966: #      0     - Invalid scriptline.
                    967: #      1     - Valid scriptline
                    968: #  NOTE:
                    969: #     Only the command syntax is checked, not the executability of the
                    970: #     command.
                    971: #
                    972: sub isValidEditCommand {
                    973:     my $scriptline = shift;
                    974: 
                    975:     #   Line elements are pipe separated:
                    976: 
                    977:     my ($command, $key, $newline)  = split(/\|/, $scriptline);
                    978:     &logthis('<font color="green"> isValideditCommand checking: '.
                    979: 	     "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
                    980:     
                    981:     if ($command eq "delete") {
                    982: 	#
                    983: 	#   key with no newline.
                    984: 	#
                    985: 	if( ($key eq "") || ($newline ne "")) {
                    986: 	    return 0;		# Must have key but no newline.
                    987: 	} else {
                    988: 	    return 1;		# Valid syntax.
                    989: 	}
1.169     foxr      990:     } elsif ($command eq "replace") {
1.168     foxr      991: 	#
                    992: 	#   key and newline:
                    993: 	#
                    994: 	if (($key eq "") || ($newline eq "")) {
                    995: 	    return 0;
                    996: 	} else {
                    997: 	    return 1;
                    998: 	}
1.169     foxr      999:     } elsif ($command eq "append") {
                   1000: 	if (($key ne "") && ($newline eq "")) {
                   1001: 	    return 1;
                   1002: 	} else {
                   1003: 	    return 0;
                   1004: 	}
1.168     foxr     1005:     } else {
                   1006: 	return 0;		# Invalid command.
                   1007:     }
                   1008:     return 0;			# Should not get here!!!
                   1009: }
1.169     foxr     1010: #
                   1011: #   ApplyEdit - Applies an edit command to a line in a configuration 
                   1012: #               file.  It is the caller's responsiblity to validate the
                   1013: #               edit line.
                   1014: #   Parameters:
                   1015: #      $directive - A single edit directive to apply.  
                   1016: #                   Edit directives are of the form:
                   1017: #                  append|newline      - Appends a new line to the file.
                   1018: #                  replace|key|newline - Replaces the line with key value 'key'
                   1019: #                  delete|key          - Deletes the line with key value 'key'.
                   1020: #      $editor   - A config file editor object that contains the
                   1021: #                  file being edited.
                   1022: #
                   1023: sub ApplyEdit {
1.192     foxr     1024: 
                   1025:     my ($directive, $editor) = @_;
1.169     foxr     1026: 
                   1027:     # Break the directive down into its command and its parameters
                   1028:     # (at most two at this point.  The meaning of the parameters, if in fact
                   1029:     #  they exist depends on the command).
                   1030: 
                   1031:     my ($command, $p1, $p2) = split(/\|/, $directive);
                   1032: 
                   1033:     if($command eq "append") {
                   1034: 	$editor->Append($p1);	          # p1 - key p2 null.
                   1035:     } elsif ($command eq "replace") {
                   1036: 	$editor->ReplaceLine($p1, $p2);   # p1 - key p2 = newline.
                   1037:     } elsif ($command eq "delete") {
                   1038: 	$editor->DeleteLine($p1);         # p1 - key p2 null.
                   1039:     } else {			          # Should not get here!!!
                   1040: 	die "Invalid command given to ApplyEdit $command"
                   1041:     }
                   1042: }
                   1043: #
                   1044: # AdjustOurHost:
                   1045: #           Adjusts a host file stored in a configuration file editor object
                   1046: #           for the true IP address of this host. This is necessary for hosts
                   1047: #           that live behind a firewall.
                   1048: #           Those hosts have a publicly distributed IP of the firewall, but
                   1049: #           internally must use their actual IP.  We assume that a given
                   1050: #           host only has a single IP interface for now.
                   1051: # Formal Parameters:
                   1052: #     editor   - The configuration file editor to adjust.  This
                   1053: #                editor is assumed to contain a hosts.tab file.
                   1054: # Strategy:
                   1055: #    - Figure out our hostname.
                   1056: #    - Lookup the entry for this host.
                   1057: #    - Modify the line to contain our IP
                   1058: #    - Do a replace for this host.
                   1059: sub AdjustOurHost {
                   1060:     my $editor        = shift;
                   1061: 
                   1062:     # figure out who I am.
                   1063: 
                   1064:     my $myHostName    = $perlvar{'lonHostID'}; # LonCAPA hostname.
                   1065: 
                   1066:     #  Get my host file entry.
                   1067: 
                   1068:     my $ConfigLine    = $editor->Find($myHostName);
                   1069:     if(! (defined $ConfigLine)) {
                   1070: 	die "AdjustOurHost - no entry for me in hosts file $myHostName";
                   1071:     }
                   1072:     # figure out my IP:
                   1073:     #   Use the config line to get my hostname.
                   1074:     #   Use gethostbyname to translate that into an IP address.
                   1075:     #
1.338     albertel 1076:     my ($id,$domain,$role,$name,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
1.169     foxr     1077:     #
                   1078:     #  Reassemble the config line from the elements in the list.
                   1079:     #  Note that if the loncnew items were not present before, they will
                   1080:     #  be now even if they would be empty
                   1081:     #
                   1082:     my $newConfigLine = $id;
1.338     albertel 1083:     foreach my $item ($domain, $role, $name, $maxcon, $idleto, $mincon) {
1.169     foxr     1084: 	$newConfigLine .= ":".$item;
                   1085:     }
                   1086:     #  Replace the line:
                   1087: 
                   1088:     $editor->ReplaceLine($id, $newConfigLine);
                   1089:     
                   1090: }
                   1091: #
                   1092: #   ReplaceConfigFile:
                   1093: #              Replaces a configuration file with the contents of a
                   1094: #              configuration file editor object.
                   1095: #              This is done by:
                   1096: #              - Copying the target file to <filename>.old
                   1097: #              - Writing the new file to <filename>.tmp
                   1098: #              - Moving <filename.tmp>  -> <filename>
                   1099: #              This laborious process ensures that the system is never without
                   1100: #              a configuration file that's at least valid (even if the contents
                   1101: #              may be dated).
                   1102: #   Parameters:
                   1103: #        filename   - Name of the file to modify... this is a full path.
                   1104: #        editor     - Editor containing the file.
                   1105: #
                   1106: sub ReplaceConfigFile {
1.192     foxr     1107:     
                   1108:     my ($filename, $editor) = @_;
1.168     foxr     1109: 
1.169     foxr     1110:     CopyFile ($filename, $filename.".old");
                   1111: 
                   1112:     my $contents  = $editor->Get(); # Get the contents of the file.
                   1113: 
                   1114:     InstallFile($filename, $contents);
                   1115: }
1.168     foxr     1116: #   
                   1117: #
                   1118: #   Called to edit a configuration table  file
1.167     foxr     1119: #   Parameters:
                   1120: #      request           - The entire command/request sent by lonc or lonManage
                   1121: #   Return:
                   1122: #      The reply to send to the client.
1.168     foxr     1123: #
1.167     foxr     1124: sub EditFile {
                   1125:     my $request = shift;
                   1126: 
                   1127:     #  Split the command into it's pieces:  edit:filetype:script
                   1128: 
1.339     albertel 1129:     my ($cmd, $filetype, $script) = split(/:/, $request,3);	# : in script
1.167     foxr     1130: 
                   1131:     #  Check the pre-coditions for success:
                   1132: 
1.339     albertel 1133:     if($cmd != "edit") {	# Something is amiss afoot alack.
1.167     foxr     1134: 	return "error:edit request detected, but request != 'edit'\n";
                   1135:     }
                   1136:     if( ($filetype ne "hosts")  &&
                   1137: 	($filetype ne "domain")) {
                   1138: 	return "error:edit requested with invalid file specifier: $filetype \n";
                   1139:     }
                   1140: 
                   1141:     #   Split the edit script and check it's validity.
1.168     foxr     1142: 
                   1143:     my @scriptlines = split(/\n/, $script);  # one line per element.
                   1144:     my $linecount   = scalar(@scriptlines);
                   1145:     for(my $i = 0; $i < $linecount; $i++) {
                   1146: 	chomp($scriptlines[$i]);
                   1147: 	if(!isValidEditCommand($scriptlines[$i])) {
                   1148: 	    return "error:edit with bad script line: '$scriptlines[$i]' \n";
                   1149: 	}
                   1150:     }
1.145     foxr     1151: 
1.167     foxr     1152:     #   Execute the edit operation.
1.169     foxr     1153:     #   - Create a config file editor for the appropriate file and 
                   1154:     #   - execute each command in the script:
                   1155:     #
                   1156:     my $configfile = ConfigFileFromSelector($filetype);
                   1157:     if (!(defined $configfile)) {
                   1158: 	return "refused\n";
                   1159:     }
                   1160:     my $editor = ConfigFileEdit->new($configfile);
1.167     foxr     1161: 
1.169     foxr     1162:     for (my $i = 0; $i < $linecount; $i++) {
                   1163: 	ApplyEdit($scriptlines[$i], $editor);
                   1164:     }
                   1165:     # If the file is the host file, ensure that our host is
                   1166:     # adjusted to have our ip:
                   1167:     #
                   1168:     if($filetype eq "host") {
                   1169: 	AdjustOurHost($editor);
                   1170:     }
                   1171:     #  Finally replace the current file with our file.
                   1172:     #
                   1173:     ReplaceConfigFile($configfile, $editor);
1.167     foxr     1174: 
                   1175:     return "ok\n";
                   1176: }
1.207     foxr     1177: 
1.255     foxr     1178: #   read_profile
                   1179: #
                   1180: #   Returns a set of specific entries from a user's profile file.
                   1181: #   this is a utility function that is used by both get_profile_entry and
                   1182: #   get_profile_entry_encrypted.
                   1183: #
                   1184: # Parameters:
                   1185: #    udom       - Domain in which the user exists.
                   1186: #    uname      - User's account name (loncapa account)
                   1187: #    namespace  - The profile namespace to open.
                   1188: #    what       - A set of & separated queries.
                   1189: # Returns:
                   1190: #    If all ok: - The string that needs to be shipped back to the user.
                   1191: #    If failure - A string that starts with error: followed by the failure
                   1192: #                 reason.. note that this probabyl gets shipped back to the
                   1193: #                 user as well.
                   1194: #
                   1195: sub read_profile {
                   1196:     my ($udom, $uname, $namespace, $what) = @_;
                   1197:     
                   1198:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   1199: 				 &GDBM_READER());
                   1200:     if ($hashref) {
                   1201:         my @queries=split(/\&/,$what);
1.440     raeburn  1202:         if ($namespace eq 'roles') {
                   1203:             @queries = map { &unescape($_); } @queries; 
                   1204:         }
1.255     foxr     1205:         my $qresult='';
                   1206: 	
                   1207: 	for (my $i=0;$i<=$#queries;$i++) {
                   1208: 	    $qresult.="$hashref->{$queries[$i]}&";    # Presumably failure gives empty string.
                   1209: 	}
                   1210: 	$qresult=~s/\&$//;              # Remove trailing & from last lookup.
1.311     albertel 1211: 	if (&untie_user_hash($hashref)) {
1.255     foxr     1212: 	    return $qresult;
                   1213: 	} else {
                   1214: 	    return "error: ".($!+0)." untie (GDBM) Failed";
                   1215: 	}
                   1216:     } else {
                   1217: 	if ($!+0 == 2) {
                   1218: 	    return "error:No such file or GDBM reported bad block error";
                   1219: 	} else {
                   1220: 	    return "error: ".($!+0)." tie (GDBM) Failed";
                   1221: 	}
                   1222:     }
                   1223: 
                   1224: }
1.214     foxr     1225: #--------------------- Request Handlers --------------------------------------------
                   1226: #
1.215     foxr     1227: #   By convention each request handler registers itself prior to the sub 
                   1228: #   declaration:
1.214     foxr     1229: #
                   1230: 
1.216     foxr     1231: #++
                   1232: #
1.214     foxr     1233: #  Handles ping requests.
                   1234: #  Parameters:
                   1235: #      $cmd    - the actual keyword that invoked us.
                   1236: #      $tail   - the tail of the request that invoked us.
                   1237: #      $replyfd- File descriptor connected to the client
                   1238: #  Implicit Inputs:
                   1239: #      $currenthostid - Global variable that carries the name of the host we are
                   1240: #                       known as.
                   1241: #  Returns:
                   1242: #      1       - Ok to continue processing.
                   1243: #      0       - Program should exit.
                   1244: #  Side effects:
                   1245: #      Reply information is sent to the client.
                   1246: sub ping_handler {
                   1247:     my ($cmd, $tail, $client) = @_;
                   1248:     Debug("$cmd $tail $client .. $currenthostid:");
                   1249:    
1.387     albertel 1250:     Reply( $client,\$currenthostid,"$cmd:$tail");
1.214     foxr     1251:    
                   1252:     return 1;
                   1253: }
                   1254: &register_handler("ping", \&ping_handler, 0, 1, 1);       # Ping unencoded, client or manager.
                   1255: 
1.216     foxr     1256: #++
1.215     foxr     1257: #
                   1258: # Handles pong requests.  Pong replies with our current host id, and
                   1259: #                         the results of a ping sent to us via our lonc.
                   1260: #
                   1261: # Parameters:
                   1262: #      $cmd    - the actual keyword that invoked us.
                   1263: #      $tail   - the tail of the request that invoked us.
                   1264: #      $replyfd- File descriptor connected to the client
                   1265: #  Implicit Inputs:
                   1266: #      $currenthostid - Global variable that carries the name of the host we are
                   1267: #                       connected to.
                   1268: #  Returns:
                   1269: #      1       - Ok to continue processing.
                   1270: #      0       - Program should exit.
                   1271: #  Side effects:
                   1272: #      Reply information is sent to the client.
                   1273: sub pong_handler {
                   1274:     my ($cmd, $tail, $replyfd) = @_;
                   1275: 
1.365     albertel 1276:     my $reply=&Apache::lonnet::reply("ping",$clientname);
1.215     foxr     1277:     &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail"); 
                   1278:     return 1;
                   1279: }
                   1280: &register_handler("pong", \&pong_handler, 0, 1, 1);       # Pong unencoded, client or manager
                   1281: 
1.216     foxr     1282: #++
                   1283: #      Called to establish an encrypted session key with the remote client.
                   1284: #      Note that with secure lond, in most cases this function is never
                   1285: #      invoked.  Instead, the secure session key is established either
                   1286: #      via a local file that's locked down tight and only lives for a short
                   1287: #      time, or via an ssl tunnel...and is generated from a bunch-o-random
                   1288: #      bits from /dev/urandom, rather than the predictable pattern used by
                   1289: #      by this sub.  This sub is only used in the old-style insecure
                   1290: #      key negotiation.
                   1291: # Parameters:
                   1292: #      $cmd    - the actual keyword that invoked us.
                   1293: #      $tail   - the tail of the request that invoked us.
                   1294: #      $replyfd- File descriptor connected to the client
                   1295: #  Implicit Inputs:
                   1296: #      $currenthostid - Global variable that carries the name of the host
                   1297: #                       known as.
1.448     raeburn  1298: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.216     foxr     1299: #  Returns:
                   1300: #      1       - Ok to continue processing.
                   1301: #      0       - Program should exit.
                   1302: #  Implicit Outputs:
                   1303: #      Reply information is sent to the client.
                   1304: #      $cipher is set with a reference to a new IDEA encryption object.
                   1305: #
                   1306: sub establish_key_handler {
                   1307:     my ($cmd, $tail, $replyfd) = @_;
                   1308: 
                   1309:     my $buildkey=time.$$.int(rand 100000);
                   1310:     $buildkey=~tr/1-6/A-F/;
                   1311:     $buildkey=int(rand 100000).$buildkey.int(rand 100000);
                   1312:     my $key=$currenthostid.$clientname;
                   1313:     $key=~tr/a-z/A-Z/;
                   1314:     $key=~tr/G-P/0-9/;
                   1315:     $key=~tr/Q-Z/0-9/;
                   1316:     $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
                   1317:     $key=substr($key,0,32);
                   1318:     my $cipherkey=pack("H32",$key);
                   1319:     $cipher=new IDEA $cipherkey;
1.387     albertel 1320:     &Reply($replyfd, \$buildkey, "$cmd:$tail"); 
1.216     foxr     1321:    
                   1322:     return 1;
                   1323: 
                   1324: }
                   1325: &register_handler("ekey", \&establish_key_handler, 0, 1,1);
                   1326: 
1.217     foxr     1327: #     Handler for the load command.  Returns the current system load average
                   1328: #     to the requestor.
                   1329: #
                   1330: # Parameters:
                   1331: #      $cmd    - the actual keyword that invoked us.
                   1332: #      $tail   - the tail of the request that invoked us.
                   1333: #      $replyfd- File descriptor connected to the client
                   1334: #  Implicit Inputs:
                   1335: #      $currenthostid - Global variable that carries the name of the host
                   1336: #                       known as.
1.448     raeburn  1337: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1338: #  Returns:
                   1339: #      1       - Ok to continue processing.
                   1340: #      0       - Program should exit.
                   1341: #  Side effects:
                   1342: #      Reply information is sent to the client.
                   1343: sub load_handler {
                   1344:     my ($cmd, $tail, $replyfd) = @_;
                   1345: 
1.463     foxr     1346: 
                   1347: 
1.217     foxr     1348:    # Get the load average from /proc/loadavg and calculate it as a percentage of
                   1349:    # the allowed load limit as set by the perl global variable lonLoadLim
                   1350: 
                   1351:     my $loadavg;
                   1352:     my $loadfile=IO::File->new('/proc/loadavg');
                   1353:    
                   1354:     $loadavg=<$loadfile>;
                   1355:     $loadavg =~ s/\s.*//g;                      # Extract the first field only.
                   1356:    
                   1357:     my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
                   1358: 
1.387     albertel 1359:     &Reply( $replyfd, \$loadpercent, "$cmd:$tail");
1.217     foxr     1360:    
                   1361:     return 1;
                   1362: }
1.263     albertel 1363: &register_handler("load", \&load_handler, 0, 1, 0);
1.217     foxr     1364: 
                   1365: #
                   1366: #   Process the userload request.  This sub returns to the client the current
                   1367: #  user load average.  It can be invoked either by clients or managers.
                   1368: #
                   1369: # Parameters:
                   1370: #      $cmd    - the actual keyword that invoked us.
                   1371: #      $tail   - the tail of the request that invoked us.
                   1372: #      $replyfd- File descriptor connected to the client
                   1373: #  Implicit Inputs:
                   1374: #      $currenthostid - Global variable that carries the name of the host
                   1375: #                       known as.
1.448     raeburn  1376: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1377: #  Returns:
                   1378: #      1       - Ok to continue processing.
                   1379: #      0       - Program should exit
                   1380: # Implicit inputs:
                   1381: #     whatever the userload() function requires.
                   1382: #  Implicit outputs:
                   1383: #     the reply is written to the client.
                   1384: #
                   1385: sub user_load_handler {
                   1386:     my ($cmd, $tail, $replyfd) = @_;
                   1387: 
1.365     albertel 1388:     my $userloadpercent=&Apache::lonnet::userload();
1.387     albertel 1389:     &Reply($replyfd, \$userloadpercent, "$cmd:$tail");
1.217     foxr     1390:     
                   1391:     return 1;
                   1392: }
1.263     albertel 1393: &register_handler("userload", \&user_load_handler, 0, 1, 0);
1.217     foxr     1394: 
1.218     foxr     1395: #   Process a request for the authorization type of a user:
                   1396: #   (userauth).
                   1397: #
                   1398: # Parameters:
                   1399: #      $cmd    - the actual keyword that invoked us.
                   1400: #      $tail   - the tail of the request that invoked us.
                   1401: #      $replyfd- File descriptor connected to the client
                   1402: #  Returns:
                   1403: #      1       - Ok to continue processing.
                   1404: #      0       - Program should exit
                   1405: # Implicit outputs:
                   1406: #    The user authorization type is written to the client.
                   1407: #
                   1408: sub user_authorization_type {
                   1409:     my ($cmd, $tail, $replyfd) = @_;
                   1410:    
                   1411:     my $userinput = "$cmd:$tail";
                   1412:    
                   1413:     #  Pull the domain and username out of the command tail.
1.222     foxr     1414:     # and call get_auth_type to determine the authentication type.
1.218     foxr     1415:    
                   1416:     my ($udom,$uname)=split(/:/,$tail);
1.222     foxr     1417:     my $result = &get_auth_type($udom, $uname);
1.218     foxr     1418:     if($result eq "nouser") {
                   1419: 	&Failure( $replyfd, "unknown_user\n", $userinput);
                   1420:     } else {
                   1421: 	#
1.222     foxr     1422: 	# We only want to pass the second field from get_auth_type
1.218     foxr     1423: 	# for ^krb.. otherwise we'll be handing out the encrypted
                   1424: 	# password for internals e.g.
                   1425: 	#
                   1426: 	my ($type,$otherinfo) = split(/:/,$result);
                   1427: 	if($type =~ /^krb/) {
                   1428: 	    $type = $result;
1.269     raeburn  1429: 	} else {
                   1430:             $type .= ':';
                   1431:         }
1.387     albertel 1432: 	&Reply( $replyfd, \$type, $userinput);
1.218     foxr     1433:     }
                   1434:   
                   1435:     return 1;
                   1436: }
                   1437: &register_handler("currentauth", \&user_authorization_type, 1, 1, 0);
                   1438: 
                   1439: #   Process a request by a manager to push a hosts or domain table 
                   1440: #   to us.  We pick apart the command and pass it on to the subs
                   1441: #   that already exist to do this.
                   1442: #
                   1443: # Parameters:
                   1444: #      $cmd    - the actual keyword that invoked us.
                   1445: #      $tail   - the tail of the request that invoked us.
                   1446: #      $client - File descriptor connected to the client
                   1447: #  Returns:
                   1448: #      1       - Ok to continue processing.
                   1449: #      0       - Program should exit
                   1450: # Implicit Output:
                   1451: #    a reply is written to the client.
                   1452: sub push_file_handler {
                   1453:     my ($cmd, $tail, $client) = @_;
1.412     foxr     1454:     &Debug("In push file handler");
1.218     foxr     1455:     my $userinput = "$cmd:$tail";
                   1456: 
                   1457:     # At this time we only know that the IP of our partner is a valid manager
                   1458:     # the code below is a hook to do further authentication (e.g. to resolve
                   1459:     # spoofing).
                   1460: 
                   1461:     my $cert = &GetCertificate($userinput);
1.412     foxr     1462:     if(&ValidManager($cert)) {
                   1463: 	&Debug("Valid manager: $client");
1.218     foxr     1464: 
                   1465: 	# Now presumably we have the bona fides of both the peer host and the
                   1466: 	# process making the request.
                   1467:       
                   1468: 	my $reply = &PushFile($userinput);
1.387     albertel 1469: 	&Reply($client, \$reply, $userinput);
1.218     foxr     1470: 
                   1471:     } else {
1.412     foxr     1472: 	&logthis("push_file_handler $client is not valid");
1.218     foxr     1473: 	&Failure( $client, "refused\n", $userinput);
                   1474:     } 
1.219     foxr     1475:     return 1;
1.218     foxr     1476: }
                   1477: &register_handler("pushfile", \&push_file_handler, 1, 0, 1);
                   1478: 
1.399     raeburn  1479: # The du_handler routine should be considered obsolete and is retained
                   1480: # for communication with legacy servers.  Please see the du2_handler.
1.243     banghart 1481: #
1.399     raeburn  1482: #   du  - list the disk usage of a directory recursively. 
1.243     banghart 1483: #    
                   1484: #   note: stolen code from the ls file handler
                   1485: #   under construction by Rick Banghart 
                   1486: #    .
                   1487: # Parameters:
                   1488: #    $cmd        - The command that dispatched us (du).
                   1489: #    $ududir     - The directory path to list... I'm not sure what this
                   1490: #                  is relative as things like ls:. return e.g.
                   1491: #                  no_such_dir.
                   1492: #    $client     - Socket open on the client.
                   1493: # Returns:
                   1494: #     1 - indicating that the daemon should not disconnect.
                   1495: # Side Effects:
                   1496: #   The reply is written to  $client.
                   1497: #
                   1498: sub du_handler {
                   1499:     my ($cmd, $ududir, $client) = @_;
1.339     albertel 1500:     ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
1.251     foxr     1501:     my $userinput = "$cmd:$ududir";
                   1502: 
1.245     albertel 1503:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
                   1504: 	&Failure($client,"refused\n","$cmd:$ududir");
                   1505: 	return 1;
                   1506:     }
1.249     foxr     1507:     #  Since $ududir could have some nasties in it,
                   1508:     #  we will require that ududir is a valid
                   1509:     #  directory.  Just in case someone tries to
                   1510:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1511:     #  etc.
                   1512:     #
                   1513:     if (-d $ududir) {
1.292     albertel 1514: 	my $total_size=0;
                   1515: 	my $code=sub { 
                   1516: 	    if ($_=~/\.\d+\./) { return;} 
                   1517: 	    if ($_=~/\.meta$/) { return;}
1.362     albertel 1518: 	    if (-d $_)         { return;}
1.292     albertel 1519: 	    $total_size+=(stat($_))[7];
                   1520: 	};
1.295     raeburn  1521: 	chdir($ududir);
1.292     albertel 1522: 	find($code,$ududir);
                   1523: 	$total_size=int($total_size/1024);
1.387     albertel 1524: 	&Reply($client,\$total_size,"$cmd:$ududir");
1.249     foxr     1525:     } else {
1.251     foxr     1526: 	&Failure($client, "bad_directory:$ududir\n","$cmd:$ududir"); 
1.249     foxr     1527:     }
1.243     banghart 1528:     return 1;
                   1529: }
                   1530: &register_handler("du", \&du_handler, 0, 1, 0);
1.218     foxr     1531: 
1.399     raeburn  1532: # Please also see the du_handler, which is obsoleted by du2. 
                   1533: # du2_handler differs from du_handler in that required path to directory
                   1534: # provided by &propath() is prepended in the handler instead of on the 
                   1535: # client side.
1.239     foxr     1536: #
1.399     raeburn  1537: #   du2  - list the disk usage of a directory recursively.
                   1538: #
                   1539: # Parameters:
                   1540: #    $cmd        - The command that dispatched us (du).
                   1541: #    $tail       - The tail of the request that invoked us.
                   1542: #                  $tail is a : separated list of the following:
                   1543: #                   - $ududir - directory path to list (before prepending)
                   1544: #                   - $getpropath = 1 if &propath() should prepend
                   1545: #                   - $uname - username to use for &propath or user dir
                   1546: #                   - $udom - domain to use for &propath or user dir
                   1547: #                   All are escaped.
                   1548: #    $client     - Socket open on the client.
                   1549: # Returns:
                   1550: #     1 - indicating that the daemon should not disconnect.
                   1551: # Side Effects:
                   1552: #   The reply is written to $client.
                   1553: #
                   1554: 
                   1555: sub du2_handler {
                   1556:     my ($cmd, $tail, $client) = @_;
                   1557:     my ($ududir,$getpropath,$uname,$udom) = map { &unescape($_) } (split(/:/, $tail));
                   1558:     my $userinput = "$cmd:$tail";
                   1559:     if (($ududir=~/\.\./) || (($ududir!~m|^/home/httpd/|) && (!$getpropath))) {
                   1560:         &Failure($client,"refused\n","$cmd:$tail");
                   1561:         return 1;
                   1562:     }
                   1563:     if ($getpropath) {
                   1564:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1565:             $ududir = &propath($udom,$uname).'/'.$ududir;
                   1566:         } else {
                   1567:             &Failure($client,"refused\n","$cmd:$tail");
                   1568:             return 1;
                   1569:         }
                   1570:     }
                   1571:     #  Since $ududir could have some nasties in it,
                   1572:     #  we will require that ududir is a valid
                   1573:     #  directory.  Just in case someone tries to
                   1574:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1575:     #  etc.
                   1576:     #
                   1577:     if (-d $ududir) {
                   1578:         my $total_size=0;
                   1579:         my $code=sub {
                   1580:             if ($_=~/\.\d+\./) { return;}
                   1581:             if ($_=~/\.meta$/) { return;}
                   1582:             if (-d $_)         { return;}
                   1583:             $total_size+=(stat($_))[7];
                   1584:         };
                   1585:         chdir($ududir);
                   1586:         find($code,$ududir);
                   1587:         $total_size=int($total_size/1024);
                   1588:         &Reply($client,\$total_size,"$cmd:$ududir");
                   1589:     } else {
                   1590:         &Failure($client, "bad_directory:$ududir\n","$cmd:$tail");
                   1591:     }
                   1592:     return 1;
                   1593: }
                   1594: &register_handler("du2", \&du2_handler, 0, 1, 0);
                   1595: 
                   1596: #
                   1597: # The ls_handler routine should be considered obsolete and is retained
                   1598: # for communication with legacy servers.  Please see the ls3_handler.
1.280     matthew  1599: #
1.239     foxr     1600: #   ls  - list the contents of a directory.  For each file in the
                   1601: #    selected directory the filename followed by the full output of
                   1602: #    the stat function is returned.  The returned info for each
                   1603: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1604: #
                   1605: #    If the requested path contains /../ or is:
                   1606: #
                   1607: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1608: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1609: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1610: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
                   1611: #    or is:
                   1612: #
1.538     raeburn  1613: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1614: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1615: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1616: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529     raeburn  1617: #
                   1618: #    the response will be "refused".
                   1619: #
1.239     foxr     1620: # Parameters:
                   1621: #    $cmd        - The command that dispatched us (ls).
                   1622: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1623: #                  is relative as things like ls:. return e.g.
                   1624: #                  no_such_dir.
                   1625: #    $client     - Socket open on the client.
                   1626: # Returns:
                   1627: #     1 - indicating that the daemon should not disconnect.
                   1628: # Side Effects:
                   1629: #   The reply is written to  $client.
                   1630: #
                   1631: sub ls_handler {
1.280     matthew  1632:     # obsoleted by ls2_handler
1.239     foxr     1633:     my ($cmd, $ulsdir, $client) = @_;
                   1634: 
                   1635:     my $userinput = "$cmd:$ulsdir";
                   1636: 
                   1637:     my $obs;
                   1638:     my $rights;
                   1639:     my $ulsout='';
                   1640:     my $ulsfn;
1.529     raeburn  1641:     if ($ulsdir =~m{/\.\./}) {
                   1642:         &Failure($client,"refused\n",$userinput);
                   1643:         return 1;
                   1644:     }
1.239     foxr     1645:     if (-e $ulsdir) {
                   1646: 	if(-d $ulsdir) {
1.539     raeburn  1647:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1648:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529     raeburn  1649:                 &Failure($client,"refused\n",$userinput);
                   1650:                 return 1;
                   1651:             }
1.239     foxr     1652: 	    if (opendir(LSDIR,$ulsdir)) {
                   1653: 		while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1654: 		    undef($obs);
                   1655: 		    undef($rights); 
1.239     foxr     1656: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1657: 		    #We do some obsolete checking here
                   1658: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1659: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1660: 			my @obsolete=<FILE>;
                   1661: 			foreach my $obsolete (@obsolete) {
1.301     www      1662: 			    if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.239     foxr     1663: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
                   1664: 			}
                   1665: 		    }
                   1666: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
                   1667: 		    if($obs eq '1') { $ulsout.="&1"; }
                   1668: 		    else { $ulsout.="&0"; }
                   1669: 		    if($rights eq '1') { $ulsout.="&1:"; }
                   1670: 		    else { $ulsout.="&0:"; }
                   1671: 		}
                   1672: 		closedir(LSDIR);
                   1673: 	    }
                   1674: 	} else {
1.539     raeburn  1675:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1676:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529     raeburn  1677:                 &Failure($client,"refused\n",$userinput);
                   1678:                 return 1;
                   1679:             }
1.239     foxr     1680: 	    my @ulsstats=stat($ulsdir);
                   1681: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1682: 	}
                   1683:     } else {
                   1684: 	$ulsout='no_such_dir';
                   1685:     }
                   1686:     if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1687:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.239     foxr     1688:     
                   1689:     return 1;
                   1690: 
                   1691: }
                   1692: &register_handler("ls", \&ls_handler, 0, 1, 0);
                   1693: 
1.399     raeburn  1694: # The ls2_handler routine should be considered obsolete and is retained
                   1695: # for communication with legacy servers.  Please see the ls3_handler.
                   1696: # Please also see the ls_handler, which was itself obsoleted by ls2.
1.280     matthew  1697: # ls2_handler differs from ls_handler in that it escapes its return 
                   1698: # values before concatenating them together with ':'s.
                   1699: #
                   1700: #   ls2  - list the contents of a directory.  For each file in the
                   1701: #    selected directory the filename followed by the full output of
                   1702: #    the stat function is returned.  The returned info for each
                   1703: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1704: #
                   1705: #    If the requested path contains /../ or is:
                   1706: #
                   1707: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1708: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1709: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1710: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
                   1711: #    or is:
                   1712: #
1.538     raeburn  1713: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1714: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1715: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1716: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529     raeburn  1717: #
                   1718: #    the response will be "refused".
                   1719: #
1.280     matthew  1720: # Parameters:
                   1721: #    $cmd        - The command that dispatched us (ls).
                   1722: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1723: #                  is relative as things like ls:. return e.g.
                   1724: #                  no_such_dir.
                   1725: #    $client     - Socket open on the client.
                   1726: # Returns:
                   1727: #     1 - indicating that the daemon should not disconnect.
                   1728: # Side Effects:
                   1729: #   The reply is written to  $client.
                   1730: #
                   1731: sub ls2_handler {
                   1732:     my ($cmd, $ulsdir, $client) = @_;
                   1733: 
                   1734:     my $userinput = "$cmd:$ulsdir";
                   1735: 
                   1736:     my $obs;
                   1737:     my $rights;
                   1738:     my $ulsout='';
                   1739:     my $ulsfn;
1.529     raeburn  1740:     if ($ulsdir =~m{/\.\./}) {
                   1741:         &Failure($client,"refused\n",$userinput);
                   1742:         return 1;
                   1743:     }
1.280     matthew  1744:     if (-e $ulsdir) {
                   1745:         if(-d $ulsdir) {
1.539     raeburn  1746:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1747:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529     raeburn  1748:                 &Failure($client,"refused\n","$userinput");
                   1749:                 return 1;
                   1750:             }
1.280     matthew  1751:             if (opendir(LSDIR,$ulsdir)) {
                   1752:                 while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1753:                     undef($obs);
                   1754: 		    undef($rights); 
1.280     matthew  1755:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1756:                     #We do some obsolete checking here
                   1757:                     if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1758:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1759:                         my @obsolete=<FILE>;
                   1760:                         foreach my $obsolete (@obsolete) {
1.301     www      1761:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.280     matthew  1762:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1763:                                 $rights = 1;
                   1764:                             }
                   1765:                         }
                   1766:                     }
                   1767:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1768:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1769:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1770:                     $ulsout.= &escape($tmp).':';
                   1771:                 }
                   1772:                 closedir(LSDIR);
                   1773:             }
                   1774:         } else {
1.539     raeburn  1775:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1776:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529     raeburn  1777:                 &Failure($client,"refused\n",$userinput);
                   1778:                 return 1;
                   1779:             }
1.280     matthew  1780:             my @ulsstats=stat($ulsdir);
                   1781:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1782:         }
                   1783:     } else {
                   1784:         $ulsout='no_such_dir';
                   1785:    }
                   1786:    if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1787:    &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.280     matthew  1788:    return 1;
                   1789: }
                   1790: &register_handler("ls2", \&ls2_handler, 0, 1, 0);
1.399     raeburn  1791: #
                   1792: #   ls3  - list the contents of a directory.  For each file in the
                   1793: #    selected directory the filename followed by the full output of
                   1794: #    the stat function is returned.  The returned info for each
                   1795: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1796: #
                   1797: #    If the requested path (after prepending) contains /../ or is:
                   1798: #
                   1799: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1800: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1801: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1802: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
1.539     raeburn  1803: #        (d) /home/httpd/html/priv/<domain> and client is the homeserver
1.529     raeburn  1804: #
1.530     raeburn  1805: #    or is:
1.529     raeburn  1806: #
1.538     raeburn  1807: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1808: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1809: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1810: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
                   1811: #        (d) /home/httpd/html/priv/<domain>/<username>/ and client is the homeserver
1.529     raeburn  1812: #
                   1813: #    the response will be "refused".
                   1814: #
1.399     raeburn  1815: # Parameters:
                   1816: #    $cmd        - The command that dispatched us (ls).
                   1817: #    $tail       - The tail of the request that invoked us.
                   1818: #                  $tail is a : separated list of the following:
                   1819: #                   - $ulsdir - directory path to list (before prepending)
                   1820: #                   - $getpropath = 1 if &propath() should prepend
                   1821: #                   - $getuserdir = 1 if path to user dir in lonUsers should
                   1822: #                                     prepend
                   1823: #                   - $alternate_root - path to prepend
                   1824: #                   - $uname - username to use for &propath or user dir
                   1825: #                   - $udom - domain to use for &propath or user dir
                   1826: #            All of these except $getpropath and &getuserdir are escaped.    
                   1827: #                  no_such_dir.
                   1828: #    $client     - Socket open on the client.
                   1829: # Returns:
                   1830: #     1 - indicating that the daemon should not disconnect.
                   1831: # Side Effects:
                   1832: #   The reply is written to $client.
                   1833: #
                   1834: 
                   1835: sub ls3_handler {
                   1836:     my ($cmd, $tail, $client) = @_;
                   1837:     my $userinput = "$cmd:$tail";
                   1838:     my ($ulsdir,$getpropath,$getuserdir,$alternate_root,$uname,$udom) =
                   1839:         split(/:/,$tail);
                   1840:     if (defined($ulsdir)) {
                   1841:         $ulsdir = &unescape($ulsdir);
                   1842:     }
                   1843:     if (defined($alternate_root)) {
                   1844:         $alternate_root = &unescape($alternate_root);
                   1845:     }
                   1846:     if (defined($uname)) {
                   1847:         $uname = &unescape($uname);
                   1848:     }
                   1849:     if (defined($udom)) {
                   1850:         $udom = &unescape($udom);
                   1851:     }
                   1852: 
                   1853:     my $dir_root = $perlvar{'lonDocRoot'};
1.529     raeburn  1854:     if (($getpropath) || ($getuserdir)) {
1.399     raeburn  1855:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1856:             $dir_root = &propath($udom,$uname);
                   1857:             $dir_root =~ s/\/$//;
                   1858:         } else {
1.529     raeburn  1859:             &Failure($client,"refused\n",$userinput);
1.399     raeburn  1860:             return 1;
                   1861:         }
1.400     raeburn  1862:     } elsif ($alternate_root ne '') {
1.399     raeburn  1863:         $dir_root = $alternate_root;
                   1864:     }
1.408     raeburn  1865:     if (($dir_root ne '') && ($dir_root ne '/')) {
1.400     raeburn  1866:         if ($ulsdir =~ /^\//) {
                   1867:             $ulsdir = $dir_root.$ulsdir;
                   1868:         } else {
                   1869:             $ulsdir = $dir_root.'/'.$ulsdir;
                   1870:         }
1.399     raeburn  1871:     }
1.529     raeburn  1872:     if ($ulsdir =~m{/\.\./}) {
                   1873:         &Failure($client,"refused\n",$userinput);
                   1874:         return 1;
                   1875:     }
                   1876:     my $islocal;
                   1877:     my @machine_ids = &Apache::lonnet::current_machine_ids();
                   1878:     if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   1879:         $islocal = 1;
                   1880:     }
1.399     raeburn  1881:     my $obs;
                   1882:     my $rights;
                   1883:     my $ulsout='';
                   1884:     my $ulsfn;
                   1885:     if (-e $ulsdir) {
                   1886:         if(-d $ulsdir) {
1.529     raeburn  1887:             unless (($getpropath) || ($getuserdir) ||
1.539     raeburn  1888:                     ($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1889:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles}) ||
                   1890:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain}) && ($islocal))) {
1.529     raeburn  1891:                 &Failure($client,"refused\n",$userinput);
                   1892:                 return 1;
                   1893:             }
1.399     raeburn  1894:             if (opendir(LSDIR,$ulsdir)) {
                   1895:                 while ($ulsfn=readdir(LSDIR)) {
                   1896:                     undef($obs);
                   1897:                     undef($rights);
                   1898:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1899:                     #We do some obsolete checking here
                   1900:                     if(-e $ulsdir.'/'.$ulsfn.".meta") {
                   1901:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1902:                         my @obsolete=<FILE>;
                   1903:                         foreach my $obsolete (@obsolete) {
                   1904:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
                   1905:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1906:                                 $rights = 1;
                   1907:                             }
                   1908:                         }
                   1909:                     }
                   1910:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1911:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1912:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1913:                     $ulsout.= &escape($tmp).':';
                   1914:                 }
                   1915:                 closedir(LSDIR);
                   1916:             }
                   1917:         } else {
1.529     raeburn  1918:             unless (($getpropath) || ($getuserdir) ||
1.539     raeburn  1919:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1920:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/}) ||
                   1921:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain/$LONCAPA::match_name/}) && ($islocal))) {
1.529     raeburn  1922:                 &Failure($client,"refused\n",$userinput);
                   1923:                 return 1;
                   1924:             }
1.399     raeburn  1925:             my @ulsstats=stat($ulsdir);
                   1926:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1927:         }
                   1928:     } else {
                   1929:         $ulsout='no_such_dir';
1.400     raeburn  1930:     }
                   1931:     if ($ulsout eq '') { $ulsout='empty'; }
                   1932:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
                   1933:     return 1;
1.399     raeburn  1934: }
                   1935: &register_handler("ls3", \&ls3_handler, 0, 1, 0);
1.280     matthew  1936: 
1.477     raeburn  1937: sub read_lonnet_global {
                   1938:     my ($cmd,$tail,$client) = @_;
                   1939:     my $userinput = "$cmd:$tail";
                   1940:     my $requested = &Apache::lonnet::thaw_unescape($tail);
                   1941:     my $result;
1.480     raeburn  1942:     my %packagevars = (
                   1943:                         spareid => \%Apache::lonnet::spareid,
                   1944:                         perlvar => \%Apache::lonnet::perlvar,
                   1945:                       );
                   1946:     my %limit_to = (
                   1947:                     perlvar => {
1.531     raeburn  1948:                                  lonOtherAuthen  => 1,
                   1949:                                  lonBalancer     => 1,
                   1950:                                  lonVersion      => 1,
                   1951:                                  lonAdmEMail     => 1,
                   1952:                                  lonSupportEMail => 1,  
                   1953:                                  lonSysEMail     => 1,
                   1954:                                  lonHostID       => 1,
                   1955:                                  lonRole         => 1,
                   1956:                                  lonDefDomain    => 1,
                   1957:                                  lonLoadLim      => 1,
                   1958:                                  lonUserLoadLim  => 1,
1.480     raeburn  1959:                                }
                   1960:                   );
1.477     raeburn  1961:     if (ref($requested) eq 'HASH') {
                   1962:         foreach my $what (keys(%{$requested})) {
                   1963:             my $response;
1.480     raeburn  1964:             my $items = {};
                   1965:             if (exists($packagevars{$what})) {
                   1966:                 if (ref($limit_to{$what}) eq 'HASH') {
                   1967:                     foreach my $varname (keys(%{$packagevars{$what}})) {
                   1968:                         if ($limit_to{$what}{$varname}) {
                   1969:                             $items->{$varname} = $packagevars{$what}{$varname};
                   1970:                         }
                   1971:                     }
                   1972:                 } else {
                   1973:                     $items = $packagevars{$what};
1.477     raeburn  1974:                 }
1.480     raeburn  1975:                 if ($what eq 'perlvar') {
                   1976:                     if (!exists($packagevars{$what}{'lonBalancer'})) {
                   1977:                         if ($dist =~ /^(centos|rhes|fedora|scientific)/) {
                   1978:                             my $othervarref=LONCAPA::Configuration::read_conf('httpd.conf');
                   1979:                             if (ref($othervarref) eq 'HASH') {
                   1980:                                 $items->{'lonBalancer'} = $othervarref->{'lonBalancer'};
                   1981:                             }
                   1982:                         }
                   1983:                     }
1.477     raeburn  1984:                 }
1.480     raeburn  1985:                 $response = &Apache::lonnet::freeze_escape($items);
1.477     raeburn  1986:             }
1.478     raeburn  1987:             $result .= &escape($what).'='.$response.'&';
1.477     raeburn  1988:         }
                   1989:     }
                   1990:     $result =~ s/\&$//;
                   1991:     &Reply($client,\$result,$userinput);
                   1992:     return 1;
                   1993: }
                   1994: &register_handler("readlonnetglobal", \&read_lonnet_global, 0, 1, 0);
                   1995: 
1.479     raeburn  1996: sub server_devalidatecache_handler {
                   1997:     my ($cmd,$tail,$client) = @_;
                   1998:     my $userinput = "$cmd:$tail";
1.503     raeburn  1999:     my $items = &unescape($tail);
                   2000:     my @cached = split(/\&/,$items);
                   2001:     foreach my $key (@cached) {
                   2002:         if ($key =~ /:/) {
                   2003:             my ($name,$id) = map { &unescape($_); } split(/:/,$key);
                   2004:             &Apache::lonnet::devalidate_cache_new($name,$id);
                   2005:         }
                   2006:     }
1.479     raeburn  2007:     my $result = 'ok';
                   2008:     &Reply($client,\$result,$userinput);
                   2009:     return 1;
                   2010: }
1.481     raeburn  2011: &register_handler("devalidatecache", \&server_devalidatecache_handler, 0, 1, 0);
1.479     raeburn  2012: 
1.410     raeburn  2013: sub server_timezone_handler {
                   2014:     my ($cmd,$tail,$client) = @_;
                   2015:     my $userinput = "$cmd:$tail";
                   2016:     my $timezone;
                   2017:     my $clockfile = '/etc/sysconfig/clock'; # Fedora/CentOS/SuSE
                   2018:     my $tzfile = '/etc/timezone'; # Debian/Ubuntu
                   2019:     if (-e $clockfile) {
                   2020:         if (open(my $fh,"<$clockfile")) {
                   2021:             while (<$fh>) {
                   2022:                 next if (/^[\#\s]/);
                   2023:                 if (/^(?:TIME)?ZONE\s*=\s*['"]?\s*([\w\/]+)/) {
                   2024:                     $timezone = $1;
                   2025:                     last;
                   2026:                 }
                   2027:             }
                   2028:             close($fh);
                   2029:         }
                   2030:     } elsif (-e $tzfile) {
                   2031:         if (open(my $fh,"<$tzfile")) {
                   2032:             $timezone = <$fh>;
                   2033:             close($fh);
                   2034:             chomp($timezone);
                   2035:             if ($timezone =~ m{^Etc/(\w+)$}) {
                   2036:                 $timezone = $1;
                   2037:             }
                   2038:         }
                   2039:     }
                   2040:     &Reply($client,\$timezone,$userinput); # This supports debug logging.
                   2041:     return 1;
                   2042: }
                   2043: &register_handler("servertimezone", \&server_timezone_handler, 0, 1, 0);
                   2044: 
1.413     raeburn  2045: sub server_loncaparev_handler {
                   2046:     my ($cmd,$tail,$client) = @_;
                   2047:     my $userinput = "$cmd:$tail";
                   2048:     &Reply($client,\$perlvar{'lonVersion'},$userinput);
                   2049:     return 1;
                   2050: }
                   2051: &register_handler("serverloncaparev", \&server_loncaparev_handler, 0, 1, 0);
                   2052: 
1.448     raeburn  2053: sub server_homeID_handler {
                   2054:     my ($cmd,$tail,$client) = @_;
                   2055:     my $userinput = "$cmd:$tail";
                   2056:     &Reply($client,\$perlvar{'lonHostID'},$userinput);
                   2057:     return 1;
                   2058: }
                   2059: &register_handler("serverhomeID", \&server_homeID_handler, 0, 1, 0);
                   2060: 
1.471     raeburn  2061: sub server_distarch_handler {
                   2062:     my ($cmd,$tail,$client) = @_;
                   2063:     my $userinput = "$cmd:$tail";
                   2064:     my $reply = &distro_and_arch();
                   2065:     &Reply($client,\$reply,$userinput);
                   2066:     return 1;
                   2067: }
                   2068: &register_handler("serverdistarch", \&server_distarch_handler, 0, 1, 0);
                   2069: 
1.523     raeburn  2070: sub server_certs_handler {
                   2071:     my ($cmd,$tail,$client) = @_;
                   2072:     my $userinput = "$cmd:$tail";
                   2073:     my $result;
                   2074:     my $result = &LONCAPA::Lond::server_certs(\%perlvar);
                   2075:     &Reply($client,\$result,$userinput);
                   2076:     return;
                   2077: }
                   2078: &register_handler("servercerts", \&server_certs_handler, 0, 1, 0);
                   2079: 
1.218     foxr     2080: #   Process a reinit request.  Reinit requests that either
                   2081: #   lonc or lond be reinitialized so that an updated 
                   2082: #   host.tab or domain.tab can be processed.
                   2083: #
                   2084: # Parameters:
                   2085: #      $cmd    - the actual keyword that invoked us.
                   2086: #      $tail   - the tail of the request that invoked us.
                   2087: #      $client - File descriptor connected to the client
                   2088: #  Returns:
                   2089: #      1       - Ok to continue processing.
                   2090: #      0       - Program should exit
                   2091: #  Implicit output:
                   2092: #     a reply is sent to the client.
                   2093: #
                   2094: sub reinit_process_handler {
                   2095:     my ($cmd, $tail, $client) = @_;
                   2096:    
                   2097:     my $userinput = "$cmd:$tail";
                   2098:    
                   2099:     my $cert = &GetCertificate($userinput);
                   2100:     if(&ValidManager($cert)) {
                   2101: 	chomp($userinput);
                   2102: 	my $reply = &ReinitProcess($userinput);
1.387     albertel 2103: 	&Reply( $client,  \$reply, $userinput);
1.218     foxr     2104:     } else {
                   2105: 	&Failure( $client, "refused\n", $userinput);
                   2106:     }
                   2107:     return 1;
                   2108: }
                   2109: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
                   2110: 
                   2111: #  Process the editing script for a table edit operation.
                   2112: #  the editing operation must be encrypted and requested by
                   2113: #  a manager host.
                   2114: #
                   2115: # Parameters:
                   2116: #      $cmd    - the actual keyword that invoked us.
                   2117: #      $tail   - the tail of the request that invoked us.
                   2118: #      $client - File descriptor connected to the client
                   2119: #  Returns:
                   2120: #      1       - Ok to continue processing.
                   2121: #      0       - Program should exit
                   2122: #  Implicit output:
                   2123: #     a reply is sent to the client.
                   2124: #
                   2125: sub edit_table_handler {
                   2126:     my ($command, $tail, $client) = @_;
                   2127:    
                   2128:     my $userinput = "$command:$tail";
                   2129: 
                   2130:     my $cert = &GetCertificate($userinput);
                   2131:     if(&ValidManager($cert)) {
                   2132: 	my($filetype, $script) = split(/:/, $tail);
                   2133: 	if (($filetype eq "hosts") || 
                   2134: 	    ($filetype eq "domain")) {
                   2135: 	    if($script ne "") {
                   2136: 		&Reply($client,              # BUGBUG - EditFile
                   2137: 		      &EditFile($userinput), #   could fail.
                   2138: 		      $userinput);
                   2139: 	    } else {
                   2140: 		&Failure($client,"refused\n",$userinput);
                   2141: 	    }
                   2142: 	} else {
                   2143: 	    &Failure($client,"refused\n",$userinput);
                   2144: 	}
                   2145:     } else {
                   2146: 	&Failure($client,"refused\n",$userinput);
                   2147:     }
                   2148:     return 1;
                   2149: }
1.263     albertel 2150: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
1.218     foxr     2151: 
1.220     foxr     2152: #
                   2153: #   Authenticate a user against the LonCAPA authentication
                   2154: #   database.  Note that there are several authentication
                   2155: #   possibilities:
                   2156: #   - unix     - The user can be authenticated against the unix
                   2157: #                password file.
                   2158: #   - internal - The user can be authenticated against a purely 
                   2159: #                internal per user password file.
                   2160: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
                   2161: #                ticket granting authority.
                   2162: #   - user     - The person tailoring LonCAPA can supply a user authentication
                   2163: #                mechanism that is per system.
                   2164: #
                   2165: # Parameters:
                   2166: #    $cmd      - The command that got us here.
                   2167: #    $tail     - Tail of the command (remaining parameters).
                   2168: #    $client   - File descriptor connected to client.
                   2169: # Returns
                   2170: #     0        - Requested to exit, caller should shut down.
                   2171: #     1        - Continue processing.
                   2172: # Implicit inputs:
                   2173: #    The authentication systems describe above have their own forms of implicit
                   2174: #    input into the authentication process that are described above.
                   2175: #
                   2176: sub authenticate_handler {
                   2177:     my ($cmd, $tail, $client) = @_;
                   2178: 
                   2179:     
                   2180:     #  Regenerate the full input line 
                   2181:     
                   2182:     my $userinput  = $cmd.":".$tail;
                   2183:     
                   2184:     #  udom    - User's domain.
                   2185:     #  uname   - Username.
                   2186:     #  upass   - User's password.
1.396     raeburn  2187:     #  checkdefauth - Pass to validate_user() to try authentication
                   2188:     #                 with default auth type(s) if no user account.
1.447     raeburn  2189:     #  clientcancheckhost - Passed by clients with functionality in lonauth.pm
                   2190:     #                       to check if session can be hosted.
1.220     foxr     2191:     
1.447     raeburn  2192:     my ($udom, $uname, $upass, $checkdefauth, $clientcancheckhost)=split(/:/,$tail);
1.399     raeburn  2193:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass,  checkdefauth = $checkdefauth");
1.220     foxr     2194:     chomp($upass);
                   2195:     $upass=&unescape($upass);
                   2196: 
1.396     raeburn  2197:     my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
1.220     foxr     2198:     if($pwdcorrect) {
1.447     raeburn  2199:         my $canhost = 1;
                   2200:         unless ($clientcancheckhost) {
1.448     raeburn  2201:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   2202:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.452     raeburn  2203:             my @intdoms;
                   2204:             my $internet_names = &Apache::lonnet::get_internet_names($clientname);
                   2205:             if (ref($internet_names) eq 'ARRAY') {
                   2206:                 @intdoms = @{$internet_names};
                   2207:             }
1.448     raeburn  2208:             unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
1.447     raeburn  2209:                 my ($remote,$hosted);
                   2210:                 my $remotesession = &get_usersession_config($udom,'remotesession');
                   2211:                 if (ref($remotesession) eq 'HASH') {
1.525     raeburn  2212:                     $remote = $remotesession->{'remote'};
1.447     raeburn  2213:                 }
1.448     raeburn  2214:                 my $hostedsession = &get_usersession_config($clienthomedom,'hostedsession');
1.447     raeburn  2215:                 if (ref($hostedsession) eq 'HASH') {
                   2216:                     $hosted = $hostedsession->{'hosted'};
                   2217:                 }
1.448     raeburn  2218:                 $canhost = &Apache::lonnet::can_host_session($udom,$clientname,
1.492     droeschl 2219:                                                              $clientversion,
1.447     raeburn  2220:                                                              $remote,$hosted);
                   2221:             }
                   2222:         }
                   2223:         if ($canhost) {               
                   2224:             &Reply( $client, "authorized\n", $userinput);
                   2225:         } else {
                   2226:             &Reply( $client, "not_allowed_to_host\n", $userinput);
                   2227:         }
1.220     foxr     2228: 	#
                   2229: 	#  Bad credentials: Failed to authorize
                   2230: 	#
                   2231:     } else {
                   2232: 	&Failure( $client, "non_authorized\n", $userinput);
                   2233:     }
                   2234: 
                   2235:     return 1;
                   2236: }
1.263     albertel 2237: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
1.214     foxr     2238: 
1.222     foxr     2239: #
                   2240: #   Change a user's password.  Note that this function is complicated by
                   2241: #   the fact that a user may be authenticated in more than one way:
                   2242: #   At present, we are not able to change the password for all types of
                   2243: #   authentication methods.  Only for:
                   2244: #      unix    - unix password or shadow passoword style authentication.
                   2245: #      local   - Locally written authentication mechanism.
                   2246: #   For now, kerb4 and kerb5 password changes are not supported and result
                   2247: #   in an error.
                   2248: # FUTURE WORK:
                   2249: #    Support kerberos passwd changes?
                   2250: # Parameters:
                   2251: #    $cmd      - The command that got us here.
                   2252: #    $tail     - Tail of the command (remaining parameters).
                   2253: #    $client   - File descriptor connected to client.
                   2254: # Returns
                   2255: #     0        - Requested to exit, caller should shut down.
                   2256: #     1        - Continue processing.
                   2257: # Implicit inputs:
                   2258: #    The authentication systems describe above have their own forms of implicit
                   2259: #    input into the authentication process that are described above.
                   2260: sub change_password_handler {
                   2261:     my ($cmd, $tail, $client) = @_;
                   2262: 
                   2263:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
                   2264: 
                   2265:     #
                   2266:     #  udom  - user's domain.
                   2267:     #  uname - Username.
                   2268:     #  upass - Current password.
                   2269:     #  npass - New password.
1.346     raeburn  2270:     #  context - Context in which this was called 
                   2271:     #            (preferences or reset_by_email).
1.428     raeburn  2272:     #  lonhost - HostID of server where request originated 
1.222     foxr     2273:    
1.428     raeburn  2274:     my ($udom,$uname,$upass,$npass,$context,$lonhost)=split(/:/,$tail);
1.222     foxr     2275: 
                   2276:     $upass=&unescape($upass);
                   2277:     $npass=&unescape($npass);
                   2278:     &Debug("Trying to change password for $uname");
                   2279: 
                   2280:     # First require that the user can be authenticated with their
1.346     raeburn  2281:     # old password unless context was 'reset_by_email':
                   2282:     
1.428     raeburn  2283:     my ($validated,$failure);
1.346     raeburn  2284:     if ($context eq 'reset_by_email') {
1.428     raeburn  2285:         if ($lonhost eq '') {
                   2286:             $failure = 'invalid_client';
                   2287:         } else {
                   2288:             $validated = 1;
                   2289:         }
1.346     raeburn  2290:     } else {
                   2291:         $validated = &validate_user($udom, $uname, $upass);
                   2292:     }
1.222     foxr     2293:     if($validated) {
                   2294: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
                   2295: 	
                   2296: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
                   2297: 	if ($howpwd eq 'internal') {
                   2298: 	    &Debug("internal auth");
1.518     raeburn  2299:             my $ncpass = &hash_passwd($udom,$npass);
1.222     foxr     2300: 	    if(&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
1.428     raeburn  2301: 		my $msg="Result of password change for $uname: pwchange_success";
                   2302:                 if ($lonhost) {
                   2303:                     $msg .= " - request originated from: $lonhost";
                   2304:                 }
                   2305:                 &logthis($msg);
1.518     raeburn  2306:                 &update_passwd_history($uname,$udom,$howpwd,$context);
1.222     foxr     2307: 		&Reply($client, "ok\n", $userinput);
                   2308: 	    } else {
                   2309: 		&logthis("Unable to open $uname passwd "               
                   2310: 			 ."to change password");
                   2311: 		&Failure( $client, "non_authorized\n",$userinput);
                   2312: 	    }
1.346     raeburn  2313: 	} elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
1.287     foxr     2314: 	    my $result = &change_unix_password($uname, $npass);
1.518     raeburn  2315:             if ($result eq 'ok') {
                   2316:                 &update_passwd_history($uname,$udom,$howpwd,$context);
                   2317:              }
1.222     foxr     2318: 	    &logthis("Result of password change for $uname: ".
1.287     foxr     2319: 		     $result);
1.387     albertel 2320: 	    &Reply($client, \$result, $userinput);
1.222     foxr     2321: 	} else {
                   2322: 	    # this just means that the current password mode is not
                   2323: 	    # one we know how to change (e.g the kerberos auth modes or
                   2324: 	    # locally written auth handler).
                   2325: 	    #
                   2326: 	    &Failure( $client, "auth_mode_error\n", $userinput);
                   2327: 	}  
                   2328: 	
1.224     foxr     2329:     } else {
1.428     raeburn  2330: 	if ($failure eq '') {
                   2331: 	    $failure = 'non_authorized';
                   2332: 	}
                   2333: 	&Failure( $client, "$failure\n", $userinput);
1.222     foxr     2334:     }
                   2335: 
                   2336:     return 1;
                   2337: }
1.263     albertel 2338: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
1.222     foxr     2339: 
1.518     raeburn  2340: sub hash_passwd {
                   2341:     my ($domain,$plainpass,@rest) = @_;
                   2342:     my ($salt,$cost);
                   2343:     if (@rest) {
                   2344:         $cost = $rest[0];
                   2345:         # salt is first 22 characters, base-64 encoded by bcrypt
                   2346:         my $plainsalt = substr($rest[1],0,22);
                   2347:         $salt = Crypt::Eksblowfish::Bcrypt::de_base64($plainsalt);
                   2348:     } else {
1.533     raeburn  2349:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2350:         my $defaultcost = $domdefaults{'intauth_cost'};
1.518     raeburn  2351:         if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   2352:             $cost = 10;
                   2353:         } else {
                   2354:             $cost = $defaultcost;
                   2355:         }
                   2356:         # Generate random 16-octet base64 salt
                   2357:         $salt = "";
                   2358:         $salt .= pack("C", int rand(256)) for 1..16;
                   2359:     }
                   2360:     my $hash = &Crypt::Eksblowfish::Bcrypt::bcrypt_hash({
                   2361:         key_nul => 1,
                   2362:         cost    => $cost,
                   2363:         salt    => $salt,
                   2364:     }, Digest::SHA::sha512(Encode::encode('UTF-8',$plainpass)));
                   2365: 
                   2366:     my $result = join("!", "", "bcrypt", sprintf("%02d",$cost),
                   2367:                 &Crypt::Eksblowfish::Bcrypt::en_base64($salt).
                   2368:                 &Crypt::Eksblowfish::Bcrypt::en_base64($hash));
                   2369:     return $result;
                   2370: }
                   2371: 
1.225     foxr     2372: #
                   2373: #   Create a new user.  User in this case means a lon-capa user.
                   2374: #   The user must either already exist in some authentication realm
                   2375: #   like kerberos or the /etc/passwd.  If not, a user completely local to
                   2376: #   this loncapa system is created.
                   2377: #
                   2378: # Parameters:
                   2379: #    $cmd      - The command that got us here.
                   2380: #    $tail     - Tail of the command (remaining parameters).
                   2381: #    $client   - File descriptor connected to client.
                   2382: # Returns
                   2383: #     0        - Requested to exit, caller should shut down.
                   2384: #     1        - Continue processing.
                   2385: # Implicit inputs:
                   2386: #    The authentication systems describe above have their own forms of implicit
                   2387: #    input into the authentication process that are described above.
                   2388: sub add_user_handler {
                   2389: 
                   2390:     my ($cmd, $tail, $client) = @_;
                   2391: 
                   2392: 
                   2393:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2394:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
                   2395: 
                   2396:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
                   2397: 
                   2398: 
                   2399:     if($udom eq $currentdomainid) { # Reject new users for other domains...
                   2400: 	
                   2401: 	my $oldumask=umask(0077);
                   2402: 	chomp($npass);
                   2403: 	$npass=&unescape($npass);
                   2404: 	my $passfilename  = &password_path($udom, $uname);
                   2405: 	&Debug("Password file created will be:".$passfilename);
                   2406: 	if (-e $passfilename) {
                   2407: 	    &Failure( $client, "already_exists\n", $userinput);
                   2408: 	} else {
                   2409: 	    my $fperror='';
1.264     albertel 2410: 	    if (!&mkpath($passfilename)) {
                   2411: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
                   2412: 		    ."makeuser";
1.225     foxr     2413: 	    }
                   2414: 	    unless ($fperror) {
1.518     raeburn  2415: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2416:                                              $passfilename,'makeuser');
1.390     raeburn  2417: 		&Reply($client,\$result, $userinput);     #BUGBUG - could be fail
1.225     foxr     2418: 	    } else {
1.387     albertel 2419: 		&Failure($client, \$fperror, $userinput);
1.225     foxr     2420: 	    }
                   2421: 	}
                   2422: 	umask($oldumask);
                   2423:     }  else {
                   2424: 	&Failure($client, "not_right_domain\n",
                   2425: 		$userinput);	# Even if we are multihomed.
                   2426:     
                   2427:     }
                   2428:     return 1;
                   2429: 
                   2430: }
                   2431: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
                   2432: 
                   2433: #
                   2434: #   Change the authentication method of a user.  Note that this may
                   2435: #   also implicitly change the user's password if, for example, the user is
                   2436: #   joining an existing authentication realm.  Known authentication realms at
                   2437: #   this time are:
                   2438: #    internal   - Purely internal password file (only loncapa knows this user)
                   2439: #    local      - Institutionally written authentication module.
                   2440: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
                   2441: #    kerb4      - kerberos version 4
                   2442: #    kerb5      - kerberos version 5
                   2443: #
                   2444: # Parameters:
                   2445: #    $cmd      - The command that got us here.
                   2446: #    $tail     - Tail of the command (remaining parameters).
                   2447: #    $client   - File descriptor connected to client.
                   2448: # Returns
                   2449: #     0        - Requested to exit, caller should shut down.
                   2450: #     1        - Continue processing.
                   2451: # Implicit inputs:
                   2452: #    The authentication systems describe above have their own forms of implicit
                   2453: #    input into the authentication process that are described above.
1.287     foxr     2454: # NOTE:
                   2455: #   This is also used to change the authentication credential values (e.g. passwd).
                   2456: #   
1.225     foxr     2457: #
                   2458: sub change_authentication_handler {
                   2459: 
                   2460:     my ($cmd, $tail, $client) = @_;
                   2461:    
                   2462:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
                   2463: 
                   2464:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2465:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
                   2466:     if ($udom ne $currentdomainid) {
                   2467: 	&Failure( $client, "not_right_domain\n", $client);
                   2468:     } else {
                   2469: 	
                   2470: 	chomp($npass);
                   2471: 	
                   2472: 	$npass=&unescape($npass);
1.261     foxr     2473: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
1.225     foxr     2474: 	my $passfilename = &password_path($udom, $uname);
                   2475: 	if ($passfilename) {	# Not allowed to create a new user!!
1.287     foxr     2476: 	    # If just changing the unix passwd. need to arrange to run
1.502     raeburn  2477: 	    # passwd since otherwise make_passwd_file will fail as 
                   2478: 	    # creation of unix authenticated users is no longer supported
                   2479:             # except from the command line, when running make_domain_coordinator.pl
1.287     foxr     2480: 
                   2481: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
                   2482: 		my $result = &change_unix_password($uname, $npass);
                   2483: 		&logthis("Result of password change for $uname: ".$result);
                   2484: 		if ($result eq "ok") {
1.518     raeburn  2485:                     &update_passwd_history($uname,$udom,$umode,'changeuserauth'); 
1.390     raeburn  2486: 		    &Reply($client, \$result);
1.288     albertel 2487: 		} else {
1.387     albertel 2488: 		    &Failure($client, \$result);
1.287     foxr     2489: 		}
1.288     albertel 2490: 	    } else {
1.518     raeburn  2491: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2492:                                              $passfilename,'changeuserauth');
1.287     foxr     2493: 		#
                   2494: 		#  If the current auth mode is internal, and the old auth mode was
                   2495: 		#  unix, or krb*,  and the user is an author for this domain,
                   2496: 		#  re-run manage_permissions for that role in order to be able
                   2497: 		#  to take ownership of the construction space back to www:www
                   2498: 		#
1.502     raeburn  2499: 
                   2500: 
1.387     albertel 2501: 		&Reply($client, \$result, $userinput);
1.261     foxr     2502: 	    }
                   2503: 	       
                   2504: 
1.225     foxr     2505: 	} else {	       
1.251     foxr     2506: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
1.225     foxr     2507: 	}
                   2508:     }
                   2509:     return 1;
                   2510: }
                   2511: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
                   2512: 
1.518     raeburn  2513: sub update_passwd_history {
                   2514:     my ($uname,$udom,$umode,$context) = @_;
                   2515:     my $proname=&propath($udom,$uname);
                   2516:     my $now = time;
                   2517:     if (open(my $fh,">>$proname/passwd.log")) {
                   2518:         print $fh "$now:$umode:$context\n";
                   2519:         close($fh);
                   2520:     }
                   2521:     return;
                   2522: }
                   2523: 
1.225     foxr     2524: #
                   2525: #   Determines if this is the home server for a user.  The home server
                   2526: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
                   2527: #   to do is determine if this file exists.
                   2528: #
                   2529: # Parameters:
                   2530: #    $cmd      - The command that got us here.
                   2531: #    $tail     - Tail of the command (remaining parameters).
                   2532: #    $client   - File descriptor connected to client.
                   2533: # Returns
                   2534: #     0        - Requested to exit, caller should shut down.
                   2535: #     1        - Continue processing.
                   2536: # Implicit inputs:
                   2537: #    The authentication systems describe above have their own forms of implicit
                   2538: #    input into the authentication process that are described above.
                   2539: #
                   2540: sub is_home_handler {
                   2541:     my ($cmd, $tail, $client) = @_;
                   2542:    
                   2543:     my $userinput  = "$cmd:$tail";
                   2544:    
                   2545:     my ($udom,$uname)=split(/:/,$tail);
                   2546:     chomp($uname);
                   2547:     my $passfile = &password_filename($udom, $uname);
                   2548:     if($passfile) {
                   2549: 	&Reply( $client, "found\n", $userinput);
                   2550:     } else {
                   2551: 	&Failure($client, "not_found\n", $userinput);
                   2552:     }
                   2553:     return 1;
                   2554: }
                   2555: &register_handler("home", \&is_home_handler, 0,1,0);
                   2556: 
                   2557: #
1.434     www      2558: #   Process an update request for a resource.
                   2559: #   A resource has been modified that we hold a subscription to.
1.225     foxr     2560: #   If the resource is not local, then we must update, or at least invalidate our
                   2561: #   cached copy of the resource. 
                   2562: # Parameters:
                   2563: #    $cmd      - The command that got us here.
                   2564: #    $tail     - Tail of the command (remaining parameters).
                   2565: #    $client   - File descriptor connected to client.
                   2566: # Returns
                   2567: #     0        - Requested to exit, caller should shut down.
                   2568: #     1        - Continue processing.
                   2569: # Implicit inputs:
                   2570: #    The authentication systems describe above have their own forms of implicit
                   2571: #    input into the authentication process that are described above.
                   2572: #
                   2573: sub update_resource_handler {
                   2574: 
                   2575:     my ($cmd, $tail, $client) = @_;
                   2576:    
                   2577:     my $userinput = "$cmd:$tail";
                   2578:    
                   2579:     my $fname= $tail;		# This allows interactive testing
                   2580: 
                   2581: 
                   2582:     my $ownership=ishome($fname);
                   2583:     if ($ownership eq 'not_owner') {
                   2584: 	if (-e $fname) {
1.434     www      2585:             # Delete preview file, if exists
                   2586:             unlink("$fname.tmp");
                   2587:             # Get usage stats
1.225     foxr     2588: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
                   2589: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
                   2590: 	    my $now=time;
                   2591: 	    my $since=$now-$atime;
1.434     www      2592:             # If the file has not been used within lonExpire seconds,
                   2593:             # unsubscribe from it and delete local copy
1.225     foxr     2594: 	    if ($since>$perlvar{'lonExpire'}) {
1.365     albertel 2595: 		my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
1.308     albertel 2596: 		&devalidate_meta_cache($fname);
1.225     foxr     2597: 		unlink("$fname");
1.334     albertel 2598: 		unlink("$fname.meta");
1.225     foxr     2599: 	    } else {
1.434     www      2600:             # Yes, this is in active use. Get a fresh copy. Since it might be in
                   2601:             # very active use and huge (like a movie), copy it to "in.transfer" filename first.
1.225     foxr     2602: 		my $transname="$fname.in.transfer";
1.365     albertel 2603: 		my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
1.225     foxr     2604: 		my $response;
1.537     raeburn  2605: # FIXME: cannot replicate files that take more than two minutes to transfer -- needs checking now 1200s timeout used
                   2606: # for LWP request.
                   2607: 		my $request=new HTTP::Request('GET',"$remoteurl");
                   2608:                 $response=&LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,0,1);
1.225     foxr     2609: 		if ($response->is_error()) {
1.541   ! raeburn  2610:                     my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
        !          2611:                     &devalidate_meta_cache($fname);
        !          2612:                     if (-e $transname) {
        !          2613:                         unlink($transname);
        !          2614:                     }
        !          2615:                     unlink($fname);
1.225     foxr     2616: 		    my $message=$response->status_line;
                   2617: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2618: 		} else {
                   2619: 		    if ($remoteurl!~/\.meta$/) {
1.537     raeburn  2620: 			my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2621:                         my $mresponse = &LONCAPA::LWPReq::makerequest($clientname,$mrequest,$fname.'.meta',\%perlvar,120,0,1);
                   2622: 			if ($mresponse->is_error()) {
                   2623: 			    unlink($fname.'.meta');
1.225     foxr     2624: 			}
                   2625: 		    }
1.434     www      2626:                     # we successfully transfered, copy file over to real name
1.225     foxr     2627: 		    rename($transname,$fname);
1.308     albertel 2628: 		    &devalidate_meta_cache($fname);
1.225     foxr     2629: 		}
                   2630: 	    }
                   2631: 	    &Reply( $client, "ok\n", $userinput);
                   2632: 	} else {
                   2633: 	    &Failure($client, "not_found\n", $userinput);
                   2634: 	}
                   2635:     } else {
                   2636: 	&Failure($client, "rejected\n", $userinput);
                   2637:     }
                   2638:     return 1;
                   2639: }
                   2640: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
                   2641: 
1.308     albertel 2642: sub devalidate_meta_cache {
                   2643:     my ($url) = @_;
                   2644:     use Cache::Memcached;
                   2645:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.365     albertel 2646:     $url = &Apache::lonnet::declutter($url);
1.308     albertel 2647:     $url =~ s-\.meta$--;
                   2648:     my $id = &escape('meta:'.$url);
                   2649:     $memcache->delete($id);
                   2650: }
                   2651: 
1.225     foxr     2652: #
1.226     foxr     2653: #   Fetch a user file from a remote server to the user's home directory
                   2654: #   userfiles subdir.
1.225     foxr     2655: # Parameters:
                   2656: #    $cmd      - The command that got us here.
                   2657: #    $tail     - Tail of the command (remaining parameters).
                   2658: #    $client   - File descriptor connected to client.
                   2659: # Returns
                   2660: #     0        - Requested to exit, caller should shut down.
                   2661: #     1        - Continue processing.
                   2662: #
                   2663: sub fetch_user_file_handler {
                   2664: 
                   2665:     my ($cmd, $tail, $client) = @_;
                   2666: 
                   2667:     my $userinput = "$cmd:$tail";
                   2668:     my $fname           = $tail;
1.232     foxr     2669:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1.225     foxr     2670:     my $udir=&propath($udom,$uname).'/userfiles';
                   2671:     unless (-e $udir) {
                   2672: 	mkdir($udir,0770); 
                   2673:     }
1.232     foxr     2674:     Debug("fetch user file for $fname");
1.225     foxr     2675:     if (-e $udir) {
                   2676: 	$ufile=~s/^[\.\~]+//;
1.232     foxr     2677: 
                   2678: 	# IF necessary, create the path right down to the file.
                   2679: 	# Note that any regular files in the way of this path are
                   2680: 	# wiped out to deal with some earlier folly of mine.
                   2681: 
1.267     raeburn  2682: 	if (!&mkpath($udir.'/'.$ufile)) {
1.264     albertel 2683: 	    &Failure($client, "unable_to_create\n", $userinput);	    
1.232     foxr     2684: 	}
                   2685: 
1.225     foxr     2686: 	my $destname=$udir.'/'.$ufile;
                   2687: 	my $transname=$udir.'/'.$ufile.'.in.transit';
1.476     raeburn  2688:         my $clientprotocol=$Apache::lonnet::protocol{$clientname};
                   2689:         $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.486     raeburn  2690: 	my $clienthost = &Apache::lonnet::hostname($clientname);
                   2691: 	my $remoteurl=$clientprotocol.'://'.$clienthost.'/userfiles/'.$fname;
1.225     foxr     2692: 	my $response;
1.232     foxr     2693: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
1.537     raeburn  2694: 	my $request=new HTTP::Request('GET',"$remoteurl");
                   2695:         my $verifycert = 1;
                   2696:         my @machine_ids = &Apache::lonnet::current_machine_ids();
                   2697:         if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   2698:             $verifycert = 0;
                   2699:         }
                   2700:         $response = &LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,$verifycert);
1.225     foxr     2701: 	if ($response->is_error()) {
                   2702: 	    unlink($transname);
                   2703: 	    my $message=$response->status_line;
                   2704: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2705: 	    &Failure($client, "failed\n", $userinput);
                   2706: 	} else {
1.232     foxr     2707: 	    Debug("Renaming $transname to $destname");
1.225     foxr     2708: 	    if (!rename($transname,$destname)) {
                   2709: 		&logthis("Unable to move $transname to $destname");
                   2710: 		unlink($transname);
                   2711: 		&Failure($client, "failed\n", $userinput);
                   2712: 	    } else {
1.495     raeburn  2713:                 if ($fname =~ /^default.+\.(page|sequence)$/) {
                   2714:                     my ($major,$minor) = split(/\./,$clientversion);
                   2715:                     if (($major < 2) || ($major == 2 && $minor < 11)) {
                   2716:                         my $now = time;
                   2717:                         &Apache::lonnet::do_cache_new('crschange',$udom.'_'.$uname,$now,600);
                   2718:                         my $key = &escape('internal.contentchange');
                   2719:                         my $what = "$key=$now";
                   2720:                         my $hashref = &tie_user_hash($udom,$uname,'environment',
                   2721:                                                      &GDBM_WRCREAT(),"P",$what);
                   2722:                         if ($hashref) {
                   2723:                             $hashref->{$key}=$now;
                   2724:                             if (!&untie_user_hash($hashref)) {
                   2725:                                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   2726:                                          "when updating internal.contentchange");
                   2727:                             }
                   2728:                         }
                   2729:                     }
                   2730:                 }
1.225     foxr     2731: 		&Reply($client, "ok\n", $userinput);
                   2732: 	    }
                   2733: 	}   
                   2734:     } else {
                   2735: 	&Failure($client, "not_home\n", $userinput);
                   2736:     }
                   2737:     return 1;
                   2738: }
                   2739: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
                   2740: 
1.226     foxr     2741: #
                   2742: #   Remove a file from a user's home directory userfiles subdirectory.
                   2743: # Parameters:
                   2744: #    cmd   - the Lond request keyword that got us here.
                   2745: #    tail  - the part of the command past the keyword.
                   2746: #    client- File descriptor connected with the client.
                   2747: #
                   2748: # Returns:
                   2749: #    1    - Continue processing.
                   2750: sub remove_user_file_handler {
                   2751:     my ($cmd, $tail, $client) = @_;
                   2752: 
                   2753:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2754: 
                   2755:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2756:     if ($ufile =~m|/\.\./|) {
                   2757: 	# any files paths with /../ in them refuse 
                   2758: 	# to deal with
                   2759: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2760:     } else {
                   2761: 	my $udir = &propath($udom,$uname);
                   2762: 	if (-e $udir) {
                   2763: 	    my $file=$udir.'/userfiles/'.$ufile;
                   2764: 	    if (-e $file) {
1.253     foxr     2765: 		#
                   2766: 		#   If the file is a regular file unlink is fine...
1.520     raeburn  2767: 		#   However it's possible the client wants a dir 
                   2768: 		#   removed, in which case rmdir is more appropriate.
                   2769: 		#   Note: rmdir will only remove an empty directory.
1.253     foxr     2770: 		#
1.240     banghart 2771: 	        if (-f $file){
1.241     albertel 2772: 		    unlink($file);
1.520     raeburn  2773:                     # for html files remove the associated .bak file 
                   2774:                     # which may have been created by the editor.
                   2775:                     if ($ufile =~ m{^((docs|supplemental)/(?:\d+|default)/\d+(?:|/.+)/)[^/]+\.x?html?$}i) {
                   2776:                         my $path = $1;
                   2777:                         if (-e $file.'.bak') {
                   2778:                             unlink($file.'.bak');
                   2779:                         }
                   2780:                     }
1.241     albertel 2781: 		} elsif(-d $file) {
                   2782: 		    rmdir($file);
1.240     banghart 2783: 		}
1.226     foxr     2784: 		if (-e $file) {
1.253     foxr     2785: 		    #  File is still there after we deleted it ?!?
                   2786: 
1.226     foxr     2787: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2788: 		} else {
                   2789: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2790: 		}
                   2791: 	    } else {
                   2792: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2793: 	    }
                   2794: 	} else {
                   2795: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2796: 	}
                   2797:     }
                   2798:     return 1;
                   2799: }
                   2800: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
                   2801: 
1.236     albertel 2802: #
                   2803: #   make a directory in a user's home directory userfiles subdirectory.
                   2804: # Parameters:
                   2805: #    cmd   - the Lond request keyword that got us here.
                   2806: #    tail  - the part of the command past the keyword.
                   2807: #    client- File descriptor connected with the client.
                   2808: #
                   2809: # Returns:
                   2810: #    1    - Continue processing.
                   2811: sub mkdir_user_file_handler {
                   2812:     my ($cmd, $tail, $client) = @_;
                   2813: 
                   2814:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2815:     $dir=&unescape($dir);
                   2816:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2817:     if ($ufile =~m|/\.\./|) {
                   2818: 	# any files paths with /../ in them refuse 
                   2819: 	# to deal with
                   2820: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2821:     } else {
                   2822: 	my $udir = &propath($udom,$uname);
                   2823: 	if (-e $udir) {
1.264     albertel 2824: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
                   2825: 	    if (!&mkpath($newdir)) {
                   2826: 		&Failure($client, "failed\n", "$cmd:$tail");
1.236     albertel 2827: 	    }
1.264     albertel 2828: 	    &Reply($client, "ok\n", "$cmd:$tail");
1.236     albertel 2829: 	} else {
                   2830: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2831: 	}
                   2832:     }
                   2833:     return 1;
                   2834: }
                   2835: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
                   2836: 
1.237     albertel 2837: #
                   2838: #   rename a file in a user's home directory userfiles subdirectory.
                   2839: # Parameters:
                   2840: #    cmd   - the Lond request keyword that got us here.
                   2841: #    tail  - the part of the command past the keyword.
                   2842: #    client- File descriptor connected with the client.
                   2843: #
                   2844: # Returns:
                   2845: #    1    - Continue processing.
                   2846: sub rename_user_file_handler {
                   2847:     my ($cmd, $tail, $client) = @_;
                   2848: 
                   2849:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
                   2850:     $old=&unescape($old);
                   2851:     $new=&unescape($new);
                   2852:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
                   2853: 	# any files paths with /../ in them refuse to deal with
                   2854: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2855:     } else {
                   2856: 	my $udir = &propath($udom,$uname);
                   2857: 	if (-e $udir) {
                   2858: 	    my $oldfile=$udir.'/userfiles/'.$old;
                   2859: 	    my $newfile=$udir.'/userfiles/'.$new;
                   2860: 	    if (-e $newfile) {
                   2861: 		&Failure($client, "exists\n", "$cmd:$tail");
                   2862: 	    } elsif (! -e $oldfile) {
                   2863: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2864: 	    } else {
                   2865: 		if (!rename($oldfile,$newfile)) {
                   2866: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2867: 		} else {
                   2868: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2869: 		}
                   2870: 	    }
                   2871: 	} else {
                   2872: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2873: 	}
                   2874:     }
                   2875:     return 1;
                   2876: }
                   2877: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
                   2878: 
1.227     foxr     2879: #
1.382     albertel 2880: #  Checks if the specified user has an active session on the server
                   2881: #  return ok if so, not_found if not
                   2882: #
                   2883: # Parameters:
                   2884: #   cmd      - The request keyword that dispatched to tus.
                   2885: #   tail     - The tail of the request (colon separated parameters).
                   2886: #   client   - Filehandle open on the client.
                   2887: # Return:
                   2888: #    1.
                   2889: sub user_has_session_handler {
                   2890:     my ($cmd, $tail, $client) = @_;
                   2891: 
                   2892:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
                   2893:     
                   2894:     opendir(DIR,$perlvar{'lonIDsDir'});
                   2895:     my $filename;
                   2896:     while ($filename=readdir(DIR)) {
                   2897: 	last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
                   2898:     }
                   2899:     if ($filename) {
                   2900: 	&Reply($client, "ok\n", "$cmd:$tail");
                   2901:     } else {
                   2902: 	&Failure($client, "not_found\n", "$cmd:$tail");
                   2903:     }
                   2904:     return 1;
                   2905: 
                   2906: }
                   2907: &register_handler("userhassession", \&user_has_session_handler, 0,1,0);
                   2908: 
                   2909: #
1.263     albertel 2910: #  Authenticate access to a user file by checking that the token the user's 
                   2911: #  passed also exists in their session file
1.227     foxr     2912: #
                   2913: # Parameters:
                   2914: #   cmd      - The request keyword that dispatched to tus.
                   2915: #   tail     - The tail of the request (colon separated parameters).
                   2916: #   client   - Filehandle open on the client.
                   2917: # Return:
                   2918: #    1.
                   2919: sub token_auth_user_file_handler {
                   2920:     my ($cmd, $tail, $client) = @_;
                   2921: 
                   2922:     my ($fname, $session) = split(/:/, $tail);
                   2923:     
                   2924:     chomp($session);
1.393     raeburn  2925:     my $reply="non_auth";
1.343     albertel 2926:     my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
                   2927:     if (open(ENVIN,"$file")) {
1.332     albertel 2928: 	flock(ENVIN,LOCK_SH);
1.343     albertel 2929: 	tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
                   2930: 	if (exists($disk_env{"userfile.$fname"})) {
1.393     raeburn  2931: 	    $reply="ok";
1.343     albertel 2932: 	} else {
                   2933: 	    foreach my $envname (keys(%disk_env)) {
                   2934: 		if ($envname=~ m|^userfile\.\Q$fname\E|) {
1.393     raeburn  2935: 		    $reply="ok";
1.343     albertel 2936: 		    last;
                   2937: 		}
                   2938: 	    }
1.227     foxr     2939: 	}
1.343     albertel 2940: 	untie(%disk_env);
1.227     foxr     2941: 	close(ENVIN);
1.387     albertel 2942: 	&Reply($client, \$reply, "$cmd:$tail");
1.227     foxr     2943:     } else {
                   2944: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
                   2945:     }
                   2946:     return 1;
                   2947: 
                   2948: }
                   2949: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229     foxr     2950: 
                   2951: #
                   2952: #   Unsubscribe from a resource.
                   2953: #
                   2954: # Parameters:
                   2955: #    $cmd      - The command that got us here.
                   2956: #    $tail     - Tail of the command (remaining parameters).
                   2957: #    $client   - File descriptor connected to client.
                   2958: # Returns
                   2959: #     0        - Requested to exit, caller should shut down.
                   2960: #     1        - Continue processing.
                   2961: #
                   2962: sub unsubscribe_handler {
                   2963:     my ($cmd, $tail, $client) = @_;
                   2964: 
                   2965:     my $userinput= "$cmd:$tail";
                   2966:     
                   2967:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
                   2968: 
                   2969:     &Debug("Unsubscribing $fname");
                   2970:     if (-e $fname) {
                   2971: 	&Debug("Exists");
                   2972: 	&Reply($client, &unsub($fname,$clientip), $userinput);
                   2973:     } else {
                   2974: 	&Failure($client, "not_found\n", $userinput);
                   2975:     }
                   2976:     return 1;
                   2977: }
                   2978: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
1.263     albertel 2979: 
1.230     foxr     2980: #   Subscribe to a resource
                   2981: #
                   2982: # Parameters:
                   2983: #    $cmd      - The command that got us here.
                   2984: #    $tail     - Tail of the command (remaining parameters).
                   2985: #    $client   - File descriptor connected to client.
                   2986: # Returns
                   2987: #     0        - Requested to exit, caller should shut down.
                   2988: #     1        - Continue processing.
                   2989: #
                   2990: sub subscribe_handler {
                   2991:     my ($cmd, $tail, $client)= @_;
                   2992: 
                   2993:     my $userinput  = "$cmd:$tail";
                   2994: 
                   2995:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
                   2996: 
                   2997:     return 1;
                   2998: }
                   2999: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
                   3000: 
                   3001: #
1.379     albertel 3002: #   Determine the latest version of a resource (it looks for the highest
                   3003: #   past version and then returns that +1)
1.230     foxr     3004: #
                   3005: # Parameters:
                   3006: #    $cmd      - The command that got us here.
                   3007: #    $tail     - Tail of the command (remaining parameters).
1.379     albertel 3008: #                 (Should consist of an absolute path to a file)
1.230     foxr     3009: #    $client   - File descriptor connected to client.
                   3010: # Returns
                   3011: #     0        - Requested to exit, caller should shut down.
                   3012: #     1        - Continue processing.
                   3013: #
                   3014: sub current_version_handler {
                   3015:     my ($cmd, $tail, $client) = @_;
                   3016: 
                   3017:     my $userinput= "$cmd:$tail";
                   3018:    
                   3019:     my $fname   = $tail;
                   3020:     &Reply( $client, &currentversion($fname)."\n", $userinput);
                   3021:     return 1;
                   3022: 
                   3023: }
                   3024: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
                   3025: 
                   3026: #  Make an entry in a user's activity log.
                   3027: #
                   3028: # Parameters:
                   3029: #    $cmd      - The command that got us here.
                   3030: #    $tail     - Tail of the command (remaining parameters).
                   3031: #    $client   - File descriptor connected to client.
                   3032: # Returns
                   3033: #     0        - Requested to exit, caller should shut down.
                   3034: #     1        - Continue processing.
                   3035: #
                   3036: sub activity_log_handler {
                   3037:     my ($cmd, $tail, $client) = @_;
                   3038: 
                   3039: 
                   3040:     my $userinput= "$cmd:$tail";
                   3041: 
                   3042:     my ($udom,$uname,$what)=split(/:/,$tail);
                   3043:     chomp($what);
                   3044:     my $proname=&propath($udom,$uname);
                   3045:     my $now=time;
                   3046:     my $hfh;
                   3047:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
                   3048: 	print $hfh "$now:$clientname:$what\n";
                   3049: 	&Reply( $client, "ok\n", $userinput); 
                   3050:     } else {
                   3051: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
                   3052: 		 ."while attempting log\n", 
                   3053: 		 $userinput);
                   3054:     }
                   3055: 
                   3056:     return 1;
                   3057: }
1.263     albertel 3058: &register_handler("log", \&activity_log_handler, 0, 1, 0);
1.230     foxr     3059: 
                   3060: #
                   3061: #   Put a namespace entry in a user profile hash.
                   3062: #   My druthers would be for this to be an encrypted interaction too.
                   3063: #   anything that might be an inadvertent covert channel about either
                   3064: #   user authentication or user personal information....
                   3065: #
                   3066: # Parameters:
                   3067: #    $cmd      - The command that got us here.
                   3068: #    $tail     - Tail of the command (remaining parameters).
                   3069: #    $client   - File descriptor connected to client.
                   3070: # Returns
                   3071: #     0        - Requested to exit, caller should shut down.
                   3072: #     1        - Continue processing.
                   3073: #
                   3074: sub put_user_profile_entry {
                   3075:     my ($cmd, $tail, $client)  = @_;
1.229     foxr     3076: 
1.230     foxr     3077:     my $userinput = "$cmd:$tail";
                   3078:     
1.242     raeburn  3079:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
1.230     foxr     3080:     if ($namespace ne 'roles') {
                   3081: 	chomp($what);
                   3082: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3083: 				  &GDBM_WRCREAT(),"P",$what);
                   3084: 	if($hashref) {
                   3085: 	    my @pairs=split(/\&/,$what);
                   3086: 	    foreach my $pair (@pairs) {
                   3087: 		my ($key,$value)=split(/=/,$pair);
                   3088: 		$hashref->{$key}=$value;
                   3089: 	    }
1.311     albertel 3090: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3091: 		&Reply( $client, "ok\n", $userinput);
                   3092: 	    } else {
                   3093: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3094: 			"while attempting put\n", 
                   3095: 			$userinput);
                   3096: 	    }
                   3097: 	} else {
1.316     albertel 3098: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.230     foxr     3099: 		     "while attempting put\n", $userinput);
                   3100: 	}
                   3101:     } else {
                   3102:         &Failure( $client, "refused\n", $userinput);
                   3103:     }
                   3104:     
                   3105:     return 1;
                   3106: }
                   3107: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
                   3108: 
1.283     albertel 3109: #   Put a piece of new data in hash, returns error if entry already exists
                   3110: # Parameters:
                   3111: #    $cmd      - The command that got us here.
                   3112: #    $tail     - Tail of the command (remaining parameters).
                   3113: #    $client   - File descriptor connected to client.
                   3114: # Returns
                   3115: #     0        - Requested to exit, caller should shut down.
                   3116: #     1        - Continue processing.
                   3117: #
                   3118: sub newput_user_profile_entry {
                   3119:     my ($cmd, $tail, $client)  = @_;
                   3120: 
                   3121:     my $userinput = "$cmd:$tail";
                   3122: 
                   3123:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
                   3124:     if ($namespace eq 'roles') {
                   3125:         &Failure( $client, "refused\n", $userinput);
                   3126: 	return 1;
                   3127:     }
                   3128: 
                   3129:     chomp($what);
                   3130: 
                   3131:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3132: 				 &GDBM_WRCREAT(),"N",$what);
                   3133:     if(!$hashref) {
1.316     albertel 3134: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.283     albertel 3135: 		  "while attempting put\n", $userinput);
                   3136: 	return 1;
                   3137:     }
                   3138: 
                   3139:     my @pairs=split(/\&/,$what);
                   3140:     foreach my $pair (@pairs) {
                   3141: 	my ($key,$value)=split(/=/,$pair);
                   3142: 	if (exists($hashref->{$key})) {
1.513     raeburn  3143:             if (!&untie_user_hash($hashref)) {
                   3144:                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   3145:                          "while attempting newput - early out as key exists");
                   3146:             }
                   3147:             &Failure($client, "key_exists: ".$key."\n",$userinput);
                   3148:             return 1;
1.283     albertel 3149: 	}
                   3150:     }
                   3151: 
                   3152:     foreach my $pair (@pairs) {
                   3153: 	my ($key,$value)=split(/=/,$pair);
                   3154: 	$hashref->{$key}=$value;
                   3155:     }
                   3156: 
1.311     albertel 3157:     if (&untie_user_hash($hashref)) {
1.283     albertel 3158: 	&Reply( $client, "ok\n", $userinput);
                   3159:     } else {
                   3160: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3161: 		 "while attempting put\n", 
                   3162: 		 $userinput);
                   3163:     }
                   3164:     return 1;
                   3165: }
                   3166: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
                   3167: 
1.230     foxr     3168: # 
                   3169: #   Increment a profile entry in the user history file.
                   3170: #   The history contains keyword value pairs.  In this case,
                   3171: #   The value itself is a pair of numbers.  The first, the current value
                   3172: #   the second an increment that this function applies to the current
                   3173: #   value.
                   3174: #
                   3175: # Parameters:
                   3176: #    $cmd      - The command that got us here.
                   3177: #    $tail     - Tail of the command (remaining parameters).
                   3178: #    $client   - File descriptor connected to client.
                   3179: # Returns
                   3180: #     0        - Requested to exit, caller should shut down.
                   3181: #     1        - Continue processing.
                   3182: #
                   3183: sub increment_user_value_handler {
                   3184:     my ($cmd, $tail, $client) = @_;
                   3185:     
                   3186:     my $userinput   = "$cmd:$tail";
                   3187:     
                   3188:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
                   3189:     if ($namespace ne 'roles') {
                   3190:         chomp($what);
                   3191: 	my $hashref = &tie_user_hash($udom, $uname,
                   3192: 				     $namespace, &GDBM_WRCREAT(),
                   3193: 				     "P",$what);
                   3194: 	if ($hashref) {
                   3195: 	    my @pairs=split(/\&/,$what);
                   3196: 	    foreach my $pair (@pairs) {
                   3197: 		my ($key,$value)=split(/=/,$pair);
1.284     raeburn  3198:                 $value = &unescape($value);
1.230     foxr     3199: 		# We could check that we have a number...
                   3200: 		if (! defined($value) || $value eq '') {
                   3201: 		    $value = 1;
                   3202: 		}
                   3203: 		$hashref->{$key}+=$value;
1.284     raeburn  3204:                 if ($namespace eq 'nohist_resourcetracker') {
                   3205:                     if ($hashref->{$key} < 0) {
                   3206:                         $hashref->{$key} = 0;
                   3207:                     }
                   3208:                 }
1.230     foxr     3209: 	    }
1.311     albertel 3210: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3211: 		&Reply( $client, "ok\n", $userinput);
                   3212: 	    } else {
                   3213: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3214: 			 "while attempting inc\n", $userinput);
                   3215: 	    }
                   3216: 	} else {
                   3217: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3218: 		     "while attempting inc\n", $userinput);
                   3219: 	}
                   3220:     } else {
                   3221: 	&Failure($client, "refused\n", $userinput);
                   3222:     }
                   3223:     
                   3224:     return 1;
                   3225: }
                   3226: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
                   3227: 
                   3228: #
                   3229: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
                   3230: #   Each 'role' a user has implies a set of permissions.  Adding a new role
                   3231: #   for a person grants the permissions packaged with that role
                   3232: #   to that user when the role is selected.
                   3233: #
                   3234: # Parameters:
                   3235: #    $cmd       - The command string (rolesput).
                   3236: #    $tail      - The remainder of the request line.  For rolesput this
                   3237: #                 consists of a colon separated list that contains:
                   3238: #                 The domain and user that is granting the role (logged).
                   3239: #                 The domain and user that is getting the role.
                   3240: #                 The roles being granted as a set of & separated pairs.
                   3241: #                 each pair a key value pair.
                   3242: #    $client    - File descriptor connected to the client.
                   3243: # Returns:
                   3244: #     0         - If the daemon should exit
                   3245: #     1         - To continue processing.
                   3246: #
                   3247: #
                   3248: sub roles_put_handler {
                   3249:     my ($cmd, $tail, $client) = @_;
                   3250: 
                   3251:     my $userinput  = "$cmd:$tail";
                   3252: 
                   3253:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
                   3254:     
                   3255: 
                   3256:     my $namespace='roles';
                   3257:     chomp($what);
                   3258:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3259: 				 &GDBM_WRCREAT(), "P",
                   3260: 				 "$exedom:$exeuser:$what");
                   3261:     #
                   3262:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
                   3263:     #  handle is open for the minimal amount of time.  Since the flush
                   3264:     #  is done on close this improves the chances the log will be an un-
                   3265:     #  corrupted ordered thing.
                   3266:     if ($hashref) {
1.261     foxr     3267: 	my $pass_entry = &get_auth_type($udom, $uname);
                   3268: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
                   3269: 	$auth_type = $auth_type.":";
1.230     foxr     3270: 	my @pairs=split(/\&/,$what);
                   3271: 	foreach my $pair (@pairs) {
                   3272: 	    my ($key,$value)=split(/=/,$pair);
                   3273: 	    &manage_permissions($key, $udom, $uname,
1.260     foxr     3274: 			       $auth_type);
1.230     foxr     3275: 	    $hashref->{$key}=$value;
                   3276: 	}
1.311     albertel 3277: 	if (&untie_user_hash($hashref)) {
1.230     foxr     3278: 	    &Reply($client, "ok\n", $userinput);
                   3279: 	} else {
                   3280: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3281: 		     "while attempting rolesput\n", $userinput);
                   3282: 	}
                   3283:     } else {
                   3284: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3285: 		 "while attempting rolesput\n", $userinput);
                   3286:     }
                   3287:     return 1;
                   3288: }
                   3289: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
                   3290: 
                   3291: #
1.231     foxr     3292: #   Deletes (removes) a role for a user.   This is equivalent to removing
                   3293: #  a permissions package associated with the role from the user's profile.
                   3294: #
                   3295: # Parameters:
                   3296: #     $cmd                 - The command (rolesdel)
                   3297: #     $tail                - The remainder of the request line. This consists
                   3298: #                             of:
                   3299: #                             The domain and user requesting the change (logged)
                   3300: #                             The domain and user being changed.
                   3301: #                             The roles being revoked.  These are shipped to us
                   3302: #                             as a bunch of & separated role name keywords.
                   3303: #     $client              - The file handle open on the client.
                   3304: # Returns:
                   3305: #     1                    - Continue processing
                   3306: #     0                    - Exit.
                   3307: #
                   3308: sub roles_delete_handler {
                   3309:     my ($cmd, $tail, $client)  = @_;
                   3310: 
                   3311:     my $userinput    = "$cmd:$tail";
                   3312:    
                   3313:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
                   3314:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
                   3315: 	   "what = ".$what);
                   3316:     my $namespace='roles';
                   3317:     chomp($what);
                   3318:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3319: 				 &GDBM_WRCREAT(), "D",
                   3320: 				 "$exedom:$exeuser:$what");
                   3321:     
                   3322:     if ($hashref) {
                   3323: 	my @rolekeys=split(/\&/,$what);
                   3324: 	
                   3325: 	foreach my $key (@rolekeys) {
                   3326: 	    delete $hashref->{$key};
                   3327: 	}
1.315     albertel 3328: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3329: 	    &Reply($client, "ok\n", $userinput);
                   3330: 	} else {
                   3331: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3332: 		     "while attempting rolesdel\n", $userinput);
                   3333: 	}
                   3334:     } else {
                   3335:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3336: 		 "while attempting rolesdel\n", $userinput);
                   3337:     }
                   3338:     
                   3339:     return 1;
                   3340: }
                   3341: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
                   3342: 
                   3343: # Unencrypted get from a user's profile database.  See 
                   3344: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
                   3345: # This function retrieves a keyed item from a specific named database in the
                   3346: # user's directory.
                   3347: #
                   3348: # Parameters:
                   3349: #   $cmd             - Command request keyword (get).
                   3350: #   $tail            - Tail of the command.  This is a colon separated list
                   3351: #                      consisting of the domain and username that uniquely
                   3352: #                      identifies the profile,
                   3353: #                      The 'namespace' which selects the gdbm file to 
                   3354: #                      do the lookup in, 
                   3355: #                      & separated list of keys to lookup.  Note that
                   3356: #                      the values are returned as an & separated list too.
                   3357: #   $client          - File descriptor open on the client.
                   3358: # Returns:
                   3359: #   1       - Continue processing.
                   3360: #   0       - Exit.
                   3361: #
                   3362: sub get_profile_entry {
                   3363:     my ($cmd, $tail, $client) = @_;
                   3364: 
                   3365:     my $userinput= "$cmd:$tail";
                   3366:    
                   3367:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3368:     chomp($what);
1.255     foxr     3369: 
1.390     raeburn  3370: 
1.255     foxr     3371:     my $replystring = read_profile($udom, $uname, $namespace, $what);
                   3372:     my ($first) = split(/:/,$replystring);
                   3373:     if($first ne "error") {
1.387     albertel 3374: 	&Reply($client, \$replystring, $userinput);
1.231     foxr     3375:     } else {
1.255     foxr     3376: 	&Failure($client, $replystring." while attempting get\n", $userinput);
1.231     foxr     3377:     }
                   3378:     return 1;
1.255     foxr     3379: 
                   3380: 
1.231     foxr     3381: }
                   3382: &register_handler("get", \&get_profile_entry, 0,1,0);
                   3383: 
                   3384: #
                   3385: #  Process the encrypted get request.  Note that the request is sent
                   3386: #  in clear, but the reply is encrypted.  This is a small covert channel:
                   3387: #  information about the sensitive keys is given to the snooper.  Just not
                   3388: #  information about the values of the sensitive key.  Hmm if I wanted to
                   3389: #  know these I'd snoop for the egets. Get the profile item names from them
                   3390: #  and then issue a get for them since there's no enforcement of the
                   3391: #  requirement of an encrypted get for particular profile items.  If I
                   3392: #  were re-doing this, I'd force the request to be encrypted as well as the
                   3393: #  reply.  I'd also just enforce encrypted transactions for all gets since
                   3394: #  that would prevent any covert channel snooping.
                   3395: #
                   3396: #  Parameters:
                   3397: #     $cmd               - Command keyword of request (eget).
1.536     raeburn  3398: #     $tail              - Tail of the command.  See GetProfileEntry
                   3399: #                          for more information about this.
1.231     foxr     3400: #     $client            - File open on the client.
                   3401: #  Returns:
                   3402: #     1      - Continue processing
                   3403: #     0      - server should exit.
                   3404: sub get_profile_entry_encrypted {
                   3405:     my ($cmd, $tail, $client) = @_;
                   3406: 
                   3407:     my $userinput = "$cmd:$tail";
                   3408:    
1.339     albertel 3409:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
1.231     foxr     3410:     chomp($what);
1.255     foxr     3411:     my $qresult = read_profile($udom, $uname, $namespace, $what);
                   3412:     my ($first) = split(/:/, $qresult);
                   3413:     if($first ne "error") {
                   3414: 	
                   3415: 	if ($cipher) {
                   3416: 	    my $cmdlength=length($qresult);
                   3417: 	    $qresult.="         ";
                   3418: 	    my $encqresult='';
                   3419: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   3420: 		$encqresult.= unpack("H16", 
                   3421: 				     $cipher->encrypt(substr($qresult,
                   3422: 							     $encidx,
                   3423: 							     8)));
                   3424: 	    }
                   3425: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   3426: 	} else {
1.231     foxr     3427: 		&Failure( $client, "error:no_key\n", $userinput);
                   3428: 	    }
                   3429:     } else {
1.255     foxr     3430: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
                   3431: 
1.231     foxr     3432:     }
                   3433:     
                   3434:     return 1;
                   3435: }
1.255     foxr     3436: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263     albertel 3437: 
1.231     foxr     3438: #
                   3439: #   Deletes a key in a user profile database.
                   3440: #   
                   3441: #   Parameters:
                   3442: #       $cmd                  - Command keyword (del).
                   3443: #       $tail                 - Command tail.  IN this case a colon
                   3444: #                               separated list containing:
                   3445: #                               The domain and user that identifies uniquely
                   3446: #                               the identity of the user.
                   3447: #                               The profile namespace (name of the profile
                   3448: #                               database file).
                   3449: #                               & separated list of keywords to delete.
                   3450: #       $client              - File open on client socket.
                   3451: # Returns:
                   3452: #     1   - Continue processing
                   3453: #     0   - Exit server.
                   3454: #
                   3455: #
                   3456: sub delete_profile_entry {
                   3457:     my ($cmd, $tail, $client) = @_;
                   3458: 
                   3459:     my $userinput = "cmd:$tail";
                   3460: 
                   3461:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3462:     chomp($what);
                   3463:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3464: 				 &GDBM_WRCREAT(),
                   3465: 				 "D",$what);
                   3466:     if ($hashref) {
                   3467:         my @keys=split(/\&/,$what);
                   3468: 	foreach my $key (@keys) {
                   3469: 	    delete($hashref->{$key});
                   3470: 	}
1.315     albertel 3471: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3472: 	    &Reply($client, "ok\n", $userinput);
                   3473: 	} else {
                   3474: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3475: 		    "while attempting del\n", $userinput);
                   3476: 	}
                   3477:     } else {
                   3478: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3479: 		 "while attempting del\n", $userinput);
                   3480:     }
                   3481:     return 1;
                   3482: }
                   3483: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263     albertel 3484: 
1.231     foxr     3485: #
                   3486: #  List the set of keys that are defined in a profile database file.
                   3487: #  A successful reply from this will contain an & separated list of
                   3488: #  the keys. 
                   3489: # Parameters:
                   3490: #     $cmd              - Command request (keys).
                   3491: #     $tail             - Remainder of the request, a colon separated
                   3492: #                         list containing domain/user that identifies the
                   3493: #                         user being queried, and the database namespace
                   3494: #                         (database filename essentially).
                   3495: #     $client           - File open on the client.
                   3496: #  Returns:
                   3497: #    1    - Continue processing.
                   3498: #    0    - Exit the server.
                   3499: #
                   3500: sub get_profile_keys {
                   3501:     my ($cmd, $tail, $client) = @_;
                   3502: 
                   3503:     my $userinput = "$cmd:$tail";
                   3504: 
                   3505:     my ($udom,$uname,$namespace)=split(/:/,$tail);
                   3506:     my $qresult='';
                   3507:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3508: 				  &GDBM_READER());
                   3509:     if ($hashref) {
                   3510: 	foreach my $key (keys %$hashref) {
                   3511: 	    $qresult.="$key&";
                   3512: 	}
1.315     albertel 3513: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3514: 	    $qresult=~s/\&$//;
1.387     albertel 3515: 	    &Reply($client, \$qresult, $userinput);
1.231     foxr     3516: 	} else {
                   3517: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3518: 		    "while attempting keys\n", $userinput);
                   3519: 	}
                   3520:     } else {
                   3521: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3522: 		 "while attempting keys\n", $userinput);
                   3523:     }
                   3524:    
                   3525:     return 1;
                   3526: }
                   3527: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
                   3528: 
                   3529: #
                   3530: #   Dump the contents of a user profile database.
                   3531: #   Note that this constitutes a very large covert channel too since
                   3532: #   the dump will return sensitive information that is not encrypted.
                   3533: #   The naive security assumption is that the session negotiation ensures
                   3534: #   our client is trusted and I don't believe that's assured at present.
                   3535: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
                   3536: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
                   3537: # 
                   3538: #  Parameters:
                   3539: #     $cmd           - The command request keyword (currentdump).
                   3540: #     $tail          - Remainder of the request, consisting of a colon
                   3541: #                      separated list that has the domain/username and
                   3542: #                      the namespace to dump (database file).
                   3543: #     $client        - file open on the remote client.
                   3544: # Returns:
                   3545: #     1    - Continue processing.
                   3546: #     0    - Exit the server.
                   3547: #
                   3548: sub dump_profile_database {
                   3549:     my ($cmd, $tail, $client) = @_;
                   3550: 
1.494     droeschl 3551:     my $res = LONCAPA::Lond::dump_profile_database($tail);
                   3552: 
                   3553:     if ($res =~ /^error:/) {
                   3554:         Failure($client, \$res, "$cmd:$tail");
                   3555:     } else {
                   3556:         Reply($client, \$res, "$cmd:$tail");
                   3557:     }
                   3558: 
                   3559:     return 1;  
                   3560: 
                   3561:     #TODO remove 
1.231     foxr     3562:     my $userinput = "$cmd:$tail";
                   3563:    
                   3564:     my ($udom,$uname,$namespace) = split(/:/,$tail);
                   3565:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3566: 				 &GDBM_READER());
                   3567:     if ($hashref) {
                   3568: 	# Structure of %data:
                   3569: 	# $data{$symb}->{$parameter}=$value;
                   3570: 	# $data{$symb}->{'v.'.$parameter}=$version;
                   3571: 	# since $parameter will be unescaped, we do not
                   3572:  	# have to worry about silly parameter names...
                   3573: 	
                   3574:         my $qresult='';
                   3575: 	my %data = ();                     # A hash of anonymous hashes..
                   3576: 	while (my ($key,$value) = each(%$hashref)) {
                   3577: 	    my ($v,$symb,$param) = split(/:/,$key);
                   3578: 	    next if ($v eq 'version' || $symb eq 'keys');
                   3579: 	    next if (exists($data{$symb}) && 
                   3580: 		     exists($data{$symb}->{$param}) &&
                   3581: 		     $data{$symb}->{'v.'.$param} > $v);
                   3582: 	    $data{$symb}->{$param}=$value;
                   3583: 	    $data{$symb}->{'v.'.$param}=$v;
                   3584: 	}
1.311     albertel 3585: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3586: 	    while (my ($symb,$param_hash) = each(%data)) {
                   3587: 		while(my ($param,$value) = each (%$param_hash)){
                   3588: 		    next if ($param =~ /^v\./);       # Ignore versions...
                   3589: 		    #
                   3590: 		    #   Just dump the symb=value pairs separated by &
                   3591: 		    #
                   3592: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
                   3593: 		}
                   3594: 	    }
                   3595: 	    chop($qresult);
1.387     albertel 3596: 	    &Reply($client , \$qresult, $userinput);
1.231     foxr     3597: 	} else {
                   3598: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3599: 		     "while attempting currentdump\n", $userinput);
                   3600: 	}
                   3601:     } else {
                   3602: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3603: 		"while attempting currentdump\n", $userinput);
                   3604:     }
                   3605: 
                   3606:     return 1;
                   3607: }
                   3608: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
                   3609: 
                   3610: #
                   3611: #   Dump a profile database with an optional regular expression
                   3612: #   to match against the keys.  In this dump, no effort is made
                   3613: #   to separate symb from version information. Presumably the
                   3614: #   databases that are dumped by this command are of a different
                   3615: #   structure.  Need to look at this and improve the documentation of
                   3616: #   both this and the currentdump handler.
                   3617: # Parameters:
                   3618: #    $cmd                     - The command keyword.
                   3619: #    $tail                    - All of the characters after the $cmd:
                   3620: #                               These are expected to be a colon
                   3621: #                               separated list containing:
                   3622: #                               domain/user - identifying the user.
                   3623: #                               namespace   - identifying the database.
                   3624: #                               regexp      - optional regular expression
                   3625: #                                             that is matched against
                   3626: #                                             database keywords to do
                   3627: #                                             selective dumps.
1.488     raeburn  3628: #                               range       - optional range of entries
                   3629: #                                             e.g., 10-20 would return the
                   3630: #                                             10th to 19th items, etc.  
1.231     foxr     3631: #   $client                   - Channel open on the client.
                   3632: # Returns:
                   3633: #    1    - Continue processing.
                   3634: # Side effects:
                   3635: #    response is written to $client.
                   3636: #
                   3637: sub dump_with_regexp {
                   3638:     my ($cmd, $tail, $client) = @_;
                   3639: 
1.494     droeschl 3640:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
1.490     droeschl 3641:     
                   3642:     if ($res =~ /^error:/) {
                   3643:         Failure($client, \$res, "$cmd:$tail");
                   3644:     } else {
                   3645:         Reply($client, \$res, "$cmd:$tail");
                   3646:     }
1.231     foxr     3647: 
                   3648:     return 1;
                   3649: }
                   3650: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
                   3651: 
                   3652: #  Store a set of key=value pairs associated with a versioned name.
                   3653: #
                   3654: #  Parameters:
                   3655: #    $cmd                - Request command keyword.
                   3656: #    $tail               - Tail of the request.  This is a colon
                   3657: #                          separated list containing:
                   3658: #                          domain/user - User and authentication domain.
                   3659: #                          namespace   - Name of the database being modified
                   3660: #                          rid         - Resource keyword to modify.
                   3661: #                          what        - new value associated with rid.
1.512     raeburn  3662: #                          laststore   - (optional) version=timestamp
                   3663: #                                        for most recent transaction for rid
                   3664: #                                        in namespace, when cstore was called
1.231     foxr     3665: #
                   3666: #    $client             - Socket open on the client.
                   3667: #
                   3668: #
                   3669: #  Returns:
                   3670: #      1 (keep on processing).
                   3671: #  Side-Effects:
                   3672: #    Writes to the client
1.512     raeburn  3673: #    Successful storage will cause either 'ok', or, if $laststore was included
                   3674: #    in the tail of the request, and the version number for the last transaction
                   3675: #    is larger than the version in $laststore, delay:$numtrans , where $numtrans
                   3676: #    is the number of store evevnts recorded for rid in namespace since
                   3677: #    lonnet::store() was called by the client.
                   3678: #
1.231     foxr     3679: sub store_handler {
                   3680:     my ($cmd, $tail, $client) = @_;
                   3681:  
                   3682:     my $userinput = "$cmd:$tail";
1.512     raeburn  3683:     chomp($tail);
                   3684:     my ($udom,$uname,$namespace,$rid,$what,$laststore) =split(/:/,$tail);
1.231     foxr     3685:     if ($namespace ne 'roles') {
                   3686: 
                   3687: 	my @pairs=split(/\&/,$what);
                   3688: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
1.268     albertel 3689: 				       &GDBM_WRCREAT(), "S",
1.231     foxr     3690: 				       "$rid:$what");
                   3691: 	if ($hashref) {
                   3692: 	    my $now = time;
1.512     raeburn  3693:             my $numtrans;
                   3694:             if ($laststore) {
                   3695:                 my ($previousversion,$previoustime) = split(/\=/,$laststore);
                   3696:                 my ($lastversion,$lasttime) = (0,0);
                   3697:                 $lastversion = $hashref->{"version:$rid"};
                   3698:                 if ($lastversion) {
                   3699:                     $lasttime = $hashref->{"$lastversion:$rid:timestamp"};
                   3700:                 }
                   3701:                 if (($previousversion) && ($previousversion !~ /\D/)) {
                   3702:                     if (($lastversion > $previousversion) && ($lasttime >= $previoustime)) {
                   3703:                         $numtrans = $lastversion - $previousversion;
                   3704:                     }
                   3705:                 } elsif ($lastversion) {
                   3706:                     $numtrans = $lastversion;
                   3707:                 }
                   3708:                 if ($numtrans) {
                   3709:                     $numtrans =~ s/D//g;
                   3710:                 }
                   3711:             }
1.231     foxr     3712: 	    $hashref->{"version:$rid"}++;
                   3713: 	    my $version=$hashref->{"version:$rid"};
                   3714: 	    my $allkeys=''; 
                   3715: 	    foreach my $pair (@pairs) {
                   3716: 		my ($key,$value)=split(/=/,$pair);
                   3717: 		$allkeys.=$key.':';
                   3718: 		$hashref->{"$version:$rid:$key"}=$value;
                   3719: 	    }
                   3720: 	    $hashref->{"$version:$rid:timestamp"}=$now;
                   3721: 	    $allkeys.='timestamp';
                   3722: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
1.311     albertel 3723: 	    if (&untie_user_hash($hashref)) {
1.512     raeburn  3724:                 my $msg = 'ok';
                   3725:                 if ($numtrans) {
                   3726:                     $msg = 'delay:'.$numtrans;
                   3727:                 }
                   3728: 		&Reply($client, "$msg\n", $userinput);
1.231     foxr     3729: 	    } else {
                   3730: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3731: 			"while attempting store\n", $userinput);
                   3732: 	    }
                   3733: 	} else {
                   3734: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3735: 		     "while attempting store\n", $userinput);
                   3736: 	}
                   3737:     } else {
                   3738: 	&Failure($client, "refused\n", $userinput);
                   3739:     }
                   3740: 
                   3741:     return 1;
                   3742: }
                   3743: &register_handler("store", \&store_handler, 0, 1, 0);
1.263     albertel 3744: 
1.323     albertel 3745: #  Modify a set of key=value pairs associated with a versioned name.
                   3746: #
                   3747: #  Parameters:
                   3748: #    $cmd                - Request command keyword.
                   3749: #    $tail               - Tail of the request.  This is a colon
                   3750: #                          separated list containing:
                   3751: #                          domain/user - User and authentication domain.
                   3752: #                          namespace   - Name of the database being modified
                   3753: #                          rid         - Resource keyword to modify.
                   3754: #                          v           - Version item to modify
                   3755: #                          what        - new value associated with rid.
                   3756: #
                   3757: #    $client             - Socket open on the client.
                   3758: #
                   3759: #
                   3760: #  Returns:
                   3761: #      1 (keep on processing).
                   3762: #  Side-Effects:
                   3763: #    Writes to the client
                   3764: sub putstore_handler {
                   3765:     my ($cmd, $tail, $client) = @_;
                   3766:  
                   3767:     my $userinput = "$cmd:$tail";
                   3768: 
                   3769:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
                   3770:     if ($namespace ne 'roles') {
                   3771: 
                   3772: 	chomp($what);
                   3773: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
                   3774: 				       &GDBM_WRCREAT(), "M",
                   3775: 				       "$rid:$v:$what");
                   3776: 	if ($hashref) {
                   3777: 	    my $now = time;
                   3778: 	    my %data = &hash_extract($what);
                   3779: 	    my @allkeys;
                   3780: 	    while (my($key,$value) = each(%data)) {
                   3781: 		push(@allkeys,$key);
                   3782: 		$hashref->{"$v:$rid:$key"} = $value;
                   3783: 	    }
                   3784: 	    my $allkeys = join(':',@allkeys);
                   3785: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
                   3786: 
                   3787: 	    if (&untie_user_hash($hashref)) {
                   3788: 		&Reply($client, "ok\n", $userinput);
                   3789: 	    } else {
                   3790: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3791: 			"while attempting store\n", $userinput);
                   3792: 	    }
                   3793: 	} else {
                   3794: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3795: 		     "while attempting store\n", $userinput);
                   3796: 	}
                   3797:     } else {
                   3798: 	&Failure($client, "refused\n", $userinput);
                   3799:     }
                   3800: 
                   3801:     return 1;
                   3802: }
                   3803: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
                   3804: 
                   3805: sub hash_extract {
                   3806:     my ($str)=@_;
                   3807:     my %hash;
                   3808:     foreach my $pair (split(/\&/,$str)) {
                   3809: 	my ($key,$value)=split(/=/,$pair);
                   3810: 	$hash{$key}=$value;
                   3811:     }
                   3812:     return (%hash);
                   3813: }
                   3814: sub hash_to_str {
                   3815:     my ($hash_ref)=@_;
                   3816:     my $str;
                   3817:     foreach my $key (keys(%$hash_ref)) {
                   3818: 	$str.=$key.'='.$hash_ref->{$key}.'&';
                   3819:     }
                   3820:     $str=~s/\&$//;
                   3821:     return $str;
                   3822: }
                   3823: 
1.231     foxr     3824: #
                   3825: #  Dump out all versions of a resource that has key=value pairs associated
                   3826: # with it for each version.  These resources are built up via the store
                   3827: # command.
                   3828: #
                   3829: #  Parameters:
                   3830: #     $cmd               - Command keyword.
                   3831: #     $tail              - Remainder of the request which consists of:
                   3832: #                          domain/user   - User and auth. domain.
                   3833: #                          namespace     - name of resource database.
                   3834: #                          rid           - Resource id.
                   3835: #    $client             - socket open on the client.
                   3836: #
                   3837: # Returns:
                   3838: #      1  indicating the caller should not yet exit.
                   3839: # Side-effects:
                   3840: #   Writes a reply to the client.
                   3841: #   The reply is a string of the following shape:
                   3842: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
                   3843: #    Where the 1 above represents version 1.
                   3844: #    this continues for all pairs of keys in all versions.
                   3845: #
                   3846: #
                   3847: #    
                   3848: #
                   3849: sub restore_handler {
                   3850:     my ($cmd, $tail, $client) = @_;
                   3851: 
                   3852:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
1.351     banghart 3853:     my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
1.352     albertel 3854:     $namespace=~s/\//\_/g;
1.350     albertel 3855:     $namespace = &LONCAPA::clean_username($namespace);
1.349     albertel 3856: 
1.231     foxr     3857:     chomp($rid);
                   3858:     my $qresult='';
1.309     albertel 3859:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
                   3860:     if ($hashref) {
                   3861: 	my $version=$hashref->{"version:$rid"};
1.231     foxr     3862: 	$qresult.="version=$version&";
                   3863: 	my $scope;
                   3864: 	for ($scope=1;$scope<=$version;$scope++) {
1.309     albertel 3865: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
1.231     foxr     3866: 	    my @keys=split(/:/,$vkeys);
                   3867: 	    my $key;
                   3868: 	    $qresult.="$scope:keys=$vkeys&";
                   3869: 	    foreach $key (@keys) {
1.309     albertel 3870: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
1.231     foxr     3871: 	    }                                  
                   3872: 	}
1.311     albertel 3873: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3874: 	    $qresult=~s/\&$//;
1.387     albertel 3875: 	    &Reply( $client, \$qresult, $userinput);
1.231     foxr     3876: 	} else {
                   3877: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3878: 		    "while attempting restore\n", $userinput);
                   3879: 	}
                   3880:     } else {
                   3881: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3882: 		"while attempting restore\n", $userinput);
                   3883:     }
                   3884:   
                   3885:     return 1;
                   3886: 
                   3887: 
                   3888: }
                   3889: &register_handler("restore", \&restore_handler, 0,1,0);
1.234     foxr     3890: 
                   3891: #
1.324     raeburn  3892: #   Add a chat message to a synchronous discussion board.
1.234     foxr     3893: #
                   3894: # Parameters:
                   3895: #    $cmd                - Request keyword.
                   3896: #    $tail               - Tail of the command. A colon separated list
                   3897: #                          containing:
                   3898: #                          cdom    - Domain on which the chat board lives
1.324     raeburn  3899: #                          cnum    - Course containing the chat board.
                   3900: #                          newpost - Body of the posting.
                   3901: #                          group   - Optional group, if chat board is only 
                   3902: #                                    accessible in a group within the course 
1.234     foxr     3903: #   $client              - Socket open on the client.
                   3904: # Returns:
                   3905: #   1    - Indicating caller should keep on processing.
                   3906: #
                   3907: # Side-effects:
                   3908: #   writes a reply to the client.
                   3909: #
                   3910: #
                   3911: sub send_chat_handler {
                   3912:     my ($cmd, $tail, $client) = @_;
                   3913: 
                   3914:     
                   3915:     my $userinput = "$cmd:$tail";
                   3916: 
1.324     raeburn  3917:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
                   3918:     &chat_add($cdom,$cnum,$newpost,$group);
1.234     foxr     3919:     &Reply($client, "ok\n", $userinput);
                   3920: 
                   3921:     return 1;
                   3922: }
                   3923: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263     albertel 3924: 
1.234     foxr     3925: #
1.324     raeburn  3926: #   Retrieve the set of chat messages from a discussion board.
1.234     foxr     3927: #
                   3928: #  Parameters:
                   3929: #    $cmd             - Command keyword that initiated the request.
                   3930: #    $tail            - Remainder of the request after the command
                   3931: #                       keyword.  In this case a colon separated list of
                   3932: #                       chat domain    - Which discussion board.
                   3933: #                       chat id        - Discussion thread(?)
                   3934: #                       domain/user    - Authentication domain and username
                   3935: #                                        of the requesting person.
1.324     raeburn  3936: #                       group          - Optional course group containing
                   3937: #                                        the board.      
1.234     foxr     3938: #   $client           - Socket open on the client program.
                   3939: # Returns:
                   3940: #    1     - continue processing
                   3941: # Side effects:
                   3942: #    Response is written to the client.
                   3943: #
                   3944: sub retrieve_chat_handler {
                   3945:     my ($cmd, $tail, $client) = @_;
                   3946: 
                   3947: 
                   3948:     my $userinput = "$cmd:$tail";
                   3949: 
1.324     raeburn  3950:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
1.234     foxr     3951:     my $reply='';
1.324     raeburn  3952:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
1.234     foxr     3953: 	$reply.=&escape($_).':';
                   3954:     }
                   3955:     $reply=~s/\:$//;
1.387     albertel 3956:     &Reply($client, \$reply, $userinput);
1.234     foxr     3957: 
                   3958: 
                   3959:     return 1;
                   3960: }
                   3961: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
                   3962: 
                   3963: #
                   3964: #  Initiate a query of an sql database.  SQL query repsonses get put in
                   3965: #  a file for later retrieval.  This prevents sql query results from
                   3966: #  bottlenecking the system.  Note that with loncnew, perhaps this is
                   3967: #  less of an issue since multiple outstanding requests can be concurrently
                   3968: #  serviced.
                   3969: #
                   3970: #  Parameters:
1.535     raeburn  3971: #     $cmd       - Command keyword that initiated the request.
1.234     foxr     3972: #     $tail      - Remainder of the command after the keyword.
                   3973: #                  For this function, this consists of a query and
                   3974: #                  3 arguments that are self-documentingly labelled
                   3975: #                  in the original arg1, arg2, arg3.
                   3976: #     $client    - Socket open on the client.
                   3977: # Return:
                   3978: #    1   - Indicating processing should continue.
                   3979: # Side-effects:
                   3980: #    a reply is written to $client.
                   3981: #
                   3982: sub send_query_handler {
                   3983:     my ($cmd, $tail, $client) = @_;
                   3984: 
                   3985:     my $userinput = "$cmd:$tail";
                   3986: 
                   3987:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
                   3988:     $query=~s/\n*$//g;
1.534     raeburn  3989:     if (($query eq 'usersearch') || ($query eq 'instdirsearch')) {
                   3990:         my $usersearchconf = &get_usersearch_config($currentdomainid,'directorysrch');
                   3991:         my $earlyout;
                   3992:         if (ref($usersearchconf) eq 'HASH') {
                   3993:             if ($currentdomainid eq $clienthomedom) {
                   3994:                 if ($query eq 'usersearch') {
                   3995:                     if ($usersearchconf->{'lcavailable'} eq '0') {
                   3996:                         $earlyout = 1;
                   3997:                     }
                   3998:                 } else {
                   3999:                     if ($usersearchconf->{'available'} eq '0') {
                   4000:                         $earlyout = 1;
                   4001:                     }
                   4002:                 }
                   4003:             } else {
                   4004:                 if ($query eq 'usersearch') {
                   4005:                     if ($usersearchconf->{'lclocalonly'}) {
                   4006:                         $earlyout = 1;
                   4007:                     }
                   4008:                 } else {
                   4009:                     if ($usersearchconf->{'localonly'}) {
                   4010:                         $earlyout = 1;
                   4011:                     }
                   4012:                 }
                   4013:             }
                   4014:         }
                   4015:         if ($earlyout) {
                   4016:             &Reply($client, "query_not_authorized\n");
                   4017:             return 1;
                   4018:         }
                   4019:     }
1.234     foxr     4020:     &Reply($client, "". &sql_reply("$clientname\&$query".
                   4021: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
                   4022: 	  $userinput);
                   4023:     
                   4024:     return 1;
                   4025: }
                   4026: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
                   4027: 
                   4028: #
                   4029: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
                   4030: #   The query is submitted via a "querysend" transaction.
                   4031: #   There it is passed on to the lonsql daemon, queued and issued to
                   4032: #   mysql.
                   4033: #     This transaction is invoked when the sql transaction is complete
                   4034: #   it stores the query results in flie and indicates query completion.
                   4035: #   presumably local software then fetches this response... I'm guessing
                   4036: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
                   4037: #   lonsql on completion of the query interacts with the lond of our
                   4038: #   client to do a query reply storing two files:
                   4039: #    - id     - The results of the query.
                   4040: #    - id.end - Indicating the transaction completed. 
                   4041: #    NOTE: id is a unique id assigned to the query and querysend time.
                   4042: # Parameters:
                   4043: #    $cmd        - Command keyword that initiated this request.
                   4044: #    $tail       - Remainder of the tail.  In this case that's a colon
                   4045: #                  separated list containing the query Id and the 
                   4046: #                  results of the query.
                   4047: #    $client     - Socket open on the client.
                   4048: # Return:
                   4049: #    1           - Indicating that we should continue processing.
                   4050: # Side effects:
                   4051: #    ok written to the client.
                   4052: #
                   4053: sub reply_query_handler {
                   4054:     my ($cmd, $tail, $client) = @_;
                   4055: 
                   4056: 
                   4057:     my $userinput = "$cmd:$tail";
                   4058: 
1.339     albertel 4059:     my ($id,$reply)=split(/:/,$tail); 
1.234     foxr     4060:     my $store;
                   4061:     my $execdir=$perlvar{'lonDaemons'};
                   4062:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
                   4063: 	$reply=~s/\&/\n/g;
                   4064: 	print $store $reply;
                   4065: 	close $store;
                   4066: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
                   4067: 	print $store2 "done\n";
                   4068: 	close $store2;
                   4069: 	&Reply($client, "ok\n", $userinput);
                   4070:     } else {
                   4071: 	&Failure($client, "error: ".($!+0)
                   4072: 		." IO::File->new Failed ".
                   4073: 		"while attempting queryreply\n", $userinput);
                   4074:     }
                   4075:  
                   4076: 
                   4077:     return 1;
                   4078: }
                   4079: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
                   4080: 
                   4081: #
                   4082: #  Process the courseidput request.  Not quite sure what this means
                   4083: #  at the system level sense.  It appears a gdbm file in the 
                   4084: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
                   4085: #  a set of entries made in that database.
                   4086: #
                   4087: # Parameters:
                   4088: #   $cmd      - The command keyword that initiated this request.
                   4089: #   $tail     - Tail of the command.  In this case consists of a colon
                   4090: #               separated list contaning the domain to apply this to and
                   4091: #               an ampersand separated list of keyword=value pairs.
1.272     raeburn  4092: #               Each value is a colon separated list that includes:  
                   4093: #               description, institutional code and course owner.
                   4094: #               For backward compatibility with versions included
                   4095: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
                   4096: #               code and/or course owner are preserved from the existing 
                   4097: #               record when writing a new record in response to 1.1 or 
                   4098: #               1.2 implementations of lonnet::flushcourselogs().   
                   4099: #                      
1.234     foxr     4100: #   $client   - Socket open on the client.
                   4101: # Returns:
                   4102: #   1    - indicating that processing should continue
                   4103: #
                   4104: # Side effects:
                   4105: #   reply is written to the client.
                   4106: #
                   4107: sub put_course_id_handler {
                   4108:     my ($cmd, $tail, $client) = @_;
                   4109: 
                   4110: 
                   4111:     my $userinput = "$cmd:$tail";
                   4112: 
1.266     raeburn  4113:     my ($udom, $what) = split(/:/, $tail,2);
1.234     foxr     4114:     chomp($what);
                   4115:     my $now=time;
                   4116:     my @pairs=split(/\&/,$what);
                   4117: 
                   4118:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4119:     if ($hashref) {
                   4120: 	foreach my $pair (@pairs) {
1.271     raeburn  4121:             my ($key,$courseinfo) = split(/=/,$pair,2);
                   4122:             $courseinfo =~ s/=/:/g;
1.384     raeburn  4123:             if (defined($hashref->{$key})) {
                   4124:                 my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
                   4125:                 if (ref($value) eq 'HASH') {
                   4126:                     my @items = ('description','inst_code','owner','type');
                   4127:                     my @new_items = split(/:/,$courseinfo,-1);
                   4128:                     my %storehash; 
                   4129:                     for (my $i=0; $i<@new_items; $i++) {
1.391     raeburn  4130:                         $storehash{$items[$i]} = &unescape($new_items[$i]);
1.384     raeburn  4131:                     }
                   4132:                     $hashref->{$key} = 
                   4133:                         &Apache::lonnet::freeze_escape(\%storehash);
                   4134:                     my $unesc_key = &unescape($key);
                   4135:                     $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4136:                     next;
1.383     raeburn  4137:                 }
1.384     raeburn  4138:             }
                   4139:             my @current_items = split(/:/,$hashref->{$key},-1);
                   4140:             shift(@current_items); # remove description
                   4141:             pop(@current_items);   # remove last access
                   4142:             my $numcurrent = scalar(@current_items);
                   4143:             if ($numcurrent > 3) {
                   4144:                 $numcurrent = 3;
                   4145:             }
                   4146:             my @new_items = split(/:/,$courseinfo,-1);
                   4147:             my $numnew = scalar(@new_items);
                   4148:             if ($numcurrent > 0) {
                   4149:                 if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2 
                   4150:                     for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
                   4151:                         $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
1.333     raeburn  4152:                     }
1.272     raeburn  4153:                 }
                   4154:             }
1.384     raeburn  4155:             $hashref->{$key}=$courseinfo.':'.$now;
1.234     foxr     4156: 	}
1.311     albertel 4157: 	if (&untie_domain_hash($hashref)) {
1.253     foxr     4158: 	    &Reply( $client, "ok\n", $userinput);
1.234     foxr     4159: 	} else {
1.253     foxr     4160: 	    &Failure($client, "error: ".($!+0)
1.234     foxr     4161: 		     ." untie(GDBM) Failed ".
                   4162: 		     "while attempting courseidput\n", $userinput);
                   4163: 	}
                   4164:     } else {
1.253     foxr     4165: 	&Failure($client, "error: ".($!+0)
1.234     foxr     4166: 		 ." tie(GDBM) Failed ".
                   4167: 		 "while attempting courseidput\n", $userinput);
                   4168:     }
                   4169: 
                   4170:     return 1;
                   4171: }
                   4172: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
                   4173: 
1.383     raeburn  4174: sub put_course_id_hash_handler {
                   4175:     my ($cmd, $tail, $client) = @_;
                   4176:     my $userinput = "$cmd:$tail";
1.384     raeburn  4177:     my ($udom,$mode,$what) = split(/:/, $tail,3);
1.383     raeburn  4178:     chomp($what);
                   4179:     my $now=time;
                   4180:     my @pairs=split(/\&/,$what);
1.384     raeburn  4181:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
1.383     raeburn  4182:     if ($hashref) {
                   4183:         foreach my $pair (@pairs) {
                   4184:             my ($key,$value)=split(/=/,$pair);
1.384     raeburn  4185:             my $unesc_key = &unescape($key);
                   4186:             if ($mode ne 'timeonly') {
                   4187:                 if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
                   4188:                     my $curritems = &Apache::lonnet::thaw_unescape($key); 
                   4189:                     if (ref($curritems) ne 'HASH') {
                   4190:                         my @current_items = split(/:/,$hashref->{$key},-1);
                   4191:                         my $lasttime = pop(@current_items);
                   4192:                         $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
                   4193:                     } else {
                   4194:                         $hashref->{&escape('lasttime:'.$unesc_key)} = '';
                   4195:                     }
                   4196:                 } 
                   4197:                 $hashref->{$key} = $value;
                   4198:             }
                   4199:             if ($mode ne 'notime') {
                   4200:                 $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4201:             }
1.383     raeburn  4202:         }
                   4203:         if (&untie_domain_hash($hashref)) {
                   4204:             &Reply($client, "ok\n", $userinput);
                   4205:         } else {
                   4206:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4207:                      "while attempting courseidputhash\n", $userinput);
                   4208:         }
                   4209:     } else {
                   4210:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4211:                   "while attempting courseidputhash\n", $userinput);
                   4212:     }
                   4213:     return 1;
                   4214: }
                   4215: &register_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
                   4216: 
1.234     foxr     4217: #  Retrieves the value of a course id resource keyword pattern
                   4218: #  defined since a starting date.  Both the starting date and the
                   4219: #  keyword pattern are optional.  If the starting date is not supplied it
                   4220: #  is treated as the beginning of time.  If the pattern is not found,
                   4221: #  it is treatred as "." matching everything.
                   4222: #
                   4223: #  Parameters:
                   4224: #     $cmd     - Command keyword that resulted in us being dispatched.
                   4225: #     $tail    - The remainder of the command that, in this case, consists
                   4226: #                of a colon separated list of:
                   4227: #                 domain   - The domain in which the course database is 
                   4228: #                            defined.
                   4229: #                 since    - Optional parameter describing the minimum
                   4230: #                            time of definition(?) of the resources that
                   4231: #                            will match the dump.
                   4232: #                 description - regular expression that is used to filter
                   4233: #                            the dump.  Only keywords matching this regexp
                   4234: #                            will be used.
1.272     raeburn  4235: #                 institutional code - optional supplied code to filter 
                   4236: #                            the dump. Only courses with an institutional code 
                   4237: #                            that match the supplied code will be returned.
1.336     raeburn  4238: #                 owner    - optional supplied username and domain of owner to
                   4239: #                            filter the dump.  Only courses for which the course
                   4240: #                            owner matches the supplied username and/or domain
                   4241: #                            will be returned. Pre-2.2.0 legacy entries from 
                   4242: #                            nohist_courseiddump will only contain usernames.
1.384     raeburn  4243: #                 type     - optional parameter for selection 
1.418     raeburn  4244: #                 regexp_ok - if 1 or -1 allow the supplied institutional code
                   4245: #                            filter to behave as a regular expression:
                   4246: #	                      1 will not exclude the course if the instcode matches the RE 
                   4247: #                            -1 will exclude the course if the instcode matches the RE
1.384     raeburn  4248: #                 rtn_as_hash - whether to return the information available for
                   4249: #                            each matched item as a frozen hash of all 
                   4250: #                            key, value pairs in the item's hash, or as a 
                   4251: #                            colon-separated list of (in order) description,
                   4252: #                            institutional code, and course owner.
1.404     raeburn  4253: #                 selfenrollonly - filter by courses allowing self-enrollment  
                   4254: #                                  now or in the future (selfenrollonly = 1).
                   4255: #                 catfilter - filter by course category, assigned to a course 
                   4256: #                             using manually defined categories (i.e., not
1.407     raeburn  4257: #                             self-cataloging based on on institutional code).   
1.404     raeburn  4258: #                 showhidden - include course in results even if course  
1.407     raeburn  4259: #                              was set to be excluded from course catalog (DC only).
1.404     raeburn  4260: #                 caller -  if set to 'coursecatalog', courses set to be hidden
                   4261: #                           from course catalog will be excluded from results (unless
                   4262: #                           overridden by "showhidden".
1.427     raeburn  4263: #                 cloner - escaped username:domain of course cloner (if picking course to
1.419     raeburn  4264: #                          clone).
                   4265: #                 cc_clone_list - escaped comma separated list of courses for which 
                   4266: #                                 course cloner has active CC role (and so can clone
                   4267: #                                 automatically).
1.427     raeburn  4268: #                 cloneonly - filter by courses for which cloner has rights to clone.
                   4269: #                 createdbefore - include courses for which creation date preceeded this date.
                   4270: #                 createdafter - include courses for which creation date followed this date.
                   4271: #                 creationcontext - include courses created in specified context 
1.404     raeburn  4272: #
1.445     raeburn  4273: #                 domcloner - flag to indicate if user can create CCs in course's domain.
1.505     raeburn  4274: #                             If so, ability to clone course is automatic.
                   4275: #                 hasuniquecode - filter by courses for which a six character unique code has 
                   4276: #                                 been set.
1.445     raeburn  4277: #
1.234     foxr     4278: #     $client  - The socket open on the client.
                   4279: # Returns:
                   4280: #    1     - Continue processing.
                   4281: # Side Effects:
                   4282: #   a reply is written to $client.
                   4283: sub dump_course_id_handler {
                   4284:     my ($cmd, $tail, $client) = @_;
1.494     droeschl 4285: 
                   4286:     my $res = LONCAPA::Lond::dump_course_id_handler($tail);
                   4287:     if ($res =~ /^error:/) {
                   4288:         Failure($client, \$res, "$cmd:$tail");
                   4289:     } else {
                   4290:         Reply($client, \$res, "$cmd:$tail");
                   4291:     }
                   4292: 
                   4293:     return 1;  
                   4294: 
                   4295:     #TODO remove
1.234     foxr     4296:     my $userinput = "$cmd:$tail";
                   4297: 
1.333     raeburn  4298:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
1.404     raeburn  4299:         $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
1.427     raeburn  4300:         $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
1.505     raeburn  4301:         $creationcontext,$domcloner,$hasuniquecode) =split(/:/,$tail);
1.397     raeburn  4302:     my $now = time;
1.419     raeburn  4303:     my ($cloneruname,$clonerudom,%cc_clone);
1.234     foxr     4304:     if (defined($description)) {
                   4305: 	$description=&unescape($description);
                   4306:     } else {
                   4307: 	$description='.';
                   4308:     }
1.266     raeburn  4309:     if (defined($instcodefilter)) {
                   4310:         $instcodefilter=&unescape($instcodefilter);
                   4311:     } else {
                   4312:         $instcodefilter='.';
                   4313:     }
1.336     raeburn  4314:     my ($ownerunamefilter,$ownerdomfilter);
1.266     raeburn  4315:     if (defined($ownerfilter)) {
                   4316:         $ownerfilter=&unescape($ownerfilter);
1.336     raeburn  4317:         if ($ownerfilter ne '.' && defined($ownerfilter)) {
                   4318:             if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
                   4319:                  $ownerunamefilter = $1;
                   4320:                  $ownerdomfilter = $2;
                   4321:             } else {
                   4322:                 $ownerunamefilter = $ownerfilter;
                   4323:                 $ownerdomfilter = '';
                   4324:             }
                   4325:         }
1.266     raeburn  4326:     } else {
                   4327:         $ownerfilter='.';
                   4328:     }
1.336     raeburn  4329: 
1.282     raeburn  4330:     if (defined($coursefilter)) {
                   4331:         $coursefilter=&unescape($coursefilter);
                   4332:     } else {
                   4333:         $coursefilter='.';
                   4334:     }
1.333     raeburn  4335:     if (defined($typefilter)) {
                   4336:         $typefilter=&unescape($typefilter);
                   4337:     } else {
                   4338:         $typefilter='.';
                   4339:     }
1.344     raeburn  4340:     if (defined($regexp_ok)) {
                   4341:         $regexp_ok=&unescape($regexp_ok);
                   4342:     }
1.401     raeburn  4343:     if (defined($catfilter)) {
                   4344:         $catfilter=&unescape($catfilter);
                   4345:     }
1.419     raeburn  4346:     if (defined($cloner)) {
                   4347:         $cloner = &unescape($cloner);
                   4348:         ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/); 
                   4349:     }
                   4350:     if (defined($cc_clone_list)) {
                   4351:         $cc_clone_list = &unescape($cc_clone_list);
                   4352:         my @cc_cloners = split('&',$cc_clone_list);
                   4353:         foreach my $cid (@cc_cloners) {
                   4354:             my ($clonedom,$clonenum) = split(':',$cid);
                   4355:             next if ($clonedom ne $udom); 
                   4356:             $cc_clone{$clonedom.'_'.$clonenum} = 1;
                   4357:         } 
                   4358:     }
1.431     raeburn  4359:     if ($createdbefore ne '') {
1.427     raeburn  4360:         $createdbefore = &unescape($createdbefore);
                   4361:     } else {
                   4362:        $createdbefore = 0;
                   4363:     }
1.431     raeburn  4364:     if ($createdafter ne '') {
1.427     raeburn  4365:         $createdafter = &unescape($createdafter);
                   4366:     } else {
                   4367:         $createdafter = 0;
                   4368:     }
1.431     raeburn  4369:     if ($creationcontext ne '') {
1.427     raeburn  4370:         $creationcontext = &unescape($creationcontext);
                   4371:     } else {
                   4372:         $creationcontext = '.';
                   4373:     }
1.505     raeburn  4374:     unless ($hasuniquecode) {
                   4375:         $hasuniquecode = '.';
                   4376:     }
1.384     raeburn  4377:     my $unpack = 1;
1.485     raeburn  4378:     if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' && 
1.384     raeburn  4379:         $typefilter eq '.') {
                   4380:         $unpack = 0;
                   4381:     }
                   4382:     if (!defined($since)) { $since=0; }
1.234     foxr     4383:     my $qresult='';
                   4384:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4385:     if ($hashref) {
1.384     raeburn  4386: 	while (my ($key,$value) = each(%$hashref)) {
1.397     raeburn  4387:             my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
1.427     raeburn  4388:                 %unesc_val,$selfenroll_end,$selfenroll_types,$created,
                   4389:                 $context);
1.384     raeburn  4390:             $unesc_key = &unescape($key);
                   4391:             if ($unesc_key =~ /^lasttime:/) {
                   4392:                 next;
                   4393:             } else {
                   4394:                 $lasttime_key = &escape('lasttime:'.$unesc_key);
                   4395:             }
                   4396:             if ($hashref->{$lasttime_key} ne '') {
                   4397:                 $lasttime = $hashref->{$lasttime_key};
                   4398:                 next if ($lasttime<$since);
                   4399:             }
1.419     raeburn  4400:             my ($canclone,$valchange);
1.384     raeburn  4401:             my $items = &Apache::lonnet::thaw_unescape($value);
                   4402:             if (ref($items) eq 'HASH') {
1.429     raeburn  4403:                 if ($hashref->{$lasttime_key} eq '') {
1.430     raeburn  4404:                     next if ($since > 1);
1.429     raeburn  4405:                 }
1.384     raeburn  4406:                 $is_hash =  1;
1.445     raeburn  4407:                 if ($domcloner) {
                   4408:                     $canclone = 1;
                   4409:                 } elsif (defined($clonerudom)) {
1.419     raeburn  4410:                     if ($items->{'cloners'}) {
                   4411:                         my @cloneable = split(',',$items->{'cloners'});
                   4412:                         if (@cloneable) {
                   4413:                             if (grep(/^\*$/,@cloneable))  {
                   4414:                                 $canclone = 1;
                   4415:                             } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
                   4416:                                 $canclone = 1;
                   4417:                             } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
                   4418:                                 $canclone = 1;
                   4419:                             }
                   4420:                         }
                   4421:                         unless ($canclone) {
                   4422:                             if ($cloneruname ne '' && $clonerudom ne '') {
                   4423:                                 if ($cc_clone{$unesc_key}) {
                   4424:                                     $canclone = 1;
                   4425:                                     $items->{'cloners'} .= ','.$cloneruname.':'.
                   4426:                                                            $clonerudom;
                   4427:                                     $valchange = 1;
                   4428:                                 }
                   4429:                             }
                   4430:                         }
                   4431:                     } elsif (defined($cloneruname)) {
                   4432:                         if ($cc_clone{$unesc_key}) {
                   4433:                             $canclone = 1;
                   4434:                             $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4435:                             $valchange = 1;
                   4436:                         }
1.437     raeburn  4437:                         unless ($canclone) {
                   4438:                             if ($items->{'owner'} =~ /:/) {
                   4439:                                 if ($items->{'owner'} eq $cloner) {
                   4440:                                     $canclone = 1;
                   4441:                                 }
1.444     raeburn  4442:                             } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
1.437     raeburn  4443:                                 $canclone = 1;
                   4444:                             }
                   4445:                             if ($canclone) {
                   4446:                                 $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4447:                                 $valchange = 1;
                   4448:                             }
                   4449:                         }
1.419     raeburn  4450:                     }
                   4451:                 }
1.384     raeburn  4452:                 if ($unpack || !$rtn_as_hash) {
                   4453:                     $unesc_val{'descr'} = $items->{'description'};
                   4454:                     $unesc_val{'inst_code'} = $items->{'inst_code'};
                   4455:                     $unesc_val{'owner'} = $items->{'owner'};
                   4456:                     $unesc_val{'type'} = $items->{'type'};
1.419     raeburn  4457:                     $unesc_val{'cloners'} = $items->{'cloners'};
1.427     raeburn  4458:                     $unesc_val{'created'} = $items->{'created'};
                   4459:                     $unesc_val{'context'} = $items->{'context'};
1.404     raeburn  4460:                 }
                   4461:                 $selfenroll_types = $items->{'selfenroll_types'};
                   4462:                 $selfenroll_end = $items->{'selfenroll_end_date'};
1.427     raeburn  4463:                 $created = $items->{'created'};
                   4464:                 $context = $items->{'context'};
1.505     raeburn  4465:                 if ($hasuniquecode ne '.') {
                   4466:                     next unless ($items->{'uniquecode'});
                   4467:                 }
1.404     raeburn  4468:                 if ($selfenrollonly) {
                   4469:                     next if (!$selfenroll_types);
                   4470:                     if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
                   4471:                         next;
1.397     raeburn  4472:                     }
1.404     raeburn  4473:                 }
1.427     raeburn  4474:                 if ($creationcontext ne '.') {
                   4475:                     next if (($context ne '') && ($context ne $creationcontext));  
                   4476:                 }
                   4477:                 if ($createdbefore > 0) {
                   4478:                     next if (($created eq '') || ($created > $createdbefore));   
                   4479:                 }
                   4480:                 if ($createdafter > 0) {
                   4481:                     next if (($created eq '') || ($created <= $createdafter)); 
                   4482:                 }
1.404     raeburn  4483:                 if ($catfilter ne '') {
1.406     raeburn  4484:                     next if ($items->{'categories'} eq '');
                   4485:                     my @categories = split('&',$items->{'categories'}); 
1.407     raeburn  4486:                     next if (@categories == 0);
                   4487:                     my @subcats = split('&',$catfilter);
                   4488:                     my $matchcat = 0;
                   4489:                     foreach my $cat (@categories) {
                   4490:                         if (grep(/^\Q$cat\E$/,@subcats)) {
                   4491:                             $matchcat = 1;
                   4492:                             last;
                   4493:                         }
                   4494:                     }
                   4495:                     next if (!$matchcat);
1.404     raeburn  4496:                 }
                   4497:                 if ($caller eq 'coursecatalog') {
1.405     raeburn  4498:                     if ($items->{'hidefromcat'} eq 'yes') {
                   4499:                         next if !$showhidden;
1.401     raeburn  4500:                     }
1.384     raeburn  4501:                 }
1.383     raeburn  4502:             } else {
1.401     raeburn  4503:                 next if ($catfilter ne '');
1.419     raeburn  4504:                 next if ($selfenrollonly);
1.427     raeburn  4505:                 next if ($createdbefore || $createdafter);
                   4506:                 next if ($creationcontext ne '.');
1.419     raeburn  4507:                 if ((defined($clonerudom)) && (defined($cloneruname)))  {
                   4508:                     if ($cc_clone{$unesc_key}) {
                   4509:                         $canclone = 1;
                   4510:                         $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
                   4511:                     }
                   4512:                 }
1.384     raeburn  4513:                 $is_hash =  0;
1.388     raeburn  4514:                 my @courseitems = split(/:/,$value);
1.403     raeburn  4515:                 $lasttime = pop(@courseitems);
1.402     raeburn  4516:                 if ($hashref->{$lasttime_key} eq '') {
                   4517:                     next if ($lasttime<$since);
                   4518:                 }
1.384     raeburn  4519: 	        ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
1.383     raeburn  4520:             }
1.419     raeburn  4521:             if ($cloneonly) {
                   4522:                next unless ($canclone);
                   4523:             }
1.266     raeburn  4524:             my $match = 1;
1.384     raeburn  4525: 	    if ($description ne '.') {
                   4526:                 if (!$is_hash) {
                   4527:                     $unesc_val{'descr'} = &unescape($val{'descr'});
                   4528:                 }
                   4529:                 if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
1.266     raeburn  4530:                     $match = 0;
1.384     raeburn  4531:                 }
1.266     raeburn  4532:             }
1.384     raeburn  4533:             if ($instcodefilter ne '.') {
                   4534:                 if (!$is_hash) {
                   4535:                     $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
                   4536:                 }
1.418     raeburn  4537:                 if ($regexp_ok == 1) {
1.384     raeburn  4538:                     if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
1.344     raeburn  4539:                         $match = 0;
                   4540:                     }
1.418     raeburn  4541:                 } elsif ($regexp_ok == -1) {
                   4542:                     if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
                   4543:                         $match = 0;
                   4544:                     }
1.344     raeburn  4545:                 } else {
1.384     raeburn  4546:                     if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
1.344     raeburn  4547:                         $match = 0;
                   4548:                     }
1.266     raeburn  4549:                 }
1.234     foxr     4550: 	    }
1.384     raeburn  4551:             if ($ownerfilter ne '.') {
                   4552:                 if (!$is_hash) {
                   4553:                     $unesc_val{'owner'} = &unescape($val{'owner'});
                   4554:                 }
1.336     raeburn  4555:                 if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
1.384     raeburn  4556:                     if ($unesc_val{'owner'} =~ /:/) {
                   4557:                         if (eval{$unesc_val{'owner'} !~ 
                   4558:                              /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
1.336     raeburn  4559:                             $match = 0;
                   4560:                         } 
                   4561:                     } else {
1.384     raeburn  4562:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4563:                             $match = 0;
                   4564:                         }
                   4565:                     }
                   4566:                 } elsif ($ownerunamefilter ne '') {
1.384     raeburn  4567:                     if ($unesc_val{'owner'} =~ /:/) {
                   4568:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
1.336     raeburn  4569:                              $match = 0;
                   4570:                         }
                   4571:                     } else {
1.384     raeburn  4572:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4573:                             $match = 0;
                   4574:                         }
                   4575:                     }
                   4576:                 } elsif ($ownerdomfilter ne '') {
1.384     raeburn  4577:                     if ($unesc_val{'owner'} =~ /:/) {
                   4578:                         if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
1.336     raeburn  4579:                              $match = 0;
                   4580:                         }
                   4581:                     } else {
                   4582:                         if ($ownerdomfilter ne $udom) {
                   4583:                             $match = 0;
                   4584:                         }
                   4585:                     }
1.266     raeburn  4586:                 }
                   4587:             }
1.384     raeburn  4588:             if ($coursefilter ne '.') {
                   4589:                 if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
1.282     raeburn  4590:                     $match = 0;
                   4591:                 }
                   4592:             }
1.384     raeburn  4593:             if ($typefilter ne '.') {
                   4594:                 if (!$is_hash) {
                   4595:                     $unesc_val{'type'} = &unescape($val{'type'});
                   4596:                 }
                   4597:                 if ($unesc_val{'type'} eq '') {
1.333     raeburn  4598:                     if ($typefilter ne 'Course') {
                   4599:                         $match = 0;
                   4600:                     }
1.383     raeburn  4601:                 } else {
1.384     raeburn  4602:                     if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
1.333     raeburn  4603:                         $match = 0;
                   4604:                     }
                   4605:                 }
                   4606:             }
1.266     raeburn  4607:             if ($match == 1) {
1.384     raeburn  4608:                 if ($rtn_as_hash) {
                   4609:                     if ($is_hash) {
1.419     raeburn  4610:                         if ($valchange) {
                   4611:                             my $newvalue = &Apache::lonnet::freeze_escape($items);
                   4612:                             $qresult.=$key.'='.$newvalue.'&';
                   4613:                         } else {
                   4614:                             $qresult.=$key.'='.$value.'&';
                   4615:                         }
1.384     raeburn  4616:                     } else {
1.388     raeburn  4617:                         my %rtnhash = ( 'description' => &unescape($val{'descr'}),
                   4618:                                         'inst_code' => &unescape($val{'inst_code'}),
                   4619:                                         'owner'     => &unescape($val{'owner'}),
                   4620:                                         'type'      => &unescape($val{'type'}),
1.419     raeburn  4621:                                         'cloners'   => &unescape($val{'cloners'}),
1.384     raeburn  4622:                                       );
                   4623:                         my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
                   4624:                         $qresult.=$key.'='.$items.'&';
                   4625:                     }
1.383     raeburn  4626:                 } else {
1.384     raeburn  4627:                     if ($is_hash) {
                   4628:                         $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
                   4629:                                     &escape($unesc_val{'inst_code'}).':'.
                   4630:                                     &escape($unesc_val{'owner'}).'&';
                   4631:                     } else {
                   4632:                         $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
                   4633:                                     ':'.$val{'owner'}.'&';
                   4634:                     }
1.383     raeburn  4635:                 }
1.266     raeburn  4636:             }
1.234     foxr     4637: 	}
1.311     albertel 4638: 	if (&untie_domain_hash($hashref)) {
1.234     foxr     4639: 	    chop($qresult);
1.387     albertel 4640: 	    &Reply($client, \$qresult, $userinput);
1.234     foxr     4641: 	} else {
                   4642: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4643: 		    "while attempting courseiddump\n", $userinput);
                   4644: 	}
                   4645:     } else {
                   4646: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4647: 		"while attempting courseiddump\n", $userinput);
                   4648:     }
                   4649:     return 1;
                   4650: }
                   4651: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238     foxr     4652: 
1.438     raeburn  4653: sub course_lastaccess_handler {
                   4654:     my ($cmd, $tail, $client) = @_;
                   4655:     my $userinput = "$cmd:$tail";
                   4656:     my ($cdom,$cnum) = split(':',$tail); 
                   4657:     my (%lastaccess,$qresult);
                   4658:     my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
                   4659:     if ($hashref) {
                   4660:         while (my ($key,$value) = each(%$hashref)) {
                   4661:             my ($unesc_key,$lasttime);
                   4662:             $unesc_key = &unescape($key);
                   4663:             if ($cnum) {
                   4664:                 next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
                   4665:             }
                   4666:             if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
                   4667:                 $lastaccess{$1} = $value;
                   4668:             } else {
                   4669:                 my $items = &Apache::lonnet::thaw_unescape($value);
                   4670:                 if (ref($items) eq 'HASH') {
                   4671:                     unless ($lastaccess{$unesc_key}) {
                   4672:                         $lastaccess{$unesc_key} = '';
                   4673:                     }
                   4674:                 } else {
                   4675:                     my @courseitems = split(':',$value);
                   4676:                     $lastaccess{$unesc_key} = pop(@courseitems);
                   4677:                 }
                   4678:             }
                   4679:         }
                   4680:         foreach my $cid (sort(keys(%lastaccess))) {
                   4681:             $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&'; 
                   4682:         }
                   4683:         if (&untie_domain_hash($hashref)) {
                   4684:             if ($qresult) {
                   4685:                 chop($qresult);
                   4686:             }
                   4687:             &Reply($client, \$qresult, $userinput);
                   4688:         } else {
                   4689:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4690:                     "while attempting lastacourseaccess\n", $userinput);
                   4691:         }
                   4692:     } else {
                   4693:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4694:                 "while attempting lastcourseaccess\n", $userinput);
                   4695:     }
                   4696:     return 1;
                   4697: }
                   4698: &register_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
                   4699: 
1.238     foxr     4700: #
1.348     raeburn  4701: # Puts an unencrypted entry in a namespace db file at the domain level 
                   4702: #
                   4703: # Parameters:
                   4704: #    $cmd      - The command that got us here.
                   4705: #    $tail     - Tail of the command (remaining parameters).
                   4706: #    $client   - File descriptor connected to client.
                   4707: # Returns
                   4708: #     0        - Requested to exit, caller should shut down.
                   4709: #     1        - Continue processing.
                   4710: #  Side effects:
                   4711: #     reply is written to $client.
                   4712: #
                   4713: sub put_domain_handler {
                   4714:     my ($cmd,$tail,$client) = @_;
                   4715: 
                   4716:     my $userinput = "$cmd:$tail";
                   4717: 
                   4718:     my ($udom,$namespace,$what) =split(/:/,$tail,3);
                   4719:     chomp($what);
                   4720:     my @pairs=split(/\&/,$what);
                   4721:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
                   4722:                                    "P", $what);
                   4723:     if ($hashref) {
                   4724:         foreach my $pair (@pairs) {
                   4725:             my ($key,$value)=split(/=/,$pair);
                   4726:             $hashref->{$key}=$value;
                   4727:         }
                   4728:         if (&untie_domain_hash($hashref)) {
                   4729:             &Reply($client, "ok\n", $userinput);
                   4730:         } else {
                   4731:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4732:                      "while attempting putdom\n", $userinput);
                   4733:         }
                   4734:     } else {
                   4735:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4736:                   "while attempting putdom\n", $userinput);
                   4737:     }
                   4738: 
                   4739:     return 1;
                   4740: }
                   4741: &register_handler("putdom", \&put_domain_handler, 0, 1, 0);
                   4742: 
1.517     raeburn  4743: # Updates one or more entries in clickers.db file at the domain level
                   4744: #
                   4745: # Parameters:
                   4746: #    $cmd      - The command that got us here.
                   4747: #    $tail     - Tail of the command (remaining parameters).
                   4748: #                In this case a colon separated list containing:
                   4749: #                (a) the domain for which we are updating the entries,
                   4750: #                (b) the action required -- add or del -- and
                   4751: #                (c) a &-separated list of entries to add or delete.
                   4752: #    $client   - File descriptor connected to client.
                   4753: # Returns
                   4754: #     1        - Continue processing.
                   4755: #     0        - Requested to exit, caller should shut down.
                   4756: #  Side effects:
                   4757: #     reply is written to $client.
                   4758: #
                   4759: 
                   4760: 
                   4761: sub update_clickers {
                   4762:     my ($cmd, $tail, $client)  = @_;
                   4763: 
                   4764:     my $userinput = "$cmd:$tail";
                   4765:     my ($udom,$action,$what) =split(/:/,$tail,3);
                   4766:     chomp($what);
                   4767: 
                   4768:     my $hashref = &tie_domain_hash($udom, "clickers", &GDBM_WRCREAT(),
                   4769:                                  "U","$action:$what");
                   4770: 
                   4771:     if (!$hashref) {
                   4772:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4773:                   "while attempting updateclickers\n", $userinput);
                   4774:         return 1;
                   4775:     }
                   4776: 
                   4777:     my @pairs=split(/\&/,$what);
                   4778:     foreach my $pair (@pairs) {
                   4779:         my ($key,$value)=split(/=/,$pair);
                   4780:         if ($action eq 'add') {
                   4781:             if (exists($hashref->{$key})) {
                   4782:                 my @newvals = split(/,/,&unescape($value));
                   4783:                 my @currvals = split(/,/,&unescape($hashref->{$key}));
                   4784:                 my @merged = sort(keys(%{{map { $_ => 1 } (@newvals,@currvals)}}));
                   4785:                 $hashref->{$key}=&escape(join(',',@merged));
                   4786:             } else {
                   4787:                 $hashref->{$key}=$value;
                   4788:             }
                   4789:         } elsif ($action eq 'del') {
                   4790:             if (exists($hashref->{$key})) {
                   4791:                 my %current;
                   4792:                 map { $current{$_} = 1; } split(/,/,&unescape($hashref->{$key}));
                   4793:                 map { delete($current{$_}); } split(/,/,&unescape($value));
                   4794:                 if (keys(%current)) {
                   4795:                     $hashref->{$key}=&escape(join(',',sort(keys(%current))));
                   4796:                 } else {
                   4797:                     delete($hashref->{$key});
                   4798:                 }
                   4799:             }
                   4800:         }
                   4801:     }
                   4802:     if (&untie_user_hash($hashref)) {
                   4803:         &Reply( $client, "ok\n", $userinput);
                   4804:     } else {
                   4805:         &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   4806:                  "while attempting put\n",
                   4807:                  $userinput);
                   4808:     }
                   4809:     return 1;
                   4810: }
                   4811: &register_handler("updateclickers", \&update_clickers, 0, 1, 0);
                   4812: 
                   4813: 
                   4814: # Deletes one or more entries in a namespace db file at the domain level
                   4815: #
                   4816: # Parameters:
                   4817: #    $cmd      - The command that got us here.
                   4818: #    $tail     - Tail of the command (remaining parameters).
                   4819: #                In this case a colon separated list containing:
                   4820: #                (a) the domain for which we are deleting the entries,
                   4821: #                (b) &-separated list of keys to delete.  
                   4822: #    $client   - File descriptor connected to client.
                   4823: # Returns
                   4824: #     1        - Continue processing.
                   4825: #     0        - Requested to exit, caller should shut down.
                   4826: #  Side effects:
                   4827: #     reply is written to $client.
                   4828: #
                   4829: 
                   4830: sub del_domain_handler {
                   4831:     my ($cmd,$tail,$client) = @_;
                   4832: 
                   4833:     my $userinput = "$cmd:$tail";
                   4834: 
                   4835:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   4836:     chomp($what);
                   4837:     my $hashref = &tie_domain_hash($udom,$namespace,&GDBM_WRCREAT(),
                   4838:                                    "D", $what);
                   4839:     if ($hashref) {
                   4840:         my @keys=split(/\&/,$what);
                   4841:         foreach my $key (@keys) {
                   4842:             delete($hashref->{$key});
                   4843:         }
                   4844:         if (&untie_user_hash($hashref)) {
                   4845:             &Reply($client, "ok\n", $userinput);
                   4846:         } else {
                   4847:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4848:                     "while attempting deldom\n", $userinput);
                   4849:         }
                   4850:     } else {
                   4851:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4852:                  "while attempting deldom\n", $userinput);
                   4853:     }
                   4854:     return 1;
                   4855: }
                   4856: &register_handler("deldom", \&del_domain_handler, 0, 1, 0);
                   4857: 
                   4858: 
1.348     raeburn  4859: # Unencrypted get from the namespace database file at the domain level.
                   4860: # This function retrieves a keyed item from a specific named database in the
                   4861: # domain directory.
                   4862: #
                   4863: # Parameters:
                   4864: #   $cmd             - Command request keyword (get).
                   4865: #   $tail            - Tail of the command.  This is a colon separated list
                   4866: #                      consisting of the domain and the 'namespace' 
                   4867: #                      which selects the gdbm file to do the lookup in,
                   4868: #                      & separated list of keys to lookup.  Note that
                   4869: #                      the values are returned as an & separated list too.
                   4870: #   $client          - File descriptor open on the client.
                   4871: # Returns:
                   4872: #   1       - Continue processing.
                   4873: #   0       - Exit.
                   4874: #  Side effects:
                   4875: #     reply is written to $client.
                   4876: #
                   4877: 
                   4878: sub get_domain_handler {
                   4879:     my ($cmd, $tail, $client) = @_;
                   4880: 
1.461     foxr     4881: 
1.536     raeburn  4882:     my $userinput = "$cmd:$tail";
                   4883: 
                   4884:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   4885:     chomp($what);
                   4886:     if ($namespace =~ /^enc/) {
                   4887:         &Failure( $client, "refused\n", $userinput);
                   4888:     } else {
                   4889:         my @queries=split(/\&/,$what);
                   4890:         my $qresult='';
                   4891:         my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
                   4892:         if ($hashref) {
                   4893:             for (my $i=0;$i<=$#queries;$i++) {
                   4894:                 $qresult.="$hashref->{$queries[$i]}&";
                   4895:             }
                   4896:             if (&untie_domain_hash($hashref)) {
                   4897:                 $qresult=~s/\&$//;
                   4898:                 &Reply($client, \$qresult, $userinput);
                   4899:             } else {
                   4900:                 &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4901:                           "while attempting getdom\n",$userinput);
                   4902:             }
                   4903:         } else {
                   4904:             &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4905:                      "while attempting getdom\n",$userinput);
                   4906:         }
                   4907:     }
                   4908: 
                   4909:     return 1;
                   4910: }
                   4911: &register_handler("getdom", \&get_domain_handler, 0, 1, 0);
                   4912: 
                   4913: sub encrypted_get_domain_handler {
                   4914:     my ($cmd, $tail, $client) = @_;
                   4915: 
                   4916:     my $userinput = "$cmd:$tail";
1.348     raeburn  4917: 
                   4918:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   4919:     chomp($what);
                   4920:     my @queries=split(/\&/,$what);
                   4921:     my $qresult='';
                   4922:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
                   4923:     if ($hashref) {
                   4924:         for (my $i=0;$i<=$#queries;$i++) {
                   4925:             $qresult.="$hashref->{$queries[$i]}&";
                   4926:         }
                   4927:         if (&untie_domain_hash($hashref)) {
                   4928:             $qresult=~s/\&$//;
1.536     raeburn  4929:             if ($cipher) {
                   4930:                 my $cmdlength=length($qresult);
                   4931:                 $qresult.="         ";
                   4932:                 my $encqresult='';
                   4933:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   4934:                     $encqresult.= unpack("H16",
                   4935:                                          $cipher->encrypt(substr($qresult,
                   4936:                                                                  $encidx,
                   4937:                                                                  8)));
                   4938:                 }
                   4939:                 &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   4940:             } else {
                   4941:                 &Failure( $client, "error:no_key\n", $userinput);
                   4942:             }
1.348     raeburn  4943:         } else {
                   4944:             &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
1.536     raeburn  4945:                       "while attempting egetdom\n",$userinput);
1.348     raeburn  4946:         }
                   4947:     } else {
                   4948:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
1.536     raeburn  4949:                  "while attempting egetdom\n",$userinput);
1.348     raeburn  4950:     }
                   4951:     return 1;
                   4952: }
1.536     raeburn  4953: &register_handler("egetdom", \&encrypted_get_domain_handler, 1, 1, 0);
1.348     raeburn  4954: 
1.420     raeburn  4955: #
1.238     foxr     4956: #  Puts an id to a domains id database. 
                   4957: #
                   4958: #  Parameters:
                   4959: #   $cmd     - The command that triggered us.
                   4960: #   $tail    - Remainder of the request other than the command. This is a 
                   4961: #              colon separated list containing:
                   4962: #              $domain  - The domain for which we are writing the id.
                   4963: #              $pairs  - The id info to write... this is and & separated list
                   4964: #                        of keyword=value.
                   4965: #   $client  - Socket open on the client.
                   4966: #  Returns:
                   4967: #    1   - Continue processing.
                   4968: #  Side effects:
                   4969: #     reply is written to $client.
                   4970: #
                   4971: sub put_id_handler {
                   4972:     my ($cmd,$tail,$client) = @_;
                   4973: 
                   4974: 
                   4975:     my $userinput = "$cmd:$tail";
                   4976: 
                   4977:     my ($udom,$what)=split(/:/,$tail);
                   4978:     chomp($what);
                   4979:     my @pairs=split(/\&/,$what);
                   4980:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   4981: 				   "P", $what);
                   4982:     if ($hashref) {
                   4983: 	foreach my $pair (@pairs) {
                   4984: 	    my ($key,$value)=split(/=/,$pair);
                   4985: 	    $hashref->{$key}=$value;
                   4986: 	}
1.311     albertel 4987: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     4988: 	    &Reply($client, "ok\n", $userinput);
                   4989: 	} else {
                   4990: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4991: 		     "while attempting idput\n", $userinput);
                   4992: 	}
                   4993:     } else {
                   4994: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4995: 		  "while attempting idput\n", $userinput);
                   4996:     }
                   4997: 
                   4998:     return 1;
                   4999: }
1.263     albertel 5000: &register_handler("idput", \&put_id_handler, 0, 1, 0);
1.238     foxr     5001: 
                   5002: #
                   5003: #  Retrieves a set of id values from the id database.
                   5004: #  Returns an & separated list of results, one for each requested id to the
                   5005: #  client.
                   5006: #
                   5007: # Parameters:
                   5008: #   $cmd       - Command keyword that caused us to be dispatched.
                   5009: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5010: #               domain - the domain whose id table we dump
                   5011: #               ids      Consists of an & separated list of
                   5012: #                        id keywords whose values will be fetched.
                   5013: #                        nonexisting keywords will have an empty value.
                   5014: #   $client    - Socket open on the client.
                   5015: #
                   5016: # Returns:
                   5017: #    1 - indicating processing should continue.
                   5018: # Side effects:
                   5019: #   An & separated list of results is written to $client.
                   5020: #
                   5021: sub get_id_handler {
                   5022:     my ($cmd, $tail, $client) = @_;
                   5023: 
                   5024:     
                   5025:     my $userinput = "$client:$tail";
                   5026:     
                   5027:     my ($udom,$what)=split(/:/,$tail);
                   5028:     chomp($what);
                   5029:     my @queries=split(/\&/,$what);
                   5030:     my $qresult='';
                   5031:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
                   5032:     if ($hashref) {
                   5033: 	for (my $i=0;$i<=$#queries;$i++) {
                   5034: 	    $qresult.="$hashref->{$queries[$i]}&";
                   5035: 	}
1.311     albertel 5036: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     5037: 	    $qresult=~s/\&$//;
1.387     albertel 5038: 	    &Reply($client, \$qresult, $userinput);
1.238     foxr     5039: 	} else {
                   5040: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5041: 		      "while attempting idget\n",$userinput);
                   5042: 	}
                   5043:     } else {
                   5044: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5045: 		 "while attempting idget\n",$userinput);
                   5046:     }
                   5047:     
                   5048:     return 1;
                   5049: }
1.263     albertel 5050: &register_handler("idget", \&get_id_handler, 0, 1, 0);
1.238     foxr     5051: 
1.501     raeburn  5052: #   Deletes one or more ids in a domain's id database.
                   5053: #
                   5054: #   Parameters:
                   5055: #       $cmd                  - Command keyword (iddel).
                   5056: #       $tail                 - Command tail.  In this case a colon
                   5057: #                               separated list containing:
                   5058: #                               The domain for which we are deleting the id(s).
                   5059: #                               &-separated list of id(s) to delete.
                   5060: #       $client               - File open on client socket.
                   5061: # Returns:
                   5062: #     1   - Continue processing
                   5063: #     0   - Exit server.
                   5064: #     
                   5065: #
                   5066: 
                   5067: sub del_id_handler {
                   5068:     my ($cmd,$tail,$client) = @_;
                   5069: 
                   5070:     my $userinput = "$cmd:$tail";
                   5071: 
                   5072:     my ($udom,$what)=split(/:/,$tail);
                   5073:     chomp($what);
                   5074:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   5075:                                    "D", $what);
                   5076:     if ($hashref) {
                   5077:         my @keys=split(/\&/,$what);
                   5078:         foreach my $key (@keys) {
                   5079:             delete($hashref->{$key});
                   5080:         }
                   5081:         if (&untie_user_hash($hashref)) {
                   5082:             &Reply($client, "ok\n", $userinput);
                   5083:         } else {
                   5084:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5085:                     "while attempting iddel\n", $userinput);
                   5086:         }
                   5087:     } else {
                   5088:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5089:                  "while attempting iddel\n", $userinput);
                   5090:     }
                   5091:     return 1;
                   5092: }
                   5093: &register_handler("iddel", \&del_id_handler, 0, 1, 0);
                   5094: 
1.238     foxr     5095: #
1.299     raeburn  5096: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
                   5097: #
                   5098: # Parameters
                   5099: #   $cmd       - Command keyword that caused us to be dispatched.
                   5100: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5101: #               domain - the domain whose dcmail we are recording
                   5102: #               email    Consists of key=value pair 
                   5103: #                        where key is unique msgid
                   5104: #                        and value is message (in XML)
                   5105: #   $client    - Socket open on the client.
                   5106: #
                   5107: # Returns:
                   5108: #    1 - indicating processing should continue.
                   5109: # Side effects
                   5110: #     reply is written to $client.
                   5111: #
                   5112: sub put_dcmail_handler {
                   5113:     my ($cmd,$tail,$client) = @_;
                   5114:     my $userinput = "$cmd:$tail";
1.463     foxr     5115: 
                   5116: 
1.299     raeburn  5117:     my ($udom,$what)=split(/:/,$tail);
                   5118:     chomp($what);
                   5119:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5120:     if ($hashref) {
                   5121:         my ($key,$value)=split(/=/,$what);
                   5122:         $hashref->{$key}=$value;
                   5123:     }
1.311     albertel 5124:     if (&untie_domain_hash($hashref)) {
1.299     raeburn  5125:         &Reply($client, "ok\n", $userinput);
                   5126:     } else {
                   5127:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5128:                  "while attempting dcmailput\n", $userinput);
                   5129:     }
                   5130:     return 1;
                   5131: }
                   5132: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
                   5133: 
                   5134: #
                   5135: # Retrieves broadcast e-mail from nohist_dcmail database
                   5136: # Returns to client an & separated list of key=value pairs,
                   5137: # where key is msgid and value is message information.
                   5138: #
                   5139: # Parameters
                   5140: #   $cmd       - Command keyword that caused us to be dispatched.
                   5141: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5142: #               domain - the domain whose dcmail table we dump
                   5143: #               startfilter - beginning of time window 
                   5144: #               endfilter - end of time window
                   5145: #               sendersfilter - & separated list of username:domain 
                   5146: #                 for senders to search for.
                   5147: #   $client    - Socket open on the client.
                   5148: #
                   5149: # Returns:
                   5150: #    1 - indicating processing should continue.
                   5151: # Side effects
                   5152: #     reply (& separated list of msgid=messageinfo pairs) is 
                   5153: #     written to $client.
                   5154: #
                   5155: sub dump_dcmail_handler {
                   5156:     my ($cmd, $tail, $client) = @_;
                   5157:                                                                                 
                   5158:     my $userinput = "$cmd:$tail";
                   5159:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
                   5160:     chomp($sendersfilter);
                   5161:     my @senders = ();
                   5162:     if (defined($startfilter)) {
                   5163:         $startfilter=&unescape($startfilter);
                   5164:     } else {
                   5165:         $startfilter='.';
                   5166:     }
                   5167:     if (defined($endfilter)) {
                   5168:         $endfilter=&unescape($endfilter);
                   5169:     } else {
                   5170:         $endfilter='.';
                   5171:     }
                   5172:     if (defined($sendersfilter)) {
                   5173:         $sendersfilter=&unescape($sendersfilter);
1.300     albertel 5174: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
1.299     raeburn  5175:     }
                   5176: 
                   5177:     my $qresult='';
                   5178:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5179:     if ($hashref) {
                   5180:         while (my ($key,$value) = each(%$hashref)) {
                   5181:             my $match = 1;
1.303     albertel 5182:             my ($timestamp,$subj,$uname,$udom) = 
                   5183: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
1.299     raeburn  5184:             $subj = &unescape($subj);
                   5185:             unless ($startfilter eq '.' || !defined($startfilter)) {
                   5186:                 if ($timestamp < $startfilter) {
                   5187:                     $match = 0;
                   5188:                 }
                   5189:             }
                   5190:             unless ($endfilter eq '.' || !defined($endfilter)) {
                   5191:                 if ($timestamp > $endfilter) {
                   5192:                     $match = 0;
                   5193:                 }
                   5194:             }
                   5195:             unless (@senders < 1) {
                   5196:                 unless (grep/^$uname:$udom$/,@senders) {
                   5197:                     $match = 0;
                   5198:                 }
                   5199:             }
                   5200:             if ($match == 1) {
                   5201:                 $qresult.=$key.'='.$value.'&';
                   5202:             }
                   5203:         }
1.311     albertel 5204:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5205:             chop($qresult);
1.387     albertel 5206:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5207:         } else {
                   5208:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5209:                     "while attempting dcmaildump\n", $userinput);
                   5210:         }
                   5211:     } else {
                   5212:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5213:                 "while attempting dcmaildump\n", $userinput);
                   5214:     }
                   5215:     return 1;
                   5216: }
                   5217: 
                   5218: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
                   5219: 
                   5220: #
                   5221: # Puts domain roles in nohist_domainroles database
                   5222: #
                   5223: # Parameters
                   5224: #   $cmd       - Command keyword that caused us to be dispatched.
                   5225: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5226: #               domain - the domain whose roles we are recording  
                   5227: #               role -   Consists of key=value pair
                   5228: #                        where key is unique role
                   5229: #                        and value is start/end date information
                   5230: #   $client    - Socket open on the client.
                   5231: #
                   5232: # Returns:
                   5233: #    1 - indicating processing should continue.
                   5234: # Side effects
                   5235: #     reply is written to $client.
                   5236: #
                   5237: 
                   5238: sub put_domainroles_handler {
                   5239:     my ($cmd,$tail,$client) = @_;
                   5240: 
                   5241:     my $userinput = "$cmd:$tail";
                   5242:     my ($udom,$what)=split(/:/,$tail);
                   5243:     chomp($what);
                   5244:     my @pairs=split(/\&/,$what);
                   5245:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5246:     if ($hashref) {
                   5247:         foreach my $pair (@pairs) {
                   5248:             my ($key,$value)=split(/=/,$pair);
                   5249:             $hashref->{$key}=$value;
                   5250:         }
1.311     albertel 5251:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5252:             &Reply($client, "ok\n", $userinput);
                   5253:         } else {
                   5254:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5255:                      "while attempting domroleput\n", $userinput);
                   5256:         }
                   5257:     } else {
                   5258:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5259:                   "while attempting domroleput\n", $userinput);
                   5260:     }
                   5261:                                                                                   
                   5262:     return 1;
                   5263: }
                   5264: 
                   5265: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
                   5266: 
                   5267: #
                   5268: # Retrieves domain roles from nohist_domainroles database
                   5269: # Returns to client an & separated list of key=value pairs,
                   5270: # where key is role and value is start and end date information.
                   5271: #
                   5272: # Parameters
                   5273: #   $cmd       - Command keyword that caused us to be dispatched.
                   5274: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5275: #               domain - the domain whose domain roles table we dump
                   5276: #   $client    - Socket open on the client.
                   5277: #
                   5278: # Returns:
                   5279: #    1 - indicating processing should continue.
                   5280: # Side effects
                   5281: #     reply (& separated list of role=start/end info pairs) is
                   5282: #     written to $client.
                   5283: #
                   5284: sub dump_domainroles_handler {
                   5285:     my ($cmd, $tail, $client) = @_;
                   5286:                                                                                            
                   5287:     my $userinput = "$cmd:$tail";
                   5288:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
                   5289:     chomp($rolesfilter);
                   5290:     my @roles = ();
                   5291:     if (defined($startfilter)) {
                   5292:         $startfilter=&unescape($startfilter);
                   5293:     } else {
                   5294:         $startfilter='.';
                   5295:     }
                   5296:     if (defined($endfilter)) {
                   5297:         $endfilter=&unescape($endfilter);
                   5298:     } else {
                   5299:         $endfilter='.';
                   5300:     }
                   5301:     if (defined($rolesfilter)) {
                   5302:         $rolesfilter=&unescape($rolesfilter);
1.300     albertel 5303: 	@roles = split(/\&/,$rolesfilter);
1.299     raeburn  5304:     }
1.421     raeburn  5305: 
1.299     raeburn  5306:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5307:     if ($hashref) {
                   5308:         my $qresult = '';
                   5309:         while (my ($key,$value) = each(%$hashref)) {
                   5310:             my $match = 1;
1.421     raeburn  5311:             my ($end,$start) = split(/:/,&unescape($value));
1.299     raeburn  5312:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
1.421     raeburn  5313:             unless (@roles < 1) {
                   5314:                 unless (grep/^\Q$trole\E$/,@roles) {
                   5315:                     $match = 0;
                   5316:                     next;
                   5317:                 }
                   5318:             }
1.299     raeburn  5319:             unless ($startfilter eq '.' || !defined($startfilter)) {
1.415     raeburn  5320:                 if ((defined($start)) && ($start >= $startfilter)) {
1.299     raeburn  5321:                     $match = 0;
1.421     raeburn  5322:                     next;
1.299     raeburn  5323:                 }
                   5324:             }
                   5325:             unless ($endfilter eq '.' || !defined($endfilter)) {
1.421     raeburn  5326:                 if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
1.299     raeburn  5327:                     $match = 0;
1.421     raeburn  5328:                     next;
1.299     raeburn  5329:                 }
                   5330:             }
                   5331:             if ($match == 1) {
                   5332:                 $qresult.=$key.'='.$value.'&';
                   5333:             }
                   5334:         }
1.311     albertel 5335:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5336:             chop($qresult);
1.387     albertel 5337:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5338:         } else {
                   5339:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5340:                     "while attempting domrolesdump\n", $userinput);
                   5341:         }
                   5342:     } else {
                   5343:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5344:                 "while attempting domrolesdump\n", $userinput);
                   5345:     }
                   5346:     return 1;
                   5347: }
                   5348: 
                   5349: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
                   5350: 
                   5351: 
1.238     foxr     5352: #  Process the tmpput command I'm not sure what this does.. Seems to
                   5353: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
                   5354: # where Id is the client's ip concatenated with a sequence number.
                   5355: # The file will contain some value that is passed in.  Is this e.g.
                   5356: # a login token?
                   5357: #
                   5358: # Parameters:
                   5359: #    $cmd     - The command that got us dispatched.
                   5360: #    $tail    - The remainder of the request following $cmd:
                   5361: #               In this case this will be the contents of the file.
                   5362: #    $client  - Socket connected to the client.
                   5363: # Returns:
                   5364: #    1 indicating processing can continue.
                   5365: # Side effects:
                   5366: #   A file is created in the local filesystem.
                   5367: #   A reply is sent to the client.
                   5368: sub tmp_put_handler {
                   5369:     my ($cmd, $what, $client) = @_;
                   5370: 
                   5371:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
                   5372: 
1.347     raeburn  5373:     my ($record,$context) = split(/:/,$what);
                   5374:     if ($context ne '') {
                   5375:         chomp($context);
                   5376:         $context = &unescape($context);
                   5377:     }
                   5378:     my ($id,$store);
1.238     foxr     5379:     $tmpsnum++;
1.454     raeburn  5380:     if (($context eq 'resetpw') || ($context eq 'createaccount')) {
1.347     raeburn  5381:         $id = &md5_hex(&md5_hex(time.{}.rand().$$));
                   5382:     } else {
                   5383:         $id = $$.'_'.$clientip.'_'.$tmpsnum;
                   5384:     }
1.238     foxr     5385:     $id=~s/\W/\_/g;
1.347     raeburn  5386:     $record=~s/\n//g;
1.238     foxr     5387:     my $execdir=$perlvar{'lonDaemons'};
                   5388:     if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
1.347     raeburn  5389: 	print $store $record;
1.238     foxr     5390: 	close $store;
1.387     albertel 5391: 	&Reply($client, \$id, $userinput);
1.238     foxr     5392:     } else {
                   5393: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5394: 		  "while attempting tmpput\n", $userinput);
                   5395:     }
                   5396:     return 1;
                   5397:   
                   5398: }
                   5399: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263     albertel 5400: 
1.238     foxr     5401: #   Processes the tmpget command.  This command returns the contents
                   5402: #  of a temporary resource file(?) created via tmpput.
                   5403: #
                   5404: # Paramters:
                   5405: #    $cmd      - Command that got us dispatched.
                   5406: #    $id       - Tail of the command, contain the id of the resource
                   5407: #                we want to fetch.
                   5408: #    $client   - socket open on the client.
                   5409: # Return:
                   5410: #    1         - Inidcating processing can continue.
                   5411: # Side effects:
                   5412: #   A reply is sent to the client.
                   5413: #
                   5414: sub tmp_get_handler {
                   5415:     my ($cmd, $id, $client) = @_;
                   5416: 
                   5417:     my $userinput = "$cmd:$id"; 
                   5418:     
                   5419: 
                   5420:     $id=~s/\W/\_/g;
                   5421:     my $store;
                   5422:     my $execdir=$perlvar{'lonDaemons'};
                   5423:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
                   5424: 	my $reply=<$store>;
1.387     albertel 5425: 	&Reply( $client, \$reply, $userinput);
1.238     foxr     5426: 	close $store;
                   5427:     } else {
                   5428: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5429: 		  "while attempting tmpget\n", $userinput);
                   5430:     }
                   5431: 
                   5432:     return 1;
                   5433: }
                   5434: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263     albertel 5435: 
1.238     foxr     5436: #
                   5437: #  Process the tmpdel command.  This command deletes a temp resource
                   5438: #  created by the tmpput command.
                   5439: #
                   5440: # Parameters:
                   5441: #   $cmd      - Command that got us here.
                   5442: #   $id       - Id of the temporary resource created.
                   5443: #   $client   - socket open on the client process.
                   5444: #
                   5445: # Returns:
                   5446: #   1     - Indicating processing should continue.
                   5447: # Side Effects:
                   5448: #   A file is deleted
                   5449: #   A reply is sent to the client.
                   5450: sub tmp_del_handler {
                   5451:     my ($cmd, $id, $client) = @_;
                   5452:     
                   5453:     my $userinput= "$cmd:$id";
                   5454:     
                   5455:     chomp($id);
                   5456:     $id=~s/\W/\_/g;
                   5457:     my $execdir=$perlvar{'lonDaemons'};
                   5458:     if (unlink("$execdir/tmp/$id.tmp")) {
                   5459: 	&Reply($client, "ok\n", $userinput);
                   5460:     } else {
                   5461: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
                   5462: 		  "while attempting tmpdel\n", $userinput);
                   5463:     }
                   5464:     
                   5465:     return 1;
                   5466: 
                   5467: }
                   5468: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263     albertel 5469: 
1.238     foxr     5470: #
1.246     foxr     5471: #   Processes the setannounce command.  This command
                   5472: #   creates a file named announce.txt in the top directory of
                   5473: #   the documentn root and sets its contents.  The announce.txt file is
                   5474: #   printed in its entirety at the LonCAPA login page.  Note:
                   5475: #   once the announcement.txt fileis created it cannot be deleted.
                   5476: #   However, setting the contents of the file to empty removes the
                   5477: #   announcement from the login page of loncapa so who cares.
                   5478: #
                   5479: # Parameters:
                   5480: #    $cmd          - The command that got us dispatched.
                   5481: #    $announcement - The text of the announcement.
                   5482: #    $client       - Socket open on the client process.
                   5483: # Retunrns:
                   5484: #   1             - Indicating request processing should continue
                   5485: # Side Effects:
                   5486: #   The file {DocRoot}/announcement.txt is created.
                   5487: #   A reply is sent to $client.
                   5488: #
                   5489: sub set_announce_handler {
                   5490:     my ($cmd, $announcement, $client) = @_;
                   5491:   
                   5492:     my $userinput    = "$cmd:$announcement";
                   5493: 
                   5494:     chomp($announcement);
                   5495:     $announcement=&unescape($announcement);
                   5496:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
                   5497: 				'/announcement.txt')) {
                   5498: 	print $store $announcement;
                   5499: 	close $store;
                   5500: 	&Reply($client, "ok\n", $userinput);
                   5501:     } else {
                   5502: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
                   5503:     }
                   5504: 
                   5505:     return 1;
                   5506: }
                   5507: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263     albertel 5508: 
1.246     foxr     5509: #
                   5510: #  Return the version of the daemon.  This can be used to determine
                   5511: #  the compatibility of cross version installations or, alternatively to
                   5512: #  simply know who's out of date and who isn't.  Note that the version
                   5513: #  is returned concatenated with the tail.
                   5514: # Parameters:
                   5515: #   $cmd        - the request that dispatched to us.
                   5516: #   $tail       - Tail of the request (client's version?).
                   5517: #   $client     - Socket open on the client.
                   5518: #Returns:
                   5519: #   1 - continue processing requests.
                   5520: # Side Effects:
                   5521: #   Replies with version to $client.
                   5522: sub get_version_handler {
                   5523:     my ($cmd, $tail, $client) = @_;
                   5524: 
                   5525:     my $userinput  = $cmd.$tail;
                   5526:     
                   5527:     &Reply($client, &version($userinput)."\n", $userinput);
                   5528: 
                   5529: 
                   5530:     return 1;
                   5531: }
                   5532: &register_handler("version", \&get_version_handler, 0, 1, 0);
1.263     albertel 5533: 
1.246     foxr     5534: #  Set the current host and domain.  This is used to support
                   5535: #  multihomed systems.  Each IP of the system, or even separate daemons
                   5536: #  on the same IP can be treated as handling a separate lonCAPA virtual
                   5537: #  machine.  This command selects the virtual lonCAPA.  The client always
                   5538: #  knows the right one since it is lonc and it is selecting the domain/system
                   5539: #  from the hosts.tab file.
                   5540: # Parameters:
                   5541: #    $cmd      - Command that dispatched us.
                   5542: #    $tail     - Tail of the command (domain/host requested).
                   5543: #    $socket   - Socket open on the client.
                   5544: #
                   5545: # Returns:
                   5546: #     1   - Indicates the program should continue to process requests.
                   5547: # Side-effects:
                   5548: #     The default domain/system context is modified for this daemon.
                   5549: #     a reply is sent to the client.
                   5550: #
                   5551: sub set_virtual_host_handler {
                   5552:     my ($cmd, $tail, $socket) = @_;
                   5553:   
                   5554:     my $userinput  ="$cmd:$tail";
                   5555: 
                   5556:     &Reply($client, &sethost($userinput)."\n", $userinput);
                   5557: 
                   5558: 
                   5559:     return 1;
                   5560: }
1.247     albertel 5561: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246     foxr     5562: 
                   5563: #  Process a request to exit:
                   5564: #   - "bye" is sent to the client.
                   5565: #   - The client socket is shutdown and closed.
                   5566: #   - We indicate to the caller that we should exit.
                   5567: # Formal Parameters:
                   5568: #   $cmd                - The command that got us here.
                   5569: #   $tail               - Tail of the command (empty).
                   5570: #   $client             - Socket open on the tail.
                   5571: # Returns:
                   5572: #   0      - Indicating the program should exit!!
                   5573: #
                   5574: sub exit_handler {
                   5575:     my ($cmd, $tail, $client) = @_;
                   5576: 
                   5577:     my $userinput = "$cmd:$tail";
                   5578: 
                   5579:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
                   5580:     &Reply($client, "bye\n", $userinput);
                   5581:     $client->shutdown(2);        # shutdown the socket forcibly.
                   5582:     $client->close();
                   5583: 
                   5584:     return 0;
                   5585: }
1.248     foxr     5586: &register_handler("exit", \&exit_handler, 0,1,1);
                   5587: &register_handler("init", \&exit_handler, 0,1,1);
                   5588: &register_handler("quit", \&exit_handler, 0,1,1);
                   5589: 
                   5590: #  Determine if auto-enrollment is enabled.
                   5591: #  Note that the original had what I believe to be a defect.
                   5592: #  The original returned 0 if the requestor was not a registerd client.
                   5593: #  It should return "refused".
                   5594: # Formal Parameters:
                   5595: #   $cmd       - The command that invoked us.
                   5596: #   $tail      - The tail of the command (Extra command parameters.
                   5597: #   $client    - The socket open on the client that issued the request.
                   5598: # Returns:
                   5599: #    1         - Indicating processing should continue.
                   5600: #
                   5601: sub enrollment_enabled_handler {
                   5602:     my ($cmd, $tail, $client) = @_;
                   5603:     my $userinput = $cmd.":".$tail; # For logging purposes.
                   5604: 
                   5605:     
1.337     albertel 5606:     my ($cdom) = split(/:/, $tail, 2);   # Domain we're asking about.
                   5607: 
1.248     foxr     5608:     my $outcome  = &localenroll::run($cdom);
1.387     albertel 5609:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5610: 
                   5611:     return 1;
                   5612: }
                   5613: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
                   5614: 
1.417     raeburn  5615: #
1.423     raeburn  5616: #   Validate an institutional code used for a LON-CAPA course.          
1.417     raeburn  5617: #
                   5618: # Formal Parameters:
                   5619: #   $cmd          - The command request that got us dispatched.
                   5620: #   $tail         - The tail of the command.  In this case,
                   5621: #                   this is a colon separated set of words that will be split
                   5622: #                   into:
1.424     raeburn  5623: #                        $dom      - The domain for which the check of 
                   5624: #                                    institutional course code will occur.
                   5625: #
                   5626: #                        $instcode - The institutional code for the course
                   5627: #                                    being requested, or validated for rights
                   5628: #                                    to request.
                   5629: #
                   5630: #                        $owner    - The course requestor (who will be the
                   5631: #                                    course owner, in the form username:domain
                   5632: #
1.417     raeburn  5633: #   $client       - Socket open on the client.
                   5634: # Returns:
                   5635: #    1           - Indicating processing should continue.
                   5636: #
                   5637: sub validate_instcode_handler {
                   5638:     my ($cmd, $tail, $client) = @_;
                   5639:     my $userinput = "$cmd:$tail";
1.423     raeburn  5640:     my ($dom,$instcode,$owner) = split(/:/, $tail);
1.422     raeburn  5641:     $instcode = &unescape($instcode);
                   5642:     $owner = &unescape($owner);
1.498     raeburn  5643:     my ($outcome,$description,$credits) = 
1.426     raeburn  5644:         &localenroll::validate_instcode($dom,$instcode,$owner);
1.498     raeburn  5645:     my $result = &escape($outcome).'&'.&escape($description).'&'.
                   5646:                  &escape($credits);
1.426     raeburn  5647:     &Reply($client, \$result, $userinput);
1.417     raeburn  5648: 
                   5649:     return 1;
                   5650: }
                   5651: &register_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
                   5652: 
1.248     foxr     5653: #   Get the official sections for which auto-enrollment is possible.
                   5654: #   Since the admin people won't know about 'unofficial sections' 
                   5655: #   we cannot auto-enroll on them.
                   5656: # Formal Parameters:
                   5657: #    $cmd     - The command request that got us dispatched here.
                   5658: #    $tail    - The remainder of the request.  In our case this
                   5659: #               will be split into:
                   5660: #               $coursecode   - The course name from the admin point of view.
                   5661: #               $cdom         - The course's domain(?).
                   5662: #    $client  - Socket open on the client.
                   5663: # Returns:
                   5664: #    1    - Indiciting processing should continue.
                   5665: #
                   5666: sub get_sections_handler {
                   5667:     my ($cmd, $tail, $client) = @_;
                   5668:     my $userinput = "$cmd:$tail";
                   5669: 
                   5670:     my ($coursecode, $cdom) = split(/:/, $tail);
                   5671:     my @secs = &localenroll::get_sections($coursecode,$cdom);
                   5672:     my $seclist = &escape(join(':',@secs));
                   5673: 
1.387     albertel 5674:     &Reply($client, \$seclist, $userinput);
1.248     foxr     5675:     
                   5676: 
                   5677:     return 1;
                   5678: }
                   5679: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
                   5680: 
                   5681: #   Validate the owner of a new course section.  
                   5682: #
                   5683: # Formal Parameters:
                   5684: #   $cmd      - Command that got us dispatched.
                   5685: #   $tail     - the remainder of the command.  For us this consists of a
                   5686: #               colon separated string containing:
                   5687: #                  $inst    - Course Id from the institutions point of view.
                   5688: #                  $owner   - Proposed owner of the course.
                   5689: #                  $cdom    - Domain of the course (from the institutions
                   5690: #                             point of view?)..
                   5691: #   $client   - Socket open on the client.
                   5692: #
                   5693: # Returns:
                   5694: #   1        - Processing should continue.
                   5695: #
                   5696: sub validate_course_owner_handler {
                   5697:     my ($cmd, $tail, $client)  = @_;
                   5698:     my $userinput = "$cmd:$tail";
1.470     raeburn  5699:     my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
                   5700:     
1.336     raeburn  5701:     $owner = &unescape($owner);
1.470     raeburn  5702:     $coowners = &unescape($coowners);
                   5703:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
1.387     albertel 5704:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5705: 
                   5706: 
                   5707: 
                   5708:     return 1;
                   5709: }
                   5710: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263     albertel 5711: 
1.248     foxr     5712: #
                   5713: #   Validate a course section in the official schedule of classes
                   5714: #   from the institutions point of view (part of autoenrollment).
                   5715: #
                   5716: # Formal Parameters:
                   5717: #   $cmd          - The command request that got us dispatched.
                   5718: #   $tail         - The tail of the command.  In this case,
                   5719: #                   this is a colon separated set of words that will be split
                   5720: #                   into:
                   5721: #                        $inst_course_id - The course/section id from the
                   5722: #                                          institutions point of view.
                   5723: #                        $cdom           - The domain from the institutions
                   5724: #                                          point of view.
                   5725: #   $client       - Socket open on the client.
                   5726: # Returns:
                   5727: #    1           - Indicating processing should continue.
                   5728: #
                   5729: sub validate_course_section_handler {
                   5730:     my ($cmd, $tail, $client) = @_;
                   5731:     my $userinput = "$cmd:$tail";
                   5732:     my ($inst_course_id, $cdom) = split(/:/, $tail);
                   5733: 
                   5734:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
1.387     albertel 5735:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5736: 
                   5737: 
                   5738:     return 1;
                   5739: }
                   5740: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
                   5741: 
                   5742: #
1.340     raeburn  5743: #   Validate course owner's access to enrollment data for specific class section. 
                   5744: #   
                   5745: #
                   5746: # Formal Parameters:
                   5747: #    $cmd     - The command request that got us dispatched.
                   5748: #    $tail    - The tail of the command.   In this case this is a colon separated
                   5749: #               set of words that will be split into:
                   5750: #               $inst_class  - Institutional code for the specific class section   
                   5751: #               $courseowner - The escaped username:domain of the course owner 
                   5752: #               $cdom        - The domain of the course from the institution's
                   5753: #                              point of view.
                   5754: #    $client  - The socket open on the client.
                   5755: # Returns:
                   5756: #    1 - continue processing.
                   5757: #
                   5758: 
                   5759: sub validate_class_access_handler {
                   5760:     my ($cmd, $tail, $client) = @_;
                   5761:     my $userinput = "$cmd:$tail";
1.383     raeburn  5762:     my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
1.392     raeburn  5763:     my $owners = &unescape($ownerlist);
1.341     albertel 5764:     my $outcome;
                   5765:     eval {
                   5766: 	local($SIG{__DIE__})='DEFAULT';
1.392     raeburn  5767: 	$outcome=&localenroll::check_section($inst_class,$owners,$cdom);
1.341     albertel 5768:     };
1.387     albertel 5769:     &Reply($client,\$outcome, $userinput);
1.340     raeburn  5770: 
                   5771:     return 1;
                   5772: }
                   5773: &register_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
                   5774: 
                   5775: #
                   5776: #   Create a password for a new LON-CAPA user added by auto-enrollment.
                   5777: #   Only used for case where authentication method for new user is localauth
1.248     foxr     5778: #
                   5779: # Formal Parameters:
                   5780: #    $cmd     - The command request that got us dispatched.
                   5781: #    $tail    - The tail of the command.   In this case this is a colon separated
                   5782: #               set of words that will be split into:
1.340     raeburn  5783: #               $authparam - An authentication parameter (localauth parameter).
1.248     foxr     5784: #               $cdom      - The domain of the course from the institution's
                   5785: #                            point of view.
                   5786: #    $client  - The socket open on the client.
                   5787: # Returns:
                   5788: #    1 - continue processing.
                   5789: #
                   5790: sub create_auto_enroll_password_handler {
                   5791:     my ($cmd, $tail, $client) = @_;
                   5792:     my $userinput = "$cmd:$tail";
                   5793: 
                   5794:     my ($authparam, $cdom) = split(/:/, $userinput);
                   5795: 
                   5796:     my ($create_passwd,$authchk);
                   5797:     ($authparam,
                   5798:      $create_passwd,
                   5799:      $authchk) = &localenroll::create_password($authparam,$cdom);
                   5800: 
                   5801:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
                   5802: 	   $userinput);
                   5803: 
                   5804: 
                   5805:     return 1;
                   5806: }
                   5807: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
                   5808: 		  0, 1, 0);
                   5809: 
1.522     raeburn  5810: sub auto_export_grades_handler {
                   5811:     my ($cmd, $tail, $client) = @_;
                   5812:     my $userinput = "$cmd:$tail";
                   5813:     my ($cdom,$cnum,$info,$data) = split(/:/,$tail);
                   5814:     my $inforef = &Apache::lonnet::thaw_unescape($info);
                   5815:     my $dataref = &Apache::lonnet::thaw_unescape($data);
                   5816:     my ($outcome,$result);;
                   5817:     eval {
                   5818:         local($SIG{__DIE__})='DEFAULT';
                   5819:         my %rtnhash;
                   5820:         $outcome=&localenroll::export_grades($cdom,$cnum,$inforef,$dataref,\%rtnhash);
                   5821:         if ($outcome eq 'ok') {
                   5822:             foreach my $key (keys(%rtnhash)) {
                   5823:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   5824:             }
                   5825:             $result =~ s/\&$//;
                   5826:         }
                   5827:     };
                   5828:     if (!$@) {
                   5829:         if ($outcome eq 'ok') {
                   5830:             if ($cipher) {
                   5831:                 my $cmdlength=length($result);
                   5832:                 $result.="         ";
                   5833:                 my $encresult='';
                   5834:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   5835:                     $encresult.= unpack("H16",
                   5836:                                         $cipher->encrypt(substr($result,
                   5837:                                                                 $encidx,
                   5838:                                                                 8)));
                   5839:                 }
                   5840:                 &Reply( $client, "enc:$cmdlength:$encresult\n", $userinput);
                   5841:             } else {
                   5842:                 &Failure( $client, "error:no_key\n", $userinput);
                   5843:             }
                   5844:         } else {
                   5845:             &Reply($client, "$outcome\n", $userinput);
                   5846:         }
                   5847:     } else {
                   5848:         &Failure($client,"export_error\n",$userinput);
                   5849:     }
                   5850:     return 1;
                   5851: }
                   5852: &register_handler("autoexportgrades", \&auto_export_grades_handler,
1.536     raeburn  5853:                   1, 1, 0);
1.522     raeburn  5854: 
1.248     foxr     5855: #   Retrieve and remove temporary files created by/during autoenrollment.
                   5856: #
                   5857: # Formal Parameters:
                   5858: #    $cmd      - The command that got us dispatched.
                   5859: #    $tail     - The tail of the command.  In our case this is a colon 
                   5860: #                separated list that will be split into:
1.526     raeburn  5861: #                $filename - The name of the file to retrieve.
1.248     foxr     5862: #                            The filename is given as a path relative to
                   5863: #                            the LonCAPA temp file directory.
                   5864: #    $client   - Socket open on the client.
                   5865: #
                   5866: # Returns:
                   5867: #   1     - Continue processing.
                   5868: sub retrieve_auto_file_handler {
                   5869:     my ($cmd, $tail, $client)    = @_;
                   5870:     my $userinput                = "cmd:$tail";
                   5871: 
                   5872:     my ($filename)   = split(/:/, $tail);
                   5873: 
                   5874:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
1.521     raeburn  5875: 
                   5876:     if ($filename =~m{/\.\./}) {
                   5877:         &Failure($client, "refused\n", $userinput);
1.526     raeburn  5878:     } elsif ($filename !~ /^$LONCAPA::match_domain\_$LONCAPA::match_courseid\_.+_classlist\.xml$/) {
                   5879:         &Failure($client, "refused\n", $userinput);
1.521     raeburn  5880:     } elsif ( (-e $source) && ($filename ne '') ) {
1.248     foxr     5881: 	my $reply = '';
                   5882: 	if (open(my $fh,$source)) {
                   5883: 	    while (<$fh>) {
                   5884: 		chomp($_);
                   5885: 		$_ =~ s/^\s+//g;
                   5886: 		$_ =~ s/\s+$//g;
                   5887: 		$reply .= $_;
                   5888: 	    }
                   5889: 	    close($fh);
                   5890: 	    &Reply($client, &escape($reply)."\n", $userinput);
                   5891: 
                   5892: #   Does this have to be uncommented??!?  (RF).
                   5893: #
                   5894: #                                unlink($source);
                   5895: 	} else {
                   5896: 	    &Failure($client, "error\n", $userinput);
                   5897: 	}
                   5898:     } else {
                   5899: 	&Failure($client, "error\n", $userinput);
                   5900:     }
                   5901:     
                   5902: 
                   5903:     return 1;
                   5904: }
                   5905: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
                   5906: 
1.423     raeburn  5907: sub crsreq_checks_handler {
                   5908:     my ($cmd, $tail, $client) = @_;
                   5909:     my $userinput = "$cmd:$tail";
                   5910:     my $dom = $tail;
                   5911:     my $result;
1.519     raeburn  5912:     my @reqtypes = ('official','unofficial','community','textbook','placement');
1.423     raeburn  5913:     eval {
                   5914:         local($SIG{__DIE__})='DEFAULT';
                   5915:         my %validations;
1.424     raeburn  5916:         my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
                   5917:                                                    \%validations);
1.423     raeburn  5918:         if ($response eq 'ok') { 
                   5919:             foreach my $key (keys(%validations)) {
                   5920:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   5921:             }
                   5922:             $result =~ s/\&$//;
                   5923:         } else {
                   5924:             $result = 'error';
                   5925:         }
                   5926:     };
                   5927:     if (!$@) {
                   5928:         &Reply($client, \$result, $userinput);
                   5929:     } else {
                   5930:         &Failure($client,"unknown_cmd\n",$userinput);
                   5931:     }
                   5932:     return 1;
                   5933: }
                   5934: &register_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
                   5935: 
                   5936: sub validate_crsreq_handler {
                   5937:     my ($cmd, $tail, $client) = @_;
                   5938:     my $userinput = "$cmd:$tail";
1.508     raeburn  5939:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
1.423     raeburn  5940:     $instcode = &unescape($instcode);
                   5941:     $owner = &unescape($owner);
                   5942:     $crstype = &unescape($crstype);
                   5943:     $inststatuslist = &unescape($inststatuslist);
                   5944:     $instcode = &unescape($instcode);
                   5945:     $instseclist = &unescape($instseclist);
1.508     raeburn  5946:     my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
1.423     raeburn  5947:     my $outcome;
                   5948:     eval {
                   5949:         local($SIG{__DIE__})='DEFAULT';
                   5950:         $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
                   5951:                                                  $inststatuslist,$instcode,
1.508     raeburn  5952:                                                  $instseclist,$custominfo);
1.423     raeburn  5953:     };
                   5954:     if (!$@) {
                   5955:         &Reply($client, \$outcome, $userinput);
                   5956:     } else {
                   5957:         &Failure($client,"unknown_cmd\n",$userinput);
                   5958:     }
                   5959:     return 1;
                   5960: }
                   5961: &register_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
                   5962: 
1.506     raeburn  5963: sub crsreq_update_handler {
                   5964:     my ($cmd, $tail, $client) = @_;
                   5965:     my $userinput = "$cmd:$tail";
1.509     raeburn  5966:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
                   5967:         $accessstart,$accessend,$infohashref) =
1.506     raeburn  5968:         split(/:/, $tail);
                   5969:     $crstype = &unescape($crstype);
                   5970:     $action = &unescape($action);
                   5971:     $ownername = &unescape($ownername);
                   5972:     $ownerdomain = &unescape($ownerdomain);
                   5973:     $fullname = &unescape($fullname);
                   5974:     $title = &unescape($title);
                   5975:     $code = &unescape($code);
1.509     raeburn  5976:     $accessstart = &unescape($accessstart);
                   5977:     $accessend = &unescape($accessend);
1.506     raeburn  5978:     my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
                   5979:     my ($result,$outcome);
                   5980:     eval {
                   5981:         local($SIG{__DIE__})='DEFAULT';
                   5982:         my %rtnhash;
                   5983:         $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
                   5984:                                                 $ownername,$ownerdomain,$fullname,
1.509     raeburn  5985:                                                 $title,$code,$accessstart,$accessend,
                   5986:                                                 $incoming,\%rtnhash);
1.506     raeburn  5987:         if ($outcome eq 'ok') {
1.515     raeburn  5988:             my @posskeys = qw(createdweb createdmsg createdcustomized createdactions queuedweb queuedmsg formitems reviewweb validationjs onload javascript);
1.506     raeburn  5989:             foreach my $key (keys(%rtnhash)) {
                   5990:                 if (grep(/^\Q$key\E/,@posskeys)) {
                   5991:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   5992:                 }
                   5993:             }
                   5994:             $result =~ s/\&$//;
                   5995:         }
                   5996:     };
                   5997:     if (!$@) {
                   5998:         if ($outcome eq 'ok') {
                   5999:             &Reply($client, \$result, $userinput);
                   6000:         } else {
                   6001:             &Reply($client, "format_error\n", $userinput);
                   6002:         }
                   6003:     } else {
                   6004:         &Failure($client,"unknown_cmd\n",$userinput);
                   6005:     }
                   6006:     return 1;
                   6007: }
                   6008: &register_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
                   6009: 
1.248     foxr     6010: #
                   6011: #   Read and retrieve institutional code format (for support form).
                   6012: # Formal Parameters:
                   6013: #    $cmd        - Command that dispatched us.
                   6014: #    $tail       - Tail of the command.  In this case it conatins 
                   6015: #                  the course domain and the coursename.
                   6016: #    $client     - Socket open on the client.
                   6017: # Returns:
                   6018: #    1     - Continue processing.
                   6019: #
                   6020: sub get_institutional_code_format_handler {
                   6021:     my ($cmd, $tail, $client)   = @_;
                   6022:     my $userinput               = "$cmd:$tail";
                   6023: 
                   6024:     my $reply;
                   6025:     my($cdom,$course) = split(/:/,$tail);
                   6026:     my @pairs = split/\&/,$course;
                   6027:     my %instcodes = ();
                   6028:     my %codes = ();
                   6029:     my @codetitles = ();
                   6030:     my %cat_titles = ();
                   6031:     my %cat_order = ();
                   6032:     foreach (@pairs) {
                   6033: 	my ($key,$value) = split/=/,$_;
                   6034: 	$instcodes{&unescape($key)} = &unescape($value);
                   6035:     }
                   6036:     my $formatreply = &localenroll::instcode_format($cdom,
                   6037: 						    \%instcodes,
                   6038: 						    \%codes,
                   6039: 						    \@codetitles,
                   6040: 						    \%cat_titles,
                   6041: 						    \%cat_order);
                   6042:     if ($formatreply eq 'ok') {
1.365     albertel 6043: 	my $codes_str = &Apache::lonnet::hash2str(%codes);
                   6044: 	my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
                   6045: 	my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
                   6046: 	my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
1.248     foxr     6047: 	&Reply($client,
                   6048: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
                   6049: 	       .$cat_order_str."\n",
                   6050: 	       $userinput);
                   6051:     } else {
                   6052: 	# this else branch added by RF since if not ok, lonc will
                   6053: 	# hang waiting on reply until timeout.
                   6054: 	#
                   6055: 	&Reply($client, "format_error\n", $userinput);
                   6056:     }
                   6057:     
                   6058:     return 1;
                   6059: }
1.265     albertel 6060: &register_handler("autoinstcodeformat",
                   6061: 		  \&get_institutional_code_format_handler,0,1,0);
1.246     foxr     6062: 
1.345     raeburn  6063: sub get_institutional_defaults_handler {
                   6064:     my ($cmd, $tail, $client)   = @_;
                   6065:     my $userinput               = "$cmd:$tail";
                   6066: 
                   6067:     my $dom = $tail;
                   6068:     my %defaults_hash;
                   6069:     my @code_order;
                   6070:     my $outcome;
                   6071:     eval {
                   6072:         local($SIG{__DIE__})='DEFAULT';
                   6073:         $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
                   6074:                                                    \@code_order);
                   6075:     };
                   6076:     if (!$@) {
                   6077:         if ($outcome eq 'ok') {
                   6078:             my $result='';
                   6079:             while (my ($key,$value) = each(%defaults_hash)) {
                   6080:                 $result.=&escape($key).'='.&escape($value).'&';
                   6081:             }
                   6082:             $result .= 'code_order='.&escape(join('&',@code_order));
1.387     albertel 6083:             &Reply($client,\$result,$userinput);
1.345     raeburn  6084:         } else {
                   6085:             &Reply($client,"error\n", $userinput);
                   6086:         }
                   6087:     } else {
                   6088:         &Failure($client,"unknown_cmd\n",$userinput);
                   6089:     }
                   6090: }
                   6091: &register_handler("autoinstcodedefaults",
                   6092:                   \&get_institutional_defaults_handler,0,1,0);
                   6093: 
1.416     raeburn  6094: sub get_possible_instcodes_handler {
                   6095:     my ($cmd, $tail, $client)   = @_;
                   6096:     my $userinput               = "$cmd:$tail";
                   6097: 
                   6098:     my $reply;
                   6099:     my $cdom = $tail;
1.417     raeburn  6100:     my (@codetitles,%cat_titles,%cat_order,@code_order);
1.416     raeburn  6101:     my $formatreply = &localenroll::possible_instcodes($cdom,
                   6102:                                                        \@codetitles,
                   6103:                                                        \%cat_titles,
1.417     raeburn  6104:                                                        \%cat_order,
                   6105:                                                        \@code_order);
1.416     raeburn  6106:     if ($formatreply eq 'ok') {
                   6107:         my $result = join('&',map {&escape($_);} (@codetitles)).':';
1.417     raeburn  6108:         $result .= join('&',map {&escape($_);} (@code_order)).':';
1.416     raeburn  6109:         foreach my $key (keys(%cat_titles)) {
                   6110:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
                   6111:         }
                   6112:         $result =~ s/\&$//;
                   6113:         $result .= ':';
                   6114:         foreach my $key (keys(%cat_order)) {
                   6115:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
                   6116:         }
                   6117:         $result =~ s/\&$//;
                   6118:         &Reply($client,\$result,$userinput);
                   6119:     } else {
                   6120:         &Reply($client, "format_error\n", $userinput);
                   6121:     }
                   6122:     return 1;
                   6123: }
                   6124: &register_handler("autopossibleinstcodes",
                   6125:                   \&get_possible_instcodes_handler,0,1,0);
                   6126: 
1.381     raeburn  6127: sub get_institutional_user_rules {
                   6128:     my ($cmd, $tail, $client)   = @_;
                   6129:     my $userinput               = "$cmd:$tail";
                   6130:     my $dom = &unescape($tail);
                   6131:     my (%rules_hash,@rules_order);
                   6132:     my $outcome;
                   6133:     eval {
                   6134:         local($SIG{__DIE__})='DEFAULT';
                   6135:         $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
                   6136:     };
                   6137:     if (!$@) {
                   6138:         if ($outcome eq 'ok') {
                   6139:             my $result;
                   6140:             foreach my $key (keys(%rules_hash)) {
                   6141:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6142:             }
                   6143:             $result =~ s/\&$//;
                   6144:             $result .= ':';
                   6145:             if (@rules_order > 0) {
                   6146:                 foreach my $item (@rules_order) {
                   6147:                     $result .= &escape($item).'&';
                   6148:                 }
                   6149:             }
                   6150:             $result =~ s/\&$//;
1.387     albertel 6151:             &Reply($client,\$result,$userinput);
1.381     raeburn  6152:         } else {
                   6153:             &Reply($client,"error\n", $userinput);
                   6154:         }
                   6155:     } else {
                   6156:         &Failure($client,"unknown_cmd\n",$userinput);
                   6157:     }
                   6158: }
                   6159: &register_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
                   6160: 
1.389     raeburn  6161: sub get_institutional_id_rules {
                   6162:     my ($cmd, $tail, $client)   = @_;
                   6163:     my $userinput               = "$cmd:$tail";
                   6164:     my $dom = &unescape($tail);
                   6165:     my (%rules_hash,@rules_order);
                   6166:     my $outcome;
                   6167:     eval {
                   6168:         local($SIG{__DIE__})='DEFAULT';
                   6169:         $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
                   6170:     };
                   6171:     if (!$@) {
                   6172:         if ($outcome eq 'ok') {
                   6173:             my $result;
                   6174:             foreach my $key (keys(%rules_hash)) {
                   6175:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6176:             }
                   6177:             $result =~ s/\&$//;
                   6178:             $result .= ':';
                   6179:             if (@rules_order > 0) {
                   6180:                 foreach my $item (@rules_order) {
                   6181:                     $result .= &escape($item).'&';
                   6182:                 }
                   6183:             }
                   6184:             $result =~ s/\&$//;
                   6185:             &Reply($client,\$result,$userinput);
                   6186:         } else {
                   6187:             &Reply($client,"error\n", $userinput);
                   6188:         }
                   6189:     } else {
                   6190:         &Failure($client,"unknown_cmd\n",$userinput);
                   6191:     }
                   6192: }
                   6193: &register_handler("instidrules",\&get_institutional_id_rules,0,1,0);
                   6194: 
1.397     raeburn  6195: sub get_institutional_selfcreate_rules {
1.396     raeburn  6196:     my ($cmd, $tail, $client)   = @_;
                   6197:     my $userinput               = "$cmd:$tail";
                   6198:     my $dom = &unescape($tail);
                   6199:     my (%rules_hash,@rules_order);
                   6200:     my $outcome;
                   6201:     eval {
                   6202:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6203:         $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
1.396     raeburn  6204:     };
                   6205:     if (!$@) {
                   6206:         if ($outcome eq 'ok') {
                   6207:             my $result;
                   6208:             foreach my $key (keys(%rules_hash)) {
                   6209:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6210:             }
                   6211:             $result =~ s/\&$//;
                   6212:             $result .= ':';
                   6213:             if (@rules_order > 0) {
                   6214:                 foreach my $item (@rules_order) {
                   6215:                     $result .= &escape($item).'&';
                   6216:                 }
                   6217:             }
                   6218:             $result =~ s/\&$//;
                   6219:             &Reply($client,\$result,$userinput);
                   6220:         } else {
                   6221:             &Reply($client,"error\n", $userinput);
                   6222:         }
                   6223:     } else {
                   6224:         &Failure($client,"unknown_cmd\n",$userinput);
                   6225:     }
                   6226: }
1.397     raeburn  6227: &register_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
1.396     raeburn  6228: 
1.381     raeburn  6229: 
                   6230: sub institutional_username_check {
                   6231:     my ($cmd, $tail, $client)   = @_;
                   6232:     my $userinput               = "$cmd:$tail";
                   6233:     my %rulecheck;
                   6234:     my $outcome;
                   6235:     my ($udom,$uname,@rules) = split(/:/,$tail);
                   6236:     $udom = &unescape($udom);
                   6237:     $uname = &unescape($uname);
                   6238:     @rules = map {&unescape($_);} (@rules);
                   6239:     eval {
                   6240:         local($SIG{__DIE__})='DEFAULT';
                   6241:         $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
                   6242:     };
                   6243:     if (!$@) {
                   6244:         if ($outcome eq 'ok') {
                   6245:             my $result='';
                   6246:             foreach my $key (keys(%rulecheck)) {
                   6247:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6248:             }
1.387     albertel 6249:             &Reply($client,\$result,$userinput);
1.381     raeburn  6250:         } else {
                   6251:             &Reply($client,"error\n", $userinput);
                   6252:         }
                   6253:     } else {
                   6254:         &Failure($client,"unknown_cmd\n",$userinput);
                   6255:     }
                   6256: }
                   6257: &register_handler("instrulecheck",\&institutional_username_check,0,1,0);
                   6258: 
1.389     raeburn  6259: sub institutional_id_check {
                   6260:     my ($cmd, $tail, $client)   = @_;
                   6261:     my $userinput               = "$cmd:$tail";
                   6262:     my %rulecheck;
                   6263:     my $outcome;
                   6264:     my ($udom,$id,@rules) = split(/:/,$tail);
                   6265:     $udom = &unescape($udom);
                   6266:     $id = &unescape($id);
                   6267:     @rules = map {&unescape($_);} (@rules);
                   6268:     eval {
                   6269:         local($SIG{__DIE__})='DEFAULT';
                   6270:         $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
                   6271:     };
                   6272:     if (!$@) {
                   6273:         if ($outcome eq 'ok') {
                   6274:             my $result='';
                   6275:             foreach my $key (keys(%rulecheck)) {
                   6276:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6277:             }
                   6278:             &Reply($client,\$result,$userinput);
                   6279:         } else {
                   6280:             &Reply($client,"error\n", $userinput);
                   6281:         }
                   6282:     } else {
                   6283:         &Failure($client,"unknown_cmd\n",$userinput);
                   6284:     }
                   6285: }
                   6286: &register_handler("instidrulecheck",\&institutional_id_check,0,1,0);
1.345     raeburn  6287: 
1.397     raeburn  6288: sub institutional_selfcreate_check {
1.396     raeburn  6289:     my ($cmd, $tail, $client)   = @_;
                   6290:     my $userinput               = "$cmd:$tail";
                   6291:     my %rulecheck;
                   6292:     my $outcome;
                   6293:     my ($udom,$email,@rules) = split(/:/,$tail);
                   6294:     $udom = &unescape($udom);
                   6295:     $email = &unescape($email);
                   6296:     @rules = map {&unescape($_);} (@rules);
                   6297:     eval {
                   6298:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6299:         $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
1.396     raeburn  6300:     };
                   6301:     if (!$@) {
                   6302:         if ($outcome eq 'ok') {
                   6303:             my $result='';
                   6304:             foreach my $key (keys(%rulecheck)) {
                   6305:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6306:             }
                   6307:             &Reply($client,\$result,$userinput);
                   6308:         } else {
                   6309:             &Reply($client,"error\n", $userinput);
                   6310:         }
                   6311:     } else {
                   6312:         &Failure($client,"unknown_cmd\n",$userinput);
                   6313:     }
                   6314: }
1.397     raeburn  6315: &register_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
1.396     raeburn  6316: 
1.317     raeburn  6317: # Get domain specific conditions for import of student photographs to a course
                   6318: #
                   6319: # Retrieves information from photo_permission subroutine in localenroll.
                   6320: # Returns outcome (ok) if no processing errors, and whether course owner is 
                   6321: # required to accept conditions of use (yes/no).
                   6322: #
                   6323: #    
                   6324: sub photo_permission_handler {
                   6325:     my ($cmd, $tail, $client)   = @_;
                   6326:     my $userinput               = "$cmd:$tail";
                   6327:     my $cdom = $tail;
                   6328:     my ($perm_reqd,$conditions);
1.320     albertel 6329:     my $outcome;
                   6330:     eval {
                   6331: 	local($SIG{__DIE__})='DEFAULT';
                   6332: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
                   6333: 						  \$conditions);
                   6334:     };
                   6335:     if (!$@) {
                   6336: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
                   6337: 	       $userinput);
                   6338:     } else {
                   6339: 	&Failure($client,"unknown_cmd\n",$userinput);
                   6340:     }
                   6341:     return 1;
1.317     raeburn  6342: }
                   6343: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
                   6344: 
                   6345: #
                   6346: # Checks if student photo is available for a user in the domain, in the user's
                   6347: # directory (in /userfiles/internal/studentphoto.jpg).
                   6348: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
                   6349: # the student's photo.   
                   6350: 
                   6351: sub photo_check_handler {
                   6352:     my ($cmd, $tail, $client)   = @_;
                   6353:     my $userinput               = "$cmd:$tail";
                   6354:     my ($udom,$uname,$pid) = split(/:/,$tail);
                   6355:     $udom = &unescape($udom);
                   6356:     $uname = &unescape($uname);
                   6357:     $pid = &unescape($pid);
                   6358:     my $path=&propath($udom,$uname).'/userfiles/internal/';
                   6359:     if (!-e $path) {
                   6360:         &mkpath($path);
                   6361:     }
                   6362:     my $response;
                   6363:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
                   6364:     $result .= ':'.$response;
                   6365:     &Reply($client, &escape($result)."\n",$userinput);
1.320     albertel 6366:     return 1;
1.317     raeburn  6367: }
                   6368: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
                   6369: 
                   6370: #
                   6371: # Retrieve information from localenroll about whether to provide a button     
                   6372: # for users who have enbled import of student photos to initiate an 
                   6373: # update of photo files for registered students. Also include 
                   6374: # comment to display alongside button.  
                   6375: 
                   6376: sub photo_choice_handler {
                   6377:     my ($cmd, $tail, $client) = @_;
                   6378:     my $userinput             = "$cmd:$tail";
                   6379:     my $cdom                  = &unescape($tail);
1.320     albertel 6380:     my ($update,$comment);
                   6381:     eval {
                   6382: 	local($SIG{__DIE__})='DEFAULT';
                   6383: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
                   6384:     };
                   6385:     if (!$@) {
                   6386: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
                   6387:     } else {
                   6388: 	&Failure($client,"unknown_cmd\n",$userinput);
                   6389:     }
                   6390:     return 1;
1.317     raeburn  6391: }
                   6392: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
                   6393: 
1.265     albertel 6394: #
                   6395: # Gets a student's photo to exist (in the correct image type) in the user's 
                   6396: # directory.
                   6397: # Formal Parameters:
                   6398: #    $cmd     - The command request that got us dispatched.
                   6399: #    $tail    - A colon separated set of words that will be split into:
                   6400: #               $domain - student's domain
                   6401: #               $uname  - student username
                   6402: #               $type   - image type desired
                   6403: #    $client  - The socket open on the client.
                   6404: # Returns:
                   6405: #    1 - continue processing.
1.317     raeburn  6406: 
1.265     albertel 6407: sub student_photo_handler {
                   6408:     my ($cmd, $tail, $client) = @_;
1.317     raeburn  6409:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
1.265     albertel 6410: 
1.317     raeburn  6411:     my $path=&propath($domain,$uname). '/userfiles/internal/';
                   6412:     my $filename = 'studentphoto.'.$ext;
                   6413:     if ($type eq 'thumbnail') {
                   6414:         $filename = 'studentphoto_tn.'.$ext;
                   6415:     }
                   6416:     if (-e $path.$filename) {
1.265     albertel 6417: 	&Reply($client,"ok\n","$cmd:$tail");
                   6418: 	return 1;
                   6419:     }
                   6420:     &mkpath($path);
1.317     raeburn  6421:     my $file;
                   6422:     if ($type eq 'thumbnail') {
1.320     albertel 6423: 	eval {
                   6424: 	    local($SIG{__DIE__})='DEFAULT';
                   6425: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
                   6426: 	};
1.317     raeburn  6427:     } else {
                   6428:         $file=&localstudentphoto::fetch($domain,$uname);
                   6429:     }
1.265     albertel 6430:     if (!$file) {
                   6431: 	&Failure($client,"unavailable\n","$cmd:$tail");
                   6432: 	return 1;
                   6433:     }
1.317     raeburn  6434:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
                   6435:     if (-e $path.$filename) {
1.265     albertel 6436: 	&Reply($client,"ok\n","$cmd:$tail");
                   6437: 	return 1;
                   6438:     }
                   6439:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
                   6440:     return 1;
                   6441: }
                   6442: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246     foxr     6443: 
1.361     raeburn  6444: sub inst_usertypes_handler {
                   6445:     my ($cmd, $domain, $client) = @_;
                   6446:     my $res;
                   6447:     my $userinput = $cmd.":".$domain; # For logging purposes.
1.370     albertel 6448:     my (%typeshash,@order,$result);
                   6449:     eval {
                   6450: 	local($SIG{__DIE__})='DEFAULT';
                   6451: 	$result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
                   6452:     };
                   6453:     if ($result eq 'ok') {
1.361     raeburn  6454:         if (keys(%typeshash) > 0) {
                   6455:             foreach my $key (keys(%typeshash)) {
                   6456:                 $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
                   6457:             }
                   6458:         }
                   6459:         $res=~s/\&$//;
                   6460:         $res .= ':';
                   6461:         if (@order > 0) {
                   6462:             foreach my $item (@order) {
                   6463:                 $res .= &escape($item).'&';
                   6464:             }
                   6465:         }
                   6466:         $res=~s/\&$//;
                   6467:     }
1.387     albertel 6468:     &Reply($client, \$res, $userinput);
1.361     raeburn  6469:     return 1;
                   6470: }
                   6471: &register_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
                   6472: 
1.264     albertel 6473: # mkpath makes all directories for a file, expects an absolute path with a
                   6474: # file or a trailing / if just a dir is passed
                   6475: # returns 1 on success 0 on failure
                   6476: sub mkpath {
                   6477:     my ($file)=@_;
                   6478:     my @parts=split(/\//,$file,-1);
                   6479:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
                   6480:     for (my $i=3;$i<= ($#parts-1);$i++) {
1.265     albertel 6481: 	$now.='/'.$parts[$i]; 
1.264     albertel 6482: 	if (!-e $now) {
                   6483: 	    if  (!mkdir($now,0770)) { return 0; }
                   6484: 	}
                   6485:     }
                   6486:     return 1;
                   6487: }
                   6488: 
1.207     foxr     6489: #---------------------------------------------------------------
                   6490: #
                   6491: #   Getting, decoding and dispatching requests:
                   6492: #
                   6493: #
                   6494: #   Get a Request:
                   6495: #   Gets a Request message from the client.  The transaction
                   6496: #   is defined as a 'line' of text.  We remove the new line
                   6497: #   from the text line.  
1.226     foxr     6498: #
1.211     albertel 6499: sub get_request {
1.207     foxr     6500:     my $input = <$client>;
                   6501:     chomp($input);
1.226     foxr     6502: 
1.234     foxr     6503:     &Debug("get_request: Request = $input\n");
1.207     foxr     6504: 
                   6505:     &status('Processing '.$clientname.':'.$input);
                   6506: 
                   6507:     return $input;
                   6508: }
1.212     foxr     6509: #---------------------------------------------------------------
                   6510: #
                   6511: #  Process a request.  This sub should shrink as each action
                   6512: #  gets farmed out into a separat sub that is registered 
                   6513: #  with the dispatch hash.  
                   6514: #
                   6515: # Parameters:
                   6516: #    user_input   - The request received from the client (lonc).
1.525     raeburn  6517: #
1.212     foxr     6518: # Returns:
                   6519: #    true to keep processing, false if caller should exit.
                   6520: #
                   6521: sub process_request {
1.525     raeburn  6522:     my ($userinput) = @_; # Easier for now to break style than to
                   6523:                           # fix all the userinput -> user_input.
1.212     foxr     6524:     my $wasenc    = 0;		# True if request was encrypted.
                   6525: # ------------------------------------------------------------ See if encrypted
1.322     albertel 6526:     # for command
                   6527:     # sethost:<server>
                   6528:     # <command>:<args>
                   6529:     #   we just send it to the processor
                   6530:     # for
                   6531:     # sethost:<server>:<command>:<args>
                   6532:     #  we do the implict set host and then do the command
                   6533:     if ($userinput =~ /^sethost:/) {
                   6534: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
                   6535: 	if (defined($userinput)) {
                   6536: 	    &sethost("$cmd:$newid");
                   6537: 	} else {
                   6538: 	    $userinput = "$cmd:$newid";
                   6539: 	}
                   6540:     }
                   6541: 
1.212     foxr     6542:     if ($userinput =~ /^enc/) {
                   6543: 	$userinput = decipher($userinput);
                   6544: 	$wasenc=1;
                   6545: 	if(!$userinput) {	# Cipher not defined.
1.251     foxr     6546: 	    &Failure($client, "error: Encrypted data without negotated key\n");
1.212     foxr     6547: 	    return 0;
                   6548: 	}
                   6549:     }
                   6550:     Debug("process_request: $userinput\n");
                   6551:     
1.213     foxr     6552:     #  
                   6553:     #   The 'correct way' to add a command to lond is now to
                   6554:     #   write a sub to execute it and Add it to the command dispatch
                   6555:     #   hash via a call to register_handler..  The comments to that
                   6556:     #   sub should give you enough to go on to show how to do this
                   6557:     #   along with the examples that are building up as this code
                   6558:     #   is getting refactored.   Until all branches of the
                   6559:     #   if/elseif monster below have been factored out into
                   6560:     #   separate procesor subs, if the dispatch hash is missing
                   6561:     #   the command keyword, we will fall through to the remainder
                   6562:     #   of the if/else chain below in order to keep this thing in 
                   6563:     #   working order throughout the transmogrification.
                   6564: 
                   6565:     my ($command, $tail) = split(/:/, $userinput, 2);
                   6566:     chomp($command);
                   6567:     chomp($tail);
                   6568:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
1.214     foxr     6569:     $command =~ s/(\r)//;	# And this too for parameterless commands.
                   6570:     if(!$tail) {
                   6571: 	$tail ="";		# defined but blank.
                   6572:     }
1.213     foxr     6573: 
                   6574:     &Debug("Command received: $command, encoded = $wasenc");
                   6575: 
                   6576:     if(defined $Dispatcher{$command}) {
                   6577: 
                   6578: 	my $dispatch_info = $Dispatcher{$command};
                   6579: 	my $handler       = $$dispatch_info[0];
                   6580: 	my $need_encode   = $$dispatch_info[1];
                   6581: 	my $client_types  = $$dispatch_info[2];
                   6582: 	Debug("Matched dispatch hash: mustencode: $need_encode "
                   6583: 	      ."ClientType $client_types");
                   6584:       
                   6585: 	#  Validate the request:
                   6586:       
                   6587: 	my $ok = 1;
                   6588: 	my $requesterprivs = 0;
                   6589: 	if(&isClient()) {
                   6590: 	    $requesterprivs |= $CLIENT_OK;
                   6591: 	}
                   6592: 	if(&isManager()) {
                   6593: 	    $requesterprivs |= $MANAGER_OK;
                   6594: 	}
                   6595: 	if($need_encode && (!$wasenc)) {
                   6596: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
                   6597: 	    $ok = 0;
                   6598: 	}
                   6599: 	if(($client_types & $requesterprivs) == 0) {
                   6600: 	    Debug("Client not privileged to do this operation");
                   6601: 	    $ok = 0;
                   6602: 	}
1.525     raeburn  6603:         if ($ok) {
1.535     raeburn  6604:             my $realcommand = $command;
                   6605:             if ($command eq 'querysend') {
                   6606:                 my ($query,$rest)=split(/\:/,$tail,2);
                   6607:                 $query=~s/\n*$//g;
                   6608:                 my @possqueries = 
                   6609:                     qw(userlog courselog fetchenrollment institutionalphotos usersearch instdirsearch getinstuser getmultinstusers);
                   6610:                 if (grep(/^\Q$query\E$/,@possqueries)) {
                   6611:                     $command .= '_'.$query;
                   6612:                 } elsif ($query eq 'prepare activity log') {
                   6613:                     $command .= '_activitylog';
                   6614:                 }
                   6615:             }
1.525     raeburn  6616:             if (ref($trust{$command}) eq 'HASH') {
                   6617:                 my $donechecks;
                   6618:                 if ($trust{$command}{'anywhere'}) {
                   6619:                    $donechecks = 1;
                   6620:                 } elsif ($trust{$command}{'manageronly'}) {
                   6621:                     unless (&isManager()) {
                   6622:                         $ok = 0;
                   6623:                     }
                   6624:                     $donechecks = 1;
                   6625:                 } elsif ($trust{$command}{'institutiononly'}) {
                   6626:                     unless ($clientsameinst) {
                   6627:                         $ok = 0;
                   6628:                     }
                   6629:                     $donechecks = 1;
                   6630:                 } elsif ($clientsameinst) {
                   6631:                     $donechecks = 1;
                   6632:                 }
                   6633:                 unless ($donechecks) {
                   6634:                     foreach my $rule (keys(%{$trust{$command}})) {
                   6635:                         next if ($rule eq 'remote');
                   6636:                         if ($trust{$command}{$rule}) {
                   6637:                             if ($clientprohibited{$rule}) {
                   6638:                                 $ok = 0;
                   6639:                             } else {
                   6640:                                 $ok = 1;
                   6641:                                 $donechecks = 1;
                   6642:                                 last;
                   6643:                             }
                   6644:                         }
                   6645:                     }
                   6646:                 }
                   6647:                 unless ($donechecks) {
                   6648:                     if ($trust{$command}{'remote'}) {
                   6649:                         if ($clientremoteok) {
                   6650:                             $ok = 1;
                   6651:                         } else {
                   6652:                             $ok = 0;
                   6653:                         } 
                   6654:                     }
                   6655:                 }
                   6656:             }
1.535     raeburn  6657:             $command = $realcommand;
1.525     raeburn  6658:         }
1.213     foxr     6659: 
                   6660: 	if($ok) {
                   6661: 	    Debug("Dispatching to handler $command $tail");
                   6662: 	    my $keep_going = &$handler($command, $tail, $client);
                   6663: 	    return $keep_going;
                   6664: 	} else {
                   6665: 	    Debug("Refusing to dispatch because client did not match requirements");
                   6666: 	    Failure($client, "refused\n", $userinput);
                   6667: 	    return 1;
                   6668: 	}
1.525     raeburn  6669:     }
1.213     foxr     6670: 
1.262     foxr     6671:     print $client "unknown_cmd\n";
1.212     foxr     6672: # -------------------------------------------------------------------- complete
                   6673:     Debug("process_request - returning 1");
                   6674:     return 1;
                   6675: }
1.207     foxr     6676: #
                   6677: #   Decipher encoded traffic
                   6678: #  Parameters:
                   6679: #     input      - Encoded data.
                   6680: #  Returns:
                   6681: #     Decoded data or undef if encryption key was not yet negotiated.
                   6682: #  Implicit input:
                   6683: #     cipher  - This global holds the negotiated encryption key.
                   6684: #
1.211     albertel 6685: sub decipher {
1.207     foxr     6686:     my ($input)  = @_;
                   6687:     my $output = '';
1.212     foxr     6688:     
                   6689:     
1.207     foxr     6690:     if($cipher) {
                   6691: 	my($enc, $enclength, $encinput) = split(/:/, $input);
                   6692: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
                   6693: 	    $output .= 
                   6694: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
                   6695: 	}
                   6696: 	return substr($output, 0, $enclength);
                   6697:     } else {
                   6698: 	return undef;
                   6699:     }
                   6700: }
                   6701: 
                   6702: #
                   6703: #   Register a command processor.  This function is invoked to register a sub
                   6704: #   to process a request.  Once registered, the ProcessRequest sub can automatically
                   6705: #   dispatch requests to an appropriate sub, and do the top level validity checking
                   6706: #   as well:
                   6707: #    - Is the keyword recognized.
                   6708: #    - Is the proper client type attempting the request.
                   6709: #    - Is the request encrypted if it has to be.
                   6710: #   Parameters:
                   6711: #    $request_name         - Name of the request being registered.
                   6712: #                           This is the command request that will match
                   6713: #                           against the hash keywords to lookup the information
                   6714: #                           associated with the dispatch information.
                   6715: #    $procedure           - Reference to a sub to call to process the request.
                   6716: #                           All subs get called as follows:
                   6717: #                             Procedure($cmd, $tail, $replyfd, $key)
                   6718: #                             $cmd    - the actual keyword that invoked us.
                   6719: #                             $tail   - the tail of the request that invoked us.
                   6720: #                             $replyfd- File descriptor connected to the client
                   6721: #    $must_encode          - True if the request must be encoded to be good.
                   6722: #    $client_ok            - True if it's ok for a client to request this.
                   6723: #    $manager_ok           - True if it's ok for a manager to request this.
                   6724: # Side effects:
                   6725: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
                   6726: #      - On failure, the program will die as it's a bad internal bug to try to 
                   6727: #        register a duplicate command handler.
                   6728: #
1.211     albertel 6729: sub register_handler {
1.212     foxr     6730:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
1.207     foxr     6731: 
                   6732:     #  Don't allow duplication#
                   6733:    
                   6734:     if (defined $Dispatcher{$request_name}) {
                   6735: 	die "Attempting to define a duplicate request handler for $request_name\n";
                   6736:     }
                   6737:     #   Build the client type mask:
                   6738:     
                   6739:     my $client_type_mask = 0;
                   6740:     if($client_ok) {
                   6741: 	$client_type_mask  |= $CLIENT_OK;
                   6742:     }
                   6743:     if($manager_ok) {
                   6744: 	$client_type_mask  |= $MANAGER_OK;
                   6745:     }
                   6746:    
                   6747:     #  Enter the hash:
                   6748:       
                   6749:     my @entry = ($procedure, $must_encode, $client_type_mask);
                   6750:    
                   6751:     $Dispatcher{$request_name} = \@entry;
                   6752:    
                   6753: }
                   6754: 
                   6755: 
                   6756: #------------------------------------------------------------------
                   6757: 
                   6758: 
                   6759: 
                   6760: 
1.141     foxr     6761: #
1.96      foxr     6762: #  Convert an error return code from lcpasswd to a string value.
                   6763: #
                   6764: sub lcpasswdstrerror {
                   6765:     my $ErrorCode = shift;
1.97      foxr     6766:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     6767: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   6768:     } else {
1.98      foxr     6769: 	return $passwderrors[$ErrorCode];
1.96      foxr     6770:     }
                   6771: }
                   6772: 
1.23      harris41 6773: # grabs exception and records it to log before exiting
                   6774: sub catchexception {
1.27      albertel 6775:     my ($error)=@_;
1.25      www      6776:     $SIG{'QUIT'}='DEFAULT';
                   6777:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 6778:     &status("Catching exception");
1.190     albertel 6779:     &logthis("<font color='red'>CRITICAL: "
1.373     albertel 6780:      ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
1.27      albertel 6781:      ."a crash with this error msg->[$error]</font>");
1.57      www      6782:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 6783:     if ($client) { print $client "error: $error\n"; }
1.59      www      6784:     $server->close();
1.27      albertel 6785:     die($error);
1.23      harris41 6786: }
1.63      www      6787: sub timeout {
1.165     albertel 6788:     &status("Handling Timeout");
1.190     albertel 6789:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63      www      6790:     &catchexception('Timeout');
                   6791: }
1.22      harris41 6792: # -------------------------------- Set signal handlers to record abnormal exits
                   6793: 
1.226     foxr     6794: 
1.22      harris41 6795: $SIG{'QUIT'}=\&catchexception;
                   6796: $SIG{__DIE__}=\&catchexception;
                   6797: 
1.81      matthew  6798: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 6799: &status("Read loncapa.conf and loncapa_apache.conf");
                   6800: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     6801: %perlvar=%{$perlvarref};
1.80      harris41 6802: undef $perlvarref;
1.19      www      6803: 
1.35      harris41 6804: # ----------------------------- Make sure this process is running from user=www
                   6805: my $wwwid=getpwnam('www');
                   6806: if ($wwwid!=$<) {
1.134     albertel 6807:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   6808:    my $subj="LON: $currenthostid User ID mismatch";
1.37      harris41 6809:    system("echo 'User ID mismatch.  lond must be run as user www.' |\
1.35      harris41 6810:  mailto $emailto -s '$subj' > /dev/null");
                   6811:    exit 1;
                   6812: }
                   6813: 
1.19      www      6814: # --------------------------------------------- Check if other instance running
                   6815: 
                   6816: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   6817: 
                   6818: if (-e $pidfile) {
                   6819:    my $lfh=IO::File->new("$pidfile");
                   6820:    my $pide=<$lfh>;
                   6821:    chomp($pide);
1.29      harris41 6822:    if (kill 0 => $pide) { die "already running"; }
1.19      www      6823: }
1.1       albertel 6824: 
                   6825: # ------------------------------------------------------------- Read hosts file
                   6826: 
                   6827: 
                   6828: 
                   6829: # establish SERVER socket, bind and listen.
                   6830: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   6831:                                 Type      => SOCK_STREAM,
                   6832:                                 Proto     => 'tcp',
1.469     foxr     6833:                                 ReuseAddr     => 1,
1.1       albertel 6834:                                 Listen    => 10 )
1.29      harris41 6835:   or die "making socket: $@\n";
1.1       albertel 6836: 
                   6837: # --------------------------------------------------------- Do global variables
                   6838: 
                   6839: # global variables
                   6840: 
1.134     albertel 6841: my %children               = ();       # keys are current child process IDs
1.1       albertel 6842: 
                   6843: sub REAPER {                        # takes care of dead children
                   6844:     $SIG{CHLD} = \&REAPER;
1.165     albertel 6845:     &status("Handling child death");
1.178     foxr     6846:     my $pid;
                   6847:     do {
                   6848: 	$pid = waitpid(-1,&WNOHANG());
                   6849: 	if (defined($children{$pid})) {
                   6850: 	    &logthis("Child $pid died");
                   6851: 	    delete($children{$pid});
1.183     albertel 6852: 	} elsif ($pid > 0) {
1.178     foxr     6853: 	    &logthis("Unknown Child $pid died");
                   6854: 	}
                   6855:     } while ( $pid > 0 );
                   6856:     foreach my $child (keys(%children)) {
                   6857: 	$pid = waitpid($child,&WNOHANG());
                   6858: 	if ($pid > 0) {
                   6859: 	    &logthis("Child $child - $pid looks like we missed it's death");
                   6860: 	    delete($children{$pid});
                   6861: 	}
1.176     albertel 6862:     }
1.165     albertel 6863:     &status("Finished Handling child death");
1.1       albertel 6864: }
                   6865: 
                   6866: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 6867:     &status("Killing children (INT)");
1.1       albertel 6868:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   6869:     kill 'INT' => keys %children;
1.59      www      6870:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 6871:     my $execdir=$perlvar{'lonDaemons'};
                   6872:     unlink("$execdir/logs/lond.pid");
1.190     albertel 6873:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165     albertel 6874:     &status("Done killing children");
1.1       albertel 6875:     exit;                           # clean up with dignity
                   6876: }
                   6877: 
                   6878: sub HUPSMAN {                      # signal handler for SIGHUP
                   6879:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 6880:     &status("Killing children for restart (HUP)");
1.1       albertel 6881:     kill 'INT' => keys %children;
1.59      www      6882:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190     albertel 6883:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134     albertel 6884:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 6885:     unlink("$execdir/logs/lond.pid");
1.165     albertel 6886:     &status("Restarting self (HUP)");
1.1       albertel 6887:     exec("$execdir/lond");         # here we go again
                   6888: }
                   6889: 
1.144     foxr     6890: #
1.148     foxr     6891: #  Reload the Apache daemon's state.
1.150     foxr     6892: #  This is done by invoking /home/httpd/perl/apachereload
                   6893: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     6894: #
                   6895: sub ReloadApache {
1.473     raeburn  6896: # --------------------------- Handle case of another apachereload process (locking)
1.474     raeburn  6897:     if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
                   6898:         my $execdir = $perlvar{'lonDaemons'};
                   6899:         my $script  = $execdir."/apachereload";
                   6900:         system($script);
                   6901:         unlink('/tmp/lock_apachereload'); #  Remove the lock file.
                   6902:     }
1.148     foxr     6903: }
                   6904: 
                   6905: #
1.144     foxr     6906: #   Called in response to a USR2 signal.
                   6907: #   - Reread hosts.tab
                   6908: #   - All children connected to hosts that were removed from hosts.tab
                   6909: #     are killed via SIGINT
                   6910: #   - All children connected to previously existing hosts are sent SIGUSR1
                   6911: #   - Our internal hosts hash is updated to reflect the new contents of
                   6912: #     hosts.tab causing connections from hosts added to hosts.tab to
                   6913: #     now be honored.
                   6914: #
                   6915: sub UpdateHosts {
1.165     albertel 6916:     &status("Reload hosts.tab");
1.147     foxr     6917:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     6918:     #
                   6919:     #  The %children hash has the set of IP's we currently have children
                   6920:     #  on.  These need to be matched against records in the hosts.tab
                   6921:     #  Any ip's no longer in the table get killed off they correspond to
                   6922:     #  either dropped or changed hosts.  Note that the re-read of the table
                   6923:     #  will take care of new and changed hosts as connections come into being.
                   6924: 
1.371     albertel 6925:     &Apache::lonnet::reset_hosts_info();
1.532     raeburn  6926:     my %active;
1.148     foxr     6927: 
1.368     albertel 6928:     foreach my $child (keys(%children)) {
1.148     foxr     6929: 	my $childip = $children{$child};
1.374     albertel 6930: 	if ($childip ne '127.0.0.1'
                   6931: 	    && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
1.149     foxr     6932: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   6933: 		    ." $child for ip $childip </font>");
1.148     foxr     6934: 	    kill('INT', $child);
1.149     foxr     6935: 	} else {
1.532     raeburn  6936:             $active{$child} = $childip;
1.149     foxr     6937: 	    logthis('<font color="green"> keeping child for ip '
                   6938: 		    ." $childip (pid=$child) </font>");
1.148     foxr     6939: 	}
                   6940:     }
1.532     raeburn  6941: 
                   6942:     my %oldconf = %secureconf;
                   6943:     my %connchange;
                   6944:     if (lonssl::Read_Connect_Config(\%secureconf,\%perlvar) eq 'ok') {
                   6945:         logthis('<font color="blue"> Reloaded SSL connection rules </font>');
                   6946:     } else {
                   6947:         logthis('<font color="yellow"> Failed to reload SSL connection rules </font>');
                   6948:     }
                   6949:     if ((ref($oldconf{'connfrom'}) eq 'HASH') && (ref($secureconf{'connfrom'}) eq 'HASH')) {
                   6950:         foreach my $type ('dom','intdom','other') {
                   6951:             if ((($oldconf{'connfrom'}{$type} eq 'no') && ($secureconf{'connfrom'}{$type} eq 'req')) ||
                   6952:                 (($oldconf{'connfrom'}{$type} eq 'req') && ($secureconf{'connfrom'}{$type} eq 'no'))) {
                   6953:                 $connchange{$type} = 1;
                   6954:             }
                   6955:         }
                   6956:     }
                   6957:     if (keys(%connchange)) {
                   6958:         foreach my $child (keys(%active)) {
                   6959:             my $childip = $active{$child};
                   6960:             if ($childip ne '127.0.0.1') {
                   6961:                 my $childhostname  = gethostbyaddr(Socket::inet_aton($childip),AF_INET);
                   6962:                 if ($childhostname ne '') {
                   6963:                     my $childlonhost = &Apache::lonnet::get_server_homeID($childhostname);
                   6964:                     my ($samedom,$sameinst) = &set_client_info($childlonhost);
                   6965:                     if ($samedom) {
                   6966:                         if ($connchange{'dom'}) {
                   6967:                             logthis('<font color="blue"> UpdateHosts killing child '
                   6968:                                    ." $child for ip $childip </font>");
                   6969:                             kill('INT', $child);
                   6970:                         }
                   6971:                     } elsif ($sameinst) {
                   6972:                         if ($connchange{'intdom'}) {
                   6973:                             logthis('<font color="blue"> UpdateHosts killing child '
                   6974:                                    ." $child for ip $childip </font>");
                   6975:                            kill('INT', $child);
                   6976:                         }
                   6977:                     } else {
                   6978:                         if ($connchange{'other'}) {
                   6979:                             logthis('<font color="blue"> UpdateHosts killing child '
                   6980:                                    ." $child for ip $childip </font>");
                   6981:                             kill('INT', $child);
                   6982:                         }
                   6983:                     }
                   6984:                 }
                   6985:             }
                   6986:         }
                   6987:     }
1.148     foxr     6988:     ReloadApache;
1.165     albertel 6989:     &status("Finished reloading hosts.tab");
1.144     foxr     6990: }
                   6991: 
1.57      www      6992: sub checkchildren {
1.165     albertel 6993:     &status("Checking on the children (sending signals)");
1.57      www      6994:     &initnewstatus();
                   6995:     &logstatus();
                   6996:     &logthis('Going to check on the children');
1.134     albertel 6997:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 6998:     foreach (sort keys %children) {
1.221     albertel 6999: 	#sleep 1;
1.57      www      7000:         unless (kill 'USR1' => $_) {
                   7001: 	    &logthis ('Child '.$_.' is dead');
                   7002:             &logstatus($$.' is dead');
1.221     albertel 7003: 	    delete($children{$_});
1.57      www      7004:         } 
1.61      harris41 7005:     }
1.63      www      7006:     sleep 5;
1.212     foxr     7007:     $SIG{ALRM} = sub { Debug("timeout"); 
                   7008: 		       die "timeout";  };
1.113     albertel 7009:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 7010:     &status("Checking on the children (waiting for reports)");
1.63      www      7011:     foreach (sort keys %children) {
                   7012:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 7013:           eval {
                   7014:             alarm(300);
1.63      www      7015: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 7016: 	    kill 9 => $_;
1.131     albertel 7017: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   7018: 	    #$subj="LON: $currenthostid killed lond process $_";
                   7019: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   7020: 	    #$execdir=$perlvar{'lonDaemons'};
                   7021: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221     albertel 7022: 	    delete($children{$_});
1.113     albertel 7023: 	    alarm(0);
                   7024: 	  }
1.63      www      7025:         }
                   7026:     }
1.113     albertel 7027:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 7028:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 7029:     &status("Finished checking children");
1.221     albertel 7030:     &logthis('Finished Checking children');
1.57      www      7031: }
                   7032: 
1.1       albertel 7033: # --------------------------------------------------------------------- Logging
                   7034: 
                   7035: sub logthis {
                   7036:     my $message=shift;
                   7037:     my $execdir=$perlvar{'lonDaemons'};
                   7038:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   7039:     my $now=time;
                   7040:     my $local=localtime($now);
1.58      www      7041:     $lastlog=$local.': '.$message;
1.1       albertel 7042:     print $fh "$local ($$): $message\n";
                   7043: }
                   7044: 
1.77      foxr     7045: # ------------------------- Conditional log if $DEBUG true.
                   7046: sub Debug {
                   7047:     my $message = shift;
                   7048:     if($DEBUG) {
                   7049: 	&logthis($message);
                   7050:     }
                   7051: }
1.161     foxr     7052: 
                   7053: #
                   7054: #   Sub to do replies to client.. this gives a hook for some
                   7055: #   debug tracing too:
                   7056: #  Parameters:
                   7057: #     fd      - File open on client.
                   7058: #     reply   - Text to send to client.
                   7059: #     request - Original request from client.
                   7060: #
1.490     droeschl 7061: #NOTE $reply must be terminated by exactly *one* \n. If $reply is a reference
                   7062: #this is done automatically ($$reply must not contain any \n in this case). 
                   7063: #If $reply is a string the caller has to ensure this.
1.161     foxr     7064: sub Reply {
1.192     foxr     7065:     my ($fd, $reply, $request) = @_;
1.387     albertel 7066:     if (ref($reply)) {
                   7067: 	print $fd $$reply;
                   7068: 	print $fd "\n";
                   7069: 	if ($DEBUG) { Debug("Request was $request  Reply was $$reply"); }
                   7070:     } else {
                   7071: 	print $fd $reply;
                   7072: 	if ($DEBUG) { Debug("Request was $request  Reply was $reply"); }
                   7073:     }
1.212     foxr     7074:     $Transactions++;
                   7075: }
                   7076: 
                   7077: 
                   7078: #
                   7079: #    Sub to report a failure.
                   7080: #    This function:
                   7081: #     -   Increments the failure statistic counters.
                   7082: #     -   Invokes Reply to send the error message to the client.
                   7083: # Parameters:
                   7084: #    fd       - File descriptor open on the client
                   7085: #    reply    - Reply text to emit.
                   7086: #    request  - The original request message (used by Reply
                   7087: #               to debug if that's enabled.
                   7088: # Implicit outputs:
                   7089: #    $Failures- The number of failures is incremented.
                   7090: #    Reply (invoked here) sends a message to the 
                   7091: #    client:
                   7092: #
                   7093: sub Failure {
                   7094:     my $fd      = shift;
                   7095:     my $reply   = shift;
                   7096:     my $request = shift;
                   7097:    
                   7098:     $Failures++;
                   7099:     Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     7100: }
1.57      www      7101: # ------------------------------------------------------------------ Log status
                   7102: 
                   7103: sub logstatus {
1.178     foxr     7104:     &status("Doing logging");
                   7105:     my $docdir=$perlvar{'lonDocRoot'};
                   7106:     {
                   7107: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200     matthew  7108:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178     foxr     7109:         $fh->close();
                   7110:     }
1.221     albertel 7111:     &status("Finished $$.txt");
                   7112:     {
                   7113: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
                   7114: 	flock(LOG,LOCK_EX);
                   7115: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
                   7116: 	    .$status."\t".$lastlog."\t $keymode\n";
1.275     albertel 7117: 	flock(LOG,LOCK_UN);
1.221     albertel 7118: 	close(LOG);
                   7119:     }
1.178     foxr     7120:     &status("Finished logging");
1.57      www      7121: }
                   7122: 
                   7123: sub initnewstatus {
                   7124:     my $docdir=$perlvar{'lonDocRoot'};
                   7125:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
1.460     foxr     7126:     my $now=time();
1.57      www      7127:     my $local=localtime($now);
                   7128:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      7129:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 7130:     while (my $filename=readdir(DIR)) {
1.64      www      7131:         unlink("$docdir/lon-status/londchld/$filename");
                   7132:     }
                   7133:     closedir(DIR);
1.57      www      7134: }
                   7135: 
                   7136: # -------------------------------------------------------------- Status setting
                   7137: 
                   7138: sub status {
                   7139:     my $what=shift;
                   7140:     my $now=time;
                   7141:     my $local=localtime($now);
1.178     foxr     7142:     $status=$local.': '.$what;
                   7143:     $0='lond: '.$what.' '.$local;
1.57      www      7144: }
1.11      www      7145: 
1.13      www      7146: # -------------------------------------------------------------- Talk to lonsql
                   7147: 
1.234     foxr     7148: sub sql_reply {
1.12      harris41 7149:     my ($cmd)=@_;
1.234     foxr     7150:     my $answer=&sub_sql_reply($cmd);
                   7151:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12      harris41 7152:     return $answer;
                   7153: }
                   7154: 
1.234     foxr     7155: sub sub_sql_reply {
1.12      harris41 7156:     my ($cmd)=@_;
                   7157:     my $unixsock="mysqlsock";
                   7158:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   7159:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   7160:                                       Type    => SOCK_STREAM,
                   7161:                                       Timeout => 10)
                   7162:        or return "con_lost";
1.319     www      7163:     print $sclient "$cmd:$currentdomainid\n";
1.12      harris41 7164:     my $answer=<$sclient>;
                   7165:     chomp($answer);
                   7166:     if (!$answer) { $answer="con_lost"; }
                   7167:     return $answer;
                   7168: }
                   7169: 
1.1       albertel 7170: # --------------------------------------- Is this the home server of an author?
1.11      www      7171: 
1.1       albertel 7172: sub ishome {
                   7173:     my $author=shift;
                   7174:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   7175:     my ($udom,$uname)=split(/\//,$author);
                   7176:     my $proname=propath($udom,$uname);
                   7177:     if (-e $proname) {
                   7178: 	return 'owner';
                   7179:     } else {
                   7180:         return 'not_owner';
                   7181:     }
                   7182: }
                   7183: 
                   7184: # ======================================================= Continue main program
                   7185: # ---------------------------------------------------- Fork once and dissociate
                   7186: 
1.134     albertel 7187: my $fpid=fork;
1.1       albertel 7188: exit if $fpid;
1.29      harris41 7189: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 7190: 
1.29      harris41 7191: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 7192: 
                   7193: # ------------------------------------------------------- Write our PID on disk
                   7194: 
1.134     albertel 7195: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 7196: open (PIDSAVE,">$execdir/logs/lond.pid");
                   7197: print PIDSAVE "$$\n";
                   7198: close(PIDSAVE);
1.190     albertel 7199: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57      www      7200: &status('Starting');
1.1       albertel 7201: 
1.106     foxr     7202: 
1.1       albertel 7203: 
                   7204: # ----------------------------------------------------- Install signal handlers
                   7205: 
1.57      www      7206: 
1.1       albertel 7207: $SIG{CHLD} = \&REAPER;
                   7208: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   7209: $SIG{HUP}  = \&HUPSMAN;
1.57      www      7210: $SIG{USR1} = \&checkchildren;
1.144     foxr     7211: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     7212: 
1.148     foxr     7213: #  Read the host hashes:
1.368     albertel 7214: &Apache::lonnet::load_hosts_tab();
1.447     raeburn  7215: my %iphost = &Apache::lonnet::get_iphost(1);
1.106     foxr     7216: 
1.480     raeburn  7217: $dist=`$perlvar{'lonDaemons'}/distprobe`;
1.286     albertel 7218: 
1.471     raeburn  7219: my $arch = `uname -i`;
1.475     raeburn  7220: chomp($arch);
1.471     raeburn  7221: if ($arch eq 'unknown') {
                   7222:     $arch = `uname -m`;
1.475     raeburn  7223:     chomp($arch);
1.471     raeburn  7224: }
                   7225: 
1.532     raeburn  7226: unless (lonssl::Read_Connect_Config(\%secureconf,\%perlvar) eq 'ok') {
                   7227:     &logthis('<font color="blue">No connectionrules table. Will fallback to loncapa.conf</font>');
                   7228: }
                   7229: 
1.106     foxr     7230: # --------------------------------------------------------------
                   7231: #   Accept connections.  When a connection comes in, it is validated
                   7232: #   and if good, a child process is created to process transactions
                   7233: #   along the connection.
                   7234: 
1.1       albertel 7235: while (1) {
1.165     albertel 7236:     &status('Starting accept');
1.106     foxr     7237:     $client = $server->accept() or next;
1.165     albertel 7238:     &status('Accepted '.$client.' off to spawn');
1.386     albertel 7239:     make_new_child($client);
1.165     albertel 7240:     &status('Finished spawning');
1.1       albertel 7241: }
                   7242: 
1.212     foxr     7243: sub make_new_child {
                   7244:     my $pid;
                   7245: #    my $cipher;     # Now global
                   7246:     my $sigset;
1.178     foxr     7247: 
1.212     foxr     7248:     $client = shift;
                   7249:     &status('Starting new child '.$client);
                   7250:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   7251: 	     ")</font>");    
                   7252:     # block signal for fork
                   7253:     $sigset = POSIX::SigSet->new(SIGINT);
                   7254:     sigprocmask(SIG_BLOCK, $sigset)
                   7255:         or die "Can't block SIGINT for fork: $!\n";
1.178     foxr     7256: 
1.212     foxr     7257:     die "fork: $!" unless defined ($pid = fork);
1.178     foxr     7258: 
1.212     foxr     7259:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   7260: 	                               # connection liveness.
1.178     foxr     7261: 
1.212     foxr     7262:     #
                   7263:     #  Figure out who we're talking to so we can record the peer in 
                   7264:     #  the pid hash.
                   7265:     #
                   7266:     my $caller = getpeername($client);
                   7267:     my ($port,$iaddr);
                   7268:     if (defined($caller) && length($caller) > 0) {
                   7269: 	($port,$iaddr)=unpack_sockaddr_in($caller);
                   7270:     } else {
                   7271: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
                   7272:     }
                   7273:     if (defined($iaddr)) {
                   7274: 	$clientip  = inet_ntoa($iaddr);
                   7275: 	Debug("Connected with $clientip");
                   7276:     } else {
                   7277: 	&logthis("Unable to determine clientip");
                   7278: 	$clientip='Unavailable';
                   7279:     }
                   7280:     
                   7281:     if ($pid) {
                   7282:         # Parent records the child's birth and returns.
                   7283:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7284:             or die "Can't unblock SIGINT for fork: $!\n";
                   7285:         $children{$pid} = $clientip;
                   7286:         &status('Started child '.$pid);
1.462     foxr     7287: 	close($client);
1.212     foxr     7288:         return;
                   7289:     } else {
                   7290:         # Child can *not* return from this subroutine.
                   7291:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                   7292:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   7293:                                 #don't get intercepted
                   7294:         $SIG{USR1}= \&logstatus;
                   7295:         $SIG{ALRM}= \&timeout;
1.468     foxr     7296: 	#
                   7297: 	# Block sigpipe as it gets thrownon socket disconnect and we want to 
                   7298: 	# deal with that as a read faiure instead.
                   7299: 	#
                   7300: 	my $blockset = POSIX::SigSet->new(SIGPIPE);
                   7301: 	sigprocmask(SIG_BLOCK, $blockset);
                   7302: 
1.212     foxr     7303:         $lastlog='Forked ';
                   7304:         $status='Forked';
1.178     foxr     7305: 
1.212     foxr     7306:         # unblock signals
                   7307:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7308:             or die "Can't unblock SIGINT for fork: $!\n";
1.178     foxr     7309: 
1.212     foxr     7310: #        my $tmpsnum=0;            # Now global
                   7311: #---------------------------------------------------- kerberos 5 initialization
                   7312:         &Authen::Krb5::init_context();
1.511     raeburn  7313: 
                   7314:         my $no_ets;
1.514     raeburn  7315:         if ($dist =~ /^(?:centos|rhes|scientific)(\d+)$/) {
1.511     raeburn  7316:             if ($1 >= 7) {
                   7317:                 $no_ets = 1;
                   7318:             }
                   7319:         } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
                   7320:             if (($1 eq '9.3') || ($1 >= 12.2)) {
                   7321:                 $no_ets = 1; 
                   7322:             }
1.514     raeburn  7323:         } elsif ($dist =~ /^sles(\d+)$/) {
                   7324:             if ($1 > 11) {
                   7325:                 $no_ets = 1;
                   7326:             }
1.511     raeburn  7327:         } elsif ($dist =~ /^fedora(\d+)$/) {
                   7328:             if ($1 < 7) {
                   7329:                 $no_ets = 1;
                   7330:             }
                   7331:         }
                   7332:         unless ($no_ets) {
1.286     albertel 7333: 	    &Authen::Krb5::init_ets();
                   7334: 	}
1.209     albertel 7335: 
1.212     foxr     7336: 	&status('Accepted connection');
                   7337: # =============================================================================
                   7338:             # do something with the connection
                   7339: # -----------------------------------------------------------------------------
                   7340: 	# see if we know client and 'check' for spoof IP by ineffective challenge
1.178     foxr     7341: 
1.278     albertel 7342: 	my $outsideip=$clientip;
                   7343: 	if ($clientip eq '127.0.0.1') {
1.368     albertel 7344: 	    $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
1.278     albertel 7345: 	}
1.412     foxr     7346: 	&ReadManagerTable();
1.368     albertel 7347: 	my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
1.278     albertel 7348: 	my $ismanager=($managers{$outsideip}    ne undef);
1.432     raeburn  7349: 	$clientname  = "[unknown]";
1.212     foxr     7350: 	if($clientrec) {	# Establish client type.
                   7351: 	    $ConnectionType = "client";
1.368     albertel 7352: 	    $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
1.212     foxr     7353: 	    if($ismanager) {
                   7354: 		$ConnectionType = "both";
                   7355: 	    }
                   7356: 	} else {
                   7357: 	    $ConnectionType = "manager";
1.278     albertel 7358: 	    $clientname = $managers{$outsideip};
1.212     foxr     7359: 	}
1.532     raeburn  7360: 	my ($clientok,$clientinfoset);
1.178     foxr     7361: 
1.212     foxr     7362: 	if ($clientrec || $ismanager) {
                   7363: 	    &status("Waiting for init from $clientip $clientname");
                   7364: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   7365: 		     $clientip.
                   7366: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   7367: 	    &status("Connecting $clientip  ($clientname))"); 
                   7368: 	    my $remotereq=<$client>;
                   7369: 	    chomp($remotereq);
                   7370: 	    Debug("Got init: $remotereq");
1.337     albertel 7371: 
1.212     foxr     7372: 	    if ($remotereq =~ /^init/) {
                   7373: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   7374: 		#
                   7375: 		#  If the remote is attempting a local init... give that a try:
                   7376: 		#
1.432     raeburn  7377: 		(my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
1.492     droeschl 7378:         # For LON-CAPA 2.9, the  client session will have sent its LON-CAPA
                   7379:         # version when initiating the connection. For LON-CAPA 2.8 and older,
                   7380:         # the version is retrieved from the global %loncaparevs in lonnet.pm.            
1.494     droeschl 7381:         # $clientversion contains path to keyfile if $inittype eq 'local'
                   7382:         # it's overridden below in this case
1.492     droeschl 7383:         $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
1.209     albertel 7384: 
1.212     foxr     7385: 		# If the connection type is ssl, but I didn't get my
                   7386: 		# certificate files yet, then I'll drop  back to 
                   7387: 		# insecure (if allowed).
1.532     raeburn  7388: 
                   7389:                 if ($inittype eq "ssl") {
                   7390:                     my $context;
                   7391:                     if ($clientsamedom) {
                   7392:                         $context = 'dom';
                   7393:                         if ($secureconf{'connfrom'}{'dom'} eq 'no') {
                   7394:                             $inittype = "";
                   7395:                         }
                   7396:                     } elsif ($clientsameinst) {
                   7397:                         $context = 'intdom';
                   7398:                         if ($secureconf{'connfrom'}{'intdom'} eq 'no') {
                   7399:                             $inittype = "";
                   7400:                         }
                   7401:                     } else {
                   7402:                         $context = 'other';
                   7403:                         if ($secureconf{'connfrom'}{'other'} eq 'no') {
                   7404:                             $inittype = "";
                   7405:                         }
                   7406:                     }
                   7407:                     if ($inittype eq '') {
                   7408:                         &logthis("<font color=\"blue\"> Domain config set "
                   7409:                                 ."to no ssl for $clientname (context: $context)"
                   7410:                                 ." -- trying insecure auth</font>");
                   7411:                     }
                   7412:                 }
                   7413: 
1.212     foxr     7414: 		if($inittype eq "ssl") {
                   7415: 		    my ($ca, $cert) = lonssl::CertificateFile;
                   7416: 		    my $kfile       = lonssl::KeyFile;
                   7417: 		    if((!$ca)   || 
                   7418: 		       (!$cert) || 
                   7419: 		       (!$kfile)) {
                   7420: 			$inittype = ""; # This forces insecure attempt.
                   7421: 			&logthis("<font color=\"blue\"> Certificates not "
                   7422: 				 ."installed -- trying insecure auth</font>");
1.224     foxr     7423: 		    } else {	# SSL certificates are in place so
1.212     foxr     7424: 		    }		# Leave the inittype alone.
                   7425: 		}
                   7426: 
                   7427: 		if($inittype eq "local") {
1.432     raeburn  7428:                     $clientversion = $perlvar{'lonVersion'};
1.212     foxr     7429: 		    my $key = LocalConnection($client, $remotereq);
                   7430: 		    if($key) {
                   7431: 			Debug("Got local key $key");
                   7432: 			$clientok     = 1;
                   7433: 			my $cipherkey = pack("H32", $key);
                   7434: 			$cipher       = new IDEA($cipherkey);
                   7435: 			print $client "ok:local\n";
1.442     www      7436: 			&logthis('<font color="green">'
1.212     foxr     7437: 				 . "Successful local authentication </font>");
                   7438: 			$keymode = "local"
1.178     foxr     7439: 		    } else {
1.212     foxr     7440: 			Debug("Failed to get local key");
                   7441: 			$clientok = 0;
                   7442: 			shutdown($client, 3);
                   7443: 			close $client;
1.178     foxr     7444: 		    }
1.212     foxr     7445: 		} elsif ($inittype eq "ssl") {
1.532     raeburn  7446: 		    my $key = SSLConnection($client,$clientname);
1.212     foxr     7447: 		    if ($key) {
                   7448: 			$clientok = 1;
                   7449: 			my $cipherkey = pack("H32", $key);
                   7450: 			$cipher       = new IDEA($cipherkey);
                   7451: 			&logthis('<font color="green">'
                   7452: 				 ."Successfull ssl authentication with $clientname </font>");
                   7453: 			$keymode = "ssl";
                   7454: 	     
1.178     foxr     7455: 		    } else {
1.212     foxr     7456: 			$clientok = 0;
                   7457: 			close $client;
1.178     foxr     7458: 		    }
1.212     foxr     7459: 	   
                   7460: 		} else {
1.532     raeburn  7461:                     $clientinfoset = &set_client_info();
1.212     foxr     7462: 		    my $ok = InsecureConnection($client);
                   7463: 		    if($ok) {
                   7464: 			$clientok = 1;
                   7465: 			&logthis('<font color="green">'
                   7466: 				 ."Successful insecure authentication with $clientname </font>");
                   7467: 			print $client "ok\n";
                   7468: 			$keymode = "insecure";
1.178     foxr     7469: 		    } else {
1.212     foxr     7470: 			&logthis('<font color="yellow">'
                   7471: 				  ."Attempted insecure connection disallowed </font>");
                   7472: 			close $client;
                   7473: 			$clientok = 0;
1.178     foxr     7474: 		    }
                   7475: 		}
1.212     foxr     7476: 	    } else {
                   7477: 		&logthis(
                   7478: 			 "<font color='blue'>WARNING: "
                   7479: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   7480: 		&status('No init '.$clientip);
                   7481: 	    }
                   7482: 	} else {
                   7483: 	    &logthis(
                   7484: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
                   7485: 	    &status('Hung up on '.$clientip);
                   7486: 	}
                   7487:  
                   7488: 	if ($clientok) {
                   7489: # ---------------- New known client connecting, could mean machine online again
1.368     albertel 7490: 	    if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip 
1.367     albertel 7491: 		&& $clientip ne '127.0.0.1') {
1.375     albertel 7492: 		&Apache::lonnet::reconlonc($clientname);
1.212     foxr     7493: 	    }
                   7494: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
                   7495: 	    &status('Will listen to '.$clientname);
                   7496: # ------------------------------------------------------------ Process requests
                   7497: 	    my $keep_going = 1;
                   7498: 	    my $user_input;
1.532     raeburn  7499:             unless ($clientinfoset) {
                   7500:                 $clientinfoset = &set_client_info();
1.525     raeburn  7501:             }
                   7502:             $clientremoteok = 0;
                   7503:             unless ($clientsameinst) {
                   7504:                 $clientremoteok = 1;
                   7505:                 my $defdom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   7506:                 %clientprohibited = &get_prohibited($defdom);
                   7507:                 if ($clientintdom) {
                   7508:                     my $remsessconf = &get_usersession_config($defdom,'remotesession');
                   7509:                     if (ref($remsessconf) eq 'HASH') {
                   7510:                         if (ref($remsessconf->{'remote'}) eq 'HASH') {
                   7511:                             if (ref($remsessconf->{'remote'}->{'excludedomain'}) eq 'ARRAY') {
                   7512:                                 if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'excludedomain'}})) {
                   7513:                                     $clientremoteok = 0;
                   7514:                                 }
                   7515:                             }
                   7516:                             if (ref($remsessconf->{'remote'}->{'includedomain'}) eq 'ARRAY') {
                   7517:                                 if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'includedomain'}})) {
                   7518:                                     $clientremoteok = 1;
                   7519:                                 } else {
                   7520:                                     $clientremoteok = 0;
                   7521:                                 }
                   7522:                             }
                   7523:                         }
                   7524:                     }
                   7525:                 }
                   7526:             }
1.212     foxr     7527: 	    while(($user_input = get_request) && $keep_going) {
                   7528: 		alarm(120);
                   7529: 		Debug("Main: Got $user_input\n");
                   7530: 		$keep_going = &process_request($user_input);
1.178     foxr     7531: 		alarm(0);
1.212     foxr     7532: 		&status('Listening to '.$clientname." ($keymode)");	   
1.161     foxr     7533: 	    }
1.212     foxr     7534: 
1.59      www      7535: # --------------------------------------------- client unknown or fishy, refuse
1.212     foxr     7536: 	}  else {
1.161     foxr     7537: 	    print $client "refused\n";
                   7538: 	    $client->close();
1.190     albertel 7539: 	    &logthis("<font color='blue'>WARNING: "
1.161     foxr     7540: 		     ."Rejected client $clientip, closing connection</font>");
                   7541: 	}
1.525     raeburn  7542:     }
1.161     foxr     7543:     
1.1       albertel 7544: # =============================================================================
1.161     foxr     7545:     
1.190     albertel 7546:     &logthis("<font color='red'>CRITICAL: "
1.161     foxr     7547: 	     ."Disconnect from $clientip ($clientname)</font>");    
                   7548:     
                   7549:     
                   7550:     # this exit is VERY important, otherwise the child will become
                   7551:     # a producer of more and more children, forking yourself into
                   7552:     # process death.
                   7553:     exit;
1.106     foxr     7554:     
1.78      foxr     7555: }
1.532     raeburn  7556: 
                   7557: #
                   7558: #  Used to determine if a particular client is from the same domain
                   7559: #  as the current server, or from the same internet domain.
                   7560: #
                   7561: #  Optional input -- the client to check for domain and internet domain.
                   7562: #  If not specified, defaults to the package variable: $clientname
                   7563: #
                   7564: #  If called in array context will not set package variables, but will
                   7565: #  instead return an array of two values - (a) true if client is in the
                   7566: #  same domain as the server, and (b) true if client is in the same internet
                   7567: #  domain.
                   7568: #
                   7569: #  If called in scalar context, sets package variables for current client:
                   7570: #
                   7571: #  $clienthomedom  - LonCAPA domain of homeID for client.
                   7572: #  $clientsamedom  - LonCAPA domain same for this host and client.
                   7573: #  $clientintdom   - LonCAPA "internet domain" for client.
                   7574: #  $clientsameinst - LonCAPA "internet domain" same for this host & client.
                   7575: #
                   7576: #  returns 1 to indicate package variables have been set for current client.
                   7577: #
                   7578: 
                   7579: sub set_client_info {
                   7580:     my ($lonhost) = @_;
                   7581:     $lonhost ||= $clientname;
                   7582:     my $clienthost = &Apache::lonnet::hostname($lonhost);
                   7583:     my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
                   7584:     my $homedom = &Apache::lonnet::host_domain($clientserverhomeID);
                   7585:     my $samedom = 0;
                   7586:     if ($perlvar{'lonDefDom'} eq $homedom) {
                   7587:         $samedom = 1;
                   7588:     }
                   7589:     my $intdom = &Apache::lonnet::internet_dom($clientserverhomeID);
                   7590:     my $sameinst = 0;
                   7591:     if ($intdom ne '') {
                   7592:         my $internet_names = &Apache::lonnet::get_internet_names($currenthostid);
                   7593:         if (ref($internet_names) eq 'ARRAY') {
                   7594:             if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   7595:                 $sameinst = 1;
                   7596:             }
                   7597:         }
                   7598:     }
                   7599:     if (wantarray) {
                   7600:         return ($samedom,$sameinst);
                   7601:     } else {
                   7602:         $clienthomedom = $homedom;
                   7603:         $clientsamedom = $samedom;
                   7604:         $clientintdom = $intdom;
                   7605:         $clientsameinst = $sameinst;
                   7606:         return 1;
                   7607:     }
                   7608: }
                   7609: 
1.261     foxr     7610: #
                   7611: #   Determine if a user is an author for the indicated domain.
                   7612: #
                   7613: # Parameters:
                   7614: #    domain          - domain to check in .
                   7615: #    user            - Name of user to check.
                   7616: #
                   7617: # Return:
                   7618: #     1             - User is an author for domain.
                   7619: #     0             - User is not an author for domain.
                   7620: sub is_author {
                   7621:     my ($domain, $user) = @_;
                   7622: 
                   7623:     &Debug("is_author: $user @ $domain");
                   7624: 
                   7625:     my $hashref = &tie_user_hash($domain, $user, "roles",
                   7626: 				 &GDBM_READER());
                   7627: 
                   7628:     #  Author role should show up as a key /domain/_au
1.78      foxr     7629: 
1.321     albertel 7630:     my $value;
1.487     foxr     7631:     if ($hashref) {
1.78      foxr     7632: 
1.487     foxr     7633: 	my $key    = "/$domain/_au";
                   7634: 	if (defined($hashref)) {
                   7635: 	    $value = $hashref->{$key};
                   7636: 	    if(!untie_user_hash($hashref)) {
                   7637: 		return 'error: ' .  ($!+0)." untie (GDBM) Failed";
                   7638: 	    }
                   7639: 	}
                   7640: 	
                   7641: 	if(defined($value)) {
                   7642: 	    &Debug("$user @ $domain is an author");
                   7643: 	}
                   7644:     } else {
                   7645: 	return 'error: '.($!+0)." tie (GDBM) Failed";
1.261     foxr     7646:     }
                   7647: 
                   7648:     return defined($value);
                   7649: }
1.78      foxr     7650: #
                   7651: #   Checks to see if the input roleput request was to set
1.482     www      7652: # an author role.  If so, creates construction space 
1.78      foxr     7653: # Parameters:
                   7654: #    request   - The request sent to the rolesput subchunk.
                   7655: #                We're looking for  /domain/_au
                   7656: #    domain    - The domain in which the user is having roles doctored.
                   7657: #    user      - Name of the user for which the role is being put.
                   7658: #    authtype  - The authentication type associated with the user.
                   7659: #
1.289     albertel 7660: sub manage_permissions {
1.192     foxr     7661:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     7662:     # See if the request is of the form /$domain/_au
1.289     albertel 7663:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.484     raeburn  7664:         my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
1.482     www      7665:         unless (-e $path) {        
                   7666:            mkdir($path);
                   7667:         }
                   7668:         unless (-e $path.'/'.$user) {
                   7669:            mkdir($path.'/'.$user);
                   7670:         }
1.78      foxr     7671:     }
                   7672: }
1.222     foxr     7673: 
                   7674: 
                   7675: #
                   7676: #  Return the full path of a user password file, whether it exists or not.
                   7677: # Parameters:
                   7678: #   domain     - Domain in which the password file lives.
                   7679: #   user       - name of the user.
                   7680: # Returns:
                   7681: #    Full passwd path:
                   7682: #
                   7683: sub password_path {
                   7684:     my ($domain, $user) = @_;
1.264     albertel 7685:     return &propath($domain, $user).'/passwd';
1.222     foxr     7686: }
                   7687: 
                   7688: #   Password Filename
                   7689: #   Returns the path to a passwd file given domain and user... only if
                   7690: #  it exists.
                   7691: # Parameters:
                   7692: #   domain    - Domain in which to search.
                   7693: #   user      - username.
                   7694: # Returns:
                   7695: #   - If the password file exists returns its path.
                   7696: #   - If the password file does not exist, returns undefined.
                   7697: #
                   7698: sub password_filename {
                   7699:     my ($domain, $user) = @_;
                   7700: 
                   7701:     Debug ("PasswordFilename called: dom = $domain user = $user");
                   7702: 
                   7703:     my $path  = &password_path($domain, $user);
                   7704:     Debug("PasswordFilename got path: $path");
                   7705:     if(-e $path) {
                   7706: 	return $path;
                   7707:     } else {
                   7708: 	return undef;
                   7709:     }
                   7710: }
                   7711: 
                   7712: #
                   7713: #   Rewrite the contents of the user's passwd file.
                   7714: #  Parameters:
                   7715: #    domain    - domain of the user.
                   7716: #    name      - User's name.
                   7717: #    contents  - New contents of the file.
1.533     raeburn  7718: #    saveold   - (optional). If true save old file in a passwd.bak file.
1.222     foxr     7719: # Returns:
                   7720: #   0    - Failed.
                   7721: #   1    - Success.
                   7722: #
                   7723: sub rewrite_password_file {
1.533     raeburn  7724:     my ($domain, $user, $contents, $saveold) = @_;
1.222     foxr     7725: 
                   7726:     my $file = &password_filename($domain, $user);
                   7727:     if (defined $file) {
1.533     raeburn  7728:         if ($saveold) {
                   7729:             my $bakfile = $file.'.bak';
                   7730:             if (CopyFile($file,$bakfile)) {
                   7731:                 chmod(0400,$bakfile);
                   7732:                 &logthis("Old password saved in passwd.bak for internally authenticated user: $user:$domain");
                   7733:             } else {
                   7734:                 &logthis("Failed to save old password in passwd.bak for internally authenticated user: $user:$domain");
                   7735:             }
                   7736:         }
1.222     foxr     7737: 	my $pf = IO::File->new(">$file");
                   7738: 	if($pf) {
                   7739: 	    print $pf "$contents\n";
                   7740: 	    return 1;
                   7741: 	} else {
                   7742: 	    return 0;
                   7743: 	}
                   7744:     } else {
                   7745: 	return 0;
                   7746:     }
                   7747: 
                   7748: }
                   7749: 
1.78      foxr     7750: #
1.222     foxr     7751: #   get_auth_type - Determines the authorization type of a user in a domain.
1.78      foxr     7752: 
                   7753: #     Returns the authorization type or nouser if there is no such user.
                   7754: #
1.436     raeburn  7755: sub get_auth_type {
1.192     foxr     7756:     my ($domain, $user)  = @_;
1.78      foxr     7757: 
1.222     foxr     7758:     Debug("get_auth_type( $domain, $user ) \n");
1.78      foxr     7759:     my $proname    = &propath($domain, $user); 
                   7760:     my $passwdfile = "$proname/passwd";
                   7761:     if( -e $passwdfile ) {
                   7762: 	my $pf = IO::File->new($passwdfile);
                   7763: 	my $realpassword = <$pf>;
                   7764: 	chomp($realpassword);
1.79      foxr     7765: 	Debug("Password info = $realpassword\n");
1.78      foxr     7766: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     7767: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.259     raeburn  7768: 	return "$authtype:$contentpwd";     
1.224     foxr     7769:     } else {
1.79      foxr     7770: 	Debug("Returning nouser");
1.78      foxr     7771: 	return "nouser";
                   7772:     }
1.1       albertel 7773: }
                   7774: 
1.220     foxr     7775: #
                   7776: #  Validate a user given their domain, name and password.  This utility
                   7777: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
                   7778: #  to validate the login credentials of a user.
                   7779: # Parameters:
                   7780: #    $domain    - The domain being logged into (this is required due to
                   7781: #                 the capability for multihomed systems.
                   7782: #    $user      - The name of the user being validated.
                   7783: #    $password  - The user's propoposed password.
                   7784: #
                   7785: # Returns:
                   7786: #     1        - The domain,user,pasword triplet corresponds to a valid
                   7787: #                user.
                   7788: #     0        - The domain,user,password triplet is not a valid user.
                   7789: #
                   7790: sub validate_user {
1.396     raeburn  7791:     my ($domain, $user, $password, $checkdefauth) = @_;
1.220     foxr     7792: 
                   7793:     # Why negative ~pi you may well ask?  Well this function is about
                   7794:     # authentication, and therefore very important to get right.
                   7795:     # I've initialized the flag that determines whether or not I've 
                   7796:     # validated correctly to a value it's not supposed to get.
                   7797:     # At the end of this function. I'll ensure that it's not still that
                   7798:     # value so we don't just wind up returning some accidental value
                   7799:     # as a result of executing an unforseen code path that
1.249     foxr     7800:     # did not set $validated.  At the end of valid execution paths,
                   7801:     # validated shoule be 1 for success or 0 for failuer.
1.220     foxr     7802: 
                   7803:     my $validated = -3.14159;
                   7804: 
                   7805:     #  How we authenticate is determined by the type of authentication
                   7806:     #  the user has been assigned.  If the authentication type is
                   7807:     #  "nouser", the user does not exist so we will return 0.
                   7808: 
1.222     foxr     7809:     my $contents = &get_auth_type($domain, $user);
1.220     foxr     7810:     my ($howpwd, $contentpwd) = split(/:/, $contents);
                   7811: 
                   7812:     my $null = pack("C",0);	# Used by kerberos auth types.
                   7813: 
1.395     raeburn  7814:     if ($howpwd eq 'nouser') {
1.396     raeburn  7815:         if ($checkdefauth) {
                   7816:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   7817:             if ($domdefaults{'auth_def'} eq 'localauth') {
                   7818:                 $howpwd = $domdefaults{'auth_def'};
                   7819:                 $contentpwd = $domdefaults{'auth_arg_def'};
                   7820:             } elsif ((($domdefaults{'auth_def'} eq 'krb4') || 
                   7821:                       ($domdefaults{'auth_def'} eq 'krb5')) &&
                   7822:                      ($domdefaults{'auth_arg_def'} ne '')) {
                   7823:                 $howpwd = $domdefaults{'auth_def'};
                   7824:                 $contentpwd = $domdefaults{'auth_arg_def'}; 
                   7825:             }
1.395     raeburn  7826:         }
1.533     raeburn  7827:     }
1.220     foxr     7828:     if ($howpwd ne 'nouser') {
                   7829: 	if($howpwd eq "internal") { # Encrypted is in local password file.
1.518     raeburn  7830:             if (length($contentpwd) == 13) {
                   7831:                 $validated = (crypt($password,$contentpwd) eq $contentpwd);
                   7832:                 if ($validated) {
1.533     raeburn  7833:                     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   7834:                     if ($domdefaults{'intauth_switch'}) {
                   7835:                         my $ncpass = &hash_passwd($domain,$password);
                   7836:                         my $saveold;
                   7837:                         if ($domdefaults{'intauth_switch'} == 2) {
                   7838:                             $saveold = 1;
                   7839:                         }
                   7840:                         if (&rewrite_password_file($domain,$user,"$howpwd:$ncpass",$saveold)) {
                   7841:                             &update_passwd_history($user,$domain,$howpwd,'conversion');
                   7842:                             &logthis("Validated password hashed with bcrypt for $user:$domain");
                   7843:                         }
1.518     raeburn  7844:                     }
                   7845:                 }
                   7846:             } else {
1.533     raeburn  7847:                 $validated = &check_internal_passwd($password,$contentpwd,$domain,$user);
1.518     raeburn  7848:             }
1.220     foxr     7849: 	}
                   7850: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
                   7851: 	    $contentpwd = (getpwnam($user))[1];
                   7852: 	    if($contentpwd) {
                   7853: 		if($contentpwd eq 'x') { # Shadow password file...
                   7854: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
                   7855: 		    open PWAUTH,  "|$pwauth_path" or
                   7856: 			die "Cannot invoke authentication";
                   7857: 		    print PWAUTH "$user\n$password\n";
                   7858: 		    close PWAUTH;
                   7859: 		    $validated = ! $?;
                   7860: 
                   7861: 		} else { 	         # Passwords in /etc/passwd. 
                   7862: 		    $validated = (crypt($password,
                   7863: 					$contentpwd) eq $contentpwd);
                   7864: 		}
                   7865: 	    } else {
                   7866: 		$validated = 0;
                   7867: 	    }
1.439     raeburn  7868: 	} elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
                   7869:             my $checkwithkrb5 = 0;
                   7870:             if ($dist =~/^fedora(\d+)$/) {
                   7871:                 if ($1 > 11) {
                   7872:                     $checkwithkrb5 = 1;
                   7873:                 }
                   7874:             } elsif ($dist =~ /^suse([\d.]+)$/) {
                   7875:                 if ($1 > 11.1) {
                   7876:                     $checkwithkrb5 = 1; 
                   7877:                 }
                   7878:             }
                   7879:             if ($checkwithkrb5) {
                   7880:                 $validated = &krb5_authen($password,$null,$user,$contentpwd);
                   7881:             } else {
                   7882:                 $validated = &krb4_authen($password,$null,$user,$contentpwd);
                   7883:             }
1.224     foxr     7884: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.439     raeburn  7885:             $validated = &krb5_authen($password,$null,$user,$contentpwd);
1.224     foxr     7886: 	} elsif ($howpwd eq "localauth") { 
1.220     foxr     7887: 	    #  Authenticate via installation specific authentcation method:
                   7888: 	    $validated = &localauth::localauth($user, 
                   7889: 					       $password, 
1.353     albertel 7890: 					       $contentpwd,
                   7891: 					       $domain);
1.358     albertel 7892: 	    if ($validated < 0) {
1.357     albertel 7893: 		&logthis("localauth for $contentpwd $user:$domain returned a $validated");
                   7894: 		$validated = 0;
                   7895: 	    }
1.224     foxr     7896: 	} else {			# Unrecognized auth is also bad.
1.220     foxr     7897: 	    $validated = 0;
                   7898: 	}
                   7899:     } else {
                   7900: 	$validated = 0;
                   7901:     }
                   7902:     #
                   7903:     #  $validated has the correct stat of the authentication:
                   7904:     #
                   7905: 
                   7906:     unless ($validated != -3.14159) {
1.249     foxr     7907: 	#  I >really really< want to know if this happens.
                   7908: 	#  since it indicates that user authentication is badly
                   7909: 	#  broken in some code path.
                   7910:         #
                   7911: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220     foxr     7912:     }
                   7913:     return $validated;
                   7914: }
                   7915: 
1.518     raeburn  7916: sub check_internal_passwd {
1.533     raeburn  7917:     my ($plainpass,$stored,$domain,$user) = @_;
1.518     raeburn  7918:     my (undef,$method,@rest) = split(/!/,$stored);
1.533     raeburn  7919:     if ($method eq 'bcrypt') {
1.518     raeburn  7920:         my $result = &hash_passwd($domain,$plainpass,@rest);
                   7921:         if ($result ne $stored) {
                   7922:             return 0;
                   7923:         }
1.533     raeburn  7924:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   7925:         if ($domdefaults{'intauth_check'}) {
                   7926:             # Upgrade to a larger number of rounds if necessary
                   7927:             my $defaultcost = $domdefaults{'intauth_cost'};
                   7928:             if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   7929:                 $defaultcost = 10;
                   7930:             }
                   7931:             if (int($rest[0])<int($defaultcost)) {
                   7932:                 if ($domdefaults{'intauth_check'} == 1) { 
                   7933:                     my $ncpass = &hash_passwd($domain,$plainpass);
                   7934:                     if (&rewrite_password_file($domain,$user,"internal:$ncpass")) {
                   7935:                         &update_passwd_history($user,$domain,'internal','update cost');
                   7936:                         &logthis("Validated password hashed with bcrypt for $user:$domain");
                   7937:                     }
                   7938:                     return 1;
                   7939:                 } elsif ($domdefaults{'intauth_check'} == 2) {
                   7940:                     return 0;
                   7941:                 }
                   7942:             }
                   7943:         } else {
                   7944:             return 1;
1.518     raeburn  7945:         }
                   7946:     }
                   7947:     return 0;
                   7948: }
                   7949: 
                   7950: sub get_last_authchg {
                   7951:     my ($domain,$user) = @_;
                   7952:     my $lastmod;
                   7953:     my $logname = &propath($domain,$user).'/passwd.log';
                   7954:     if (-e "$logname") {
                   7955:         $lastmod = (stat("$logname"))[9];
                   7956:     }
                   7957:     return $lastmod;
                   7958: }
                   7959: 
1.439     raeburn  7960: sub krb4_authen {
                   7961:     my ($password,$null,$user,$contentpwd) = @_;
                   7962:     my $validated = 0;
                   7963:     if (!($password =~ /$null/) ) {  # Null password not allowed.
                   7964:         eval {
                   7965:             require Authen::Krb4;
                   7966:         };
                   7967:         if (!$@) {
                   7968:             my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
                   7969:                                                        "",
                   7970:                                                        $contentpwd,,
                   7971:                                                        'krbtgt',
                   7972:                                                        $contentpwd,
                   7973:                                                        1,
                   7974:                                                        $password);
                   7975:             if(!$k4error) {
                   7976:                 $validated = 1;
                   7977:             } else {
                   7978:                 $validated = 0;
                   7979:                 &logthis('krb4: '.$user.', '.$contentpwd.', '.
                   7980:                           &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   7981:             }
                   7982:         } else {
                   7983:             $validated = krb5_authen($password,$null,$user,$contentpwd);
                   7984:         }
                   7985:     }
                   7986:     return $validated;
                   7987: }
                   7988: 
                   7989: sub krb5_authen {
                   7990:     my ($password,$null,$user,$contentpwd) = @_;
                   7991:     my $validated = 0;
                   7992:     if(!($password =~ /$null/)) { # Null password not allowed.
                   7993:         my $krbclient = &Authen::Krb5::parse_name($user.'@'
                   7994:                                                   .$contentpwd);
                   7995:         my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
                   7996:         my $krbserver  = &Authen::Krb5::parse_name($krbservice);
                   7997:         my $credentials= &Authen::Krb5::cc_default();
                   7998:         $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
                   7999:                                                             .$contentpwd));
                   8000:         my $krbreturn;
                   8001:         if (exists(&Authen::Krb5::get_init_creds_password)) {
                   8002:             $krbreturn =
                   8003:                 &Authen::Krb5::get_init_creds_password($krbclient,$password,
                   8004:                                                           $krbservice);
                   8005:             $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
                   8006:         } else {
                   8007:             $krbreturn  =
                   8008:                 &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
                   8009:                                                          $password,$credentials);
                   8010:             $validated = ($krbreturn == 1);
                   8011:         }
                   8012:         if (!$validated) {
                   8013:             &logthis('krb5: '.$user.', '.$contentpwd.', '.
                   8014:                      &Authen::Krb5::error());
                   8015:         }
                   8016:     }
                   8017:     return $validated;
                   8018: }
1.220     foxr     8019: 
1.84      albertel 8020: sub addline {
                   8021:     my ($fname,$hostid,$ip,$newline)=@_;
                   8022:     my $contents;
                   8023:     my $found=0;
1.355     albertel 8024:     my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
1.134     albertel 8025:     my $sh;
1.84      albertel 8026:     if ($sh=IO::File->new("$fname.subscription")) {
                   8027: 	while (my $subline=<$sh>) {
                   8028: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   8029: 	}
                   8030: 	$sh->close();
                   8031:     }
                   8032:     $sh=IO::File->new(">$fname.subscription");
                   8033:     if ($contents) { print $sh $contents; }
                   8034:     if ($newline) { print $sh $newline; }
                   8035:     $sh->close();
                   8036:     return $found;
1.86      www      8037: }
                   8038: 
1.234     foxr     8039: sub get_chat {
1.324     raeburn  8040:     my ($cdom,$cname,$udom,$uname,$group)=@_;
1.310     albertel 8041: 
1.87      www      8042:     my @entries=();
1.324     raeburn  8043:     my $namespace = 'nohist_chatroom';
                   8044:     my $namespace_inroom = 'nohist_inchatroom';
1.335     albertel 8045:     if ($group ne '') {
1.324     raeburn  8046:         $namespace .= '_'.$group;
                   8047:         $namespace_inroom .= '_'.$group;
                   8048:     }
                   8049:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8050: 				 &GDBM_READER());
                   8051:     if ($hashref) {
                   8052: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.311     albertel 8053: 	&untie_user_hash($hashref);
1.123     www      8054:     }
1.124     www      8055:     my @participants=();
1.134     albertel 8056:     my $cutoff=time-60;
1.324     raeburn  8057:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
1.310     albertel 8058: 			      &GDBM_WRCREAT());
                   8059:     if ($hashref) {
                   8060:         $hashref->{$uname.':'.$udom}=time;
                   8061:         foreach my $user (sort(keys(%$hashref))) {
                   8062: 	    if ($hashref->{$user}>$cutoff) {
                   8063: 		push(@participants, 'active_participant:'.$user);
1.123     www      8064:             }
                   8065:         }
1.311     albertel 8066:         &untie_user_hash($hashref);
1.86      www      8067:     }
1.124     www      8068:     return (@participants,@entries);
1.86      www      8069: }
                   8070: 
1.234     foxr     8071: sub chat_add {
1.324     raeburn  8072:     my ($cdom,$cname,$newchat,$group)=@_;
1.88      albertel 8073:     my @entries=();
1.142     www      8074:     my $time=time;
1.324     raeburn  8075:     my $namespace = 'nohist_chatroom';
                   8076:     my $logfile = 'chatroom.log';
1.335     albertel 8077:     if ($group ne '') {
1.324     raeburn  8078:         $namespace .= '_'.$group;
                   8079:         $logfile = 'chatroom_'.$group.'.log';
                   8080:     }
                   8081:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8082: 				 &GDBM_WRCREAT());
                   8083:     if ($hashref) {
                   8084: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.88      albertel 8085: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   8086: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   8087: 	my $newid=$time.'_000000';
                   8088: 	if ($thentime==$time) {
                   8089: 	    $idnum=~s/^0+//;
                   8090: 	    $idnum++;
                   8091: 	    $idnum=substr('000000'.$idnum,-6,6);
                   8092: 	    $newid=$time.'_'.$idnum;
                   8093: 	}
1.310     albertel 8094: 	$hashref->{$newid}=$newchat;
1.88      albertel 8095: 	my $expired=$time-3600;
1.310     albertel 8096: 	foreach my $comment (keys(%$hashref)) {
                   8097: 	    my ($thistime) = ($comment=~/(\d+)\_/);
1.88      albertel 8098: 	    if ($thistime<$expired) {
1.310     albertel 8099: 		delete $hashref->{$comment};
1.88      albertel 8100: 	    }
                   8101: 	}
1.310     albertel 8102: 	{
                   8103: 	    my $proname=&propath($cdom,$cname);
1.324     raeburn  8104: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
1.310     albertel 8105: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
                   8106: 	    }
                   8107: 	    close(CHATLOG);
1.142     www      8108: 	}
1.311     albertel 8109: 	&untie_user_hash($hashref);
1.86      www      8110:     }
1.84      albertel 8111: }
                   8112: 
                   8113: sub unsub {
                   8114:     my ($fname,$clientip)=@_;
                   8115:     my $result;
1.188     foxr     8116:     my $unsubs = 0;		# Number of successful unsubscribes:
                   8117: 
                   8118: 
                   8119:     # An old way subscriptions were handled was to have a 
                   8120:     # subscription marker file:
                   8121: 
                   8122:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     8123:     if (unlink("$fname.$clientname")) {
1.188     foxr     8124: 	$unsubs++;		# Successful unsub via marker file.
                   8125:     } 
                   8126: 
                   8127:     # The more modern way to do it is to have a subscription list
                   8128:     # file:
                   8129: 
1.84      albertel 8130:     if (-e "$fname.subscription") {
1.161     foxr     8131: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     8132: 	if ($found) { 
                   8133: 	    $unsubs++;
                   8134: 	}
                   8135:     } 
                   8136: 
                   8137:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   8138:     #  resource we can return ok:
                   8139: 
                   8140:     if($unsubs) {
                   8141: 	$result = "ok\n";
1.84      albertel 8142:     } else {
1.188     foxr     8143: 	$result = "not_subscribed\n";
1.84      albertel 8144:     }
1.188     foxr     8145: 
1.84      albertel 8146:     return $result;
                   8147: }
                   8148: 
1.101     www      8149: sub currentversion {
                   8150:     my $fname=shift;
                   8151:     my $version=-1;
                   8152:     my $ulsdir='';
                   8153:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   8154:        $ulsdir=$1;
                   8155:     }
1.114     albertel 8156:     my ($fnamere1,$fnamere2);
                   8157:     # remove version if already specified
1.101     www      8158:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 8159:     # get the bits that go before and after the version number
                   8160:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   8161: 	$fnamere1=$1;
                   8162: 	$fnamere2='.'.$2;
                   8163:     }
1.101     www      8164:     if (-e $fname) { $version=1; }
                   8165:     if (-e $ulsdir) {
1.134     albertel 8166: 	if(-d $ulsdir) {
                   8167: 	    if (opendir(LSDIR,$ulsdir)) {
                   8168: 		my $ulsfn;
                   8169: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      8170: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 8171: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   8172: 		    unless (-l $thisfile) {
1.160     www      8173: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 8174: 			    if ($1>$version) { $version=$1; }
                   8175: 			}
                   8176: 		    }
                   8177: 		}
                   8178: 		closedir(LSDIR);
                   8179: 		$version++;
                   8180: 	    }
                   8181: 	}
                   8182:     }
                   8183:     return $version;
1.101     www      8184: }
                   8185: 
                   8186: sub thisversion {
                   8187:     my $fname=shift;
                   8188:     my $version=-1;
                   8189:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   8190: 	$version=$1;
                   8191:     }
                   8192:     return $version;
                   8193: }
                   8194: 
1.84      albertel 8195: sub subscribe {
                   8196:     my ($userinput,$clientip)=@_;
                   8197:     my $result;
1.293     albertel 8198:     my ($cmd,$fname)=split(/:/,$userinput,2);
1.84      albertel 8199:     my $ownership=&ishome($fname);
                   8200:     if ($ownership eq 'owner') {
1.101     www      8201: # explitly asking for the current version?
                   8202:         unless (-e $fname) {
                   8203:             my $currentversion=&currentversion($fname);
                   8204: 	    if (&thisversion($fname)==$currentversion) {
                   8205:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   8206: 		    my $root=$1;
                   8207:                     my $extension=$2;
                   8208:                     symlink($root.'.'.$extension,
                   8209:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      8210:                     unless ($extension=~/\.meta$/) {
                   8211:                        symlink($root.'.'.$extension.'.meta',
                   8212:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   8213: 		    }
1.101     www      8214:                 }
                   8215:             }
                   8216:         }
1.84      albertel 8217: 	if (-e $fname) {
                   8218: 	    if (-d $fname) {
                   8219: 		$result="directory\n";
                   8220: 	    } else {
1.161     foxr     8221: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 8222: 		my $now=time;
1.161     foxr     8223: 		my $found=&addline($fname,$clientname,$clientip,
                   8224: 				   "$clientname:$clientip:$now\n");
1.84      albertel 8225: 		if ($found) { $result="$fname\n"; }
                   8226: 		# if they were subscribed to only meta data, delete that
                   8227:                 # subscription, when you subscribe to a file you also get
                   8228:                 # the metadata
                   8229: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   8230: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
1.476     raeburn  8231:                 my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
                   8232:                 $protocol = 'http' if ($protocol ne 'https');
                   8233: 		$fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
1.84      albertel 8234: 		$result="$fname\n";
                   8235: 	    }
                   8236: 	} else {
                   8237: 	    $result="not_found\n";
                   8238: 	}
                   8239:     } else {
                   8240: 	$result="rejected\n";
                   8241:     }
                   8242:     return $result;
                   8243: }
1.287     foxr     8244: #  Change the passwd of a unix user.  The caller must have
                   8245: #  first verified that the user is a loncapa user.
                   8246: #
                   8247: # Parameters:
                   8248: #    user      - Unix user name to change.
                   8249: #    pass      - New password for the user.
                   8250: # Returns:
                   8251: #    ok    - if success
                   8252: #    other - Some meaningfule error message string.
                   8253: # NOTE:
                   8254: #    invokes a setuid script to change the passwd.
                   8255: sub change_unix_password {
                   8256:     my ($user, $pass) = @_;
                   8257: 
                   8258:     &Debug("change_unix_password");
                   8259:     my $execdir=$perlvar{'lonDaemons'};
                   8260:     &Debug("Opening lcpasswd pipeline");
                   8261:     my $pf = IO::File->new("|$execdir/lcpasswd > "
                   8262: 			   ."$perlvar{'lonDaemons'}"
                   8263: 			   ."/logs/lcpasswd.log");
                   8264:     print $pf "$user\n$pass\n$pass\n";
                   8265:     close $pf;
                   8266:     my $err = $?;
                   8267:     return ($err < @passwderrors) ? $passwderrors[$err] : 
                   8268: 	"pwchange_falure - unknown error";
                   8269: 
                   8270:     
                   8271: }
                   8272: 
1.91      albertel 8273: 
                   8274: sub make_passwd_file {
1.518     raeburn  8275:     my ($uname,$udom,$umode,$npass,$passfilename,$action)=@_;
1.390     raeburn  8276:     my $result="ok";
1.91      albertel 8277:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   8278: 	{
                   8279: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8280: 	    if ($pf) {
                   8281: 		print $pf "$umode:$npass\n";
1.518     raeburn  8282:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     8283: 	    } else {
                   8284: 		$result = "pass_file_failed_error";
                   8285: 	    }
1.91      albertel 8286: 	}
                   8287:     } elsif ($umode eq 'internal') {
1.518     raeburn  8288:         my $ncpass = &hash_passwd($udom,$npass);
1.91      albertel 8289: 	{
                   8290: 	    &Debug("Creating internal auth");
                   8291: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8292: 	    if($pf) {
1.518     raeburn  8293: 		print $pf "internal:$ncpass\n";
                   8294:                 &update_passwd_history($uname,$udom,$umode,$action); 
1.261     foxr     8295: 	    } else {
                   8296: 		$result = "pass_file_failed_error";
                   8297: 	    }
1.91      albertel 8298: 	}
                   8299:     } elsif ($umode eq 'localauth') {
                   8300: 	{
                   8301: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8302: 	    if($pf) {
                   8303: 		print $pf "localauth:$npass\n";
1.524     raeburn  8304:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     8305: 	    } else {
                   8306: 		$result = "pass_file_failed_error";
                   8307: 	    }
1.91      albertel 8308: 	}
                   8309:     } elsif ($umode eq 'unix') {
1.502     raeburn  8310: 	&logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
                   8311: 	$result="no_new_unix_accounts";
1.91      albertel 8312:     } elsif ($umode eq 'none') {
                   8313: 	{
1.223     foxr     8314: 	    my $pf = IO::File->new("> $passfilename");
1.261     foxr     8315: 	    if($pf) {
                   8316: 		print $pf "none:\n";
                   8317: 	    } else {
                   8318: 		$result = "pass_file_failed_error";
                   8319: 	    }
1.91      albertel 8320: 	}
                   8321:     } else {
1.390     raeburn  8322: 	$result="auth_mode_error";
1.91      albertel 8323:     }
                   8324:     return $result;
1.121     albertel 8325: }
                   8326: 
1.265     albertel 8327: sub convert_photo {
                   8328:     my ($start,$dest)=@_;
                   8329:     system("convert $start $dest");
                   8330: }
                   8331: 
1.121     albertel 8332: sub sethost {
                   8333:     my ($remotereq) = @_;
                   8334:     my (undef,$hostid)=split(/:/,$remotereq);
1.322     albertel 8335:     # ignore sethost if we are already correct
                   8336:     if ($hostid eq $currenthostid) {
                   8337: 	return 'ok';
                   8338:     }
                   8339: 
1.121     albertel 8340:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
1.368     albertel 8341:     if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'}) 
                   8342: 	eq &Apache::lonnet::get_host_ip($hostid)) {
1.200     matthew  8343: 	$currenthostid  =$hostid;
1.369     albertel 8344: 	$currentdomainid=&Apache::lonnet::host_domain($hostid);
1.443     www      8345: #	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
1.121     albertel 8346:     } else {
                   8347: 	&logthis("Requested host id $hostid not an alias of ".
                   8348: 		 $perlvar{'lonHostID'}." refusing connection");
                   8349: 	return 'unable_to_set';
                   8350:     }
                   8351:     return 'ok';
                   8352: }
                   8353: 
                   8354: sub version {
                   8355:     my ($userinput)=@_;
                   8356:     $remoteVERSION=(split(/:/,$userinput))[1];
                   8357:     return "version:$VERSION";
1.127     albertel 8358: }
1.178     foxr     8359: 
1.447     raeburn  8360: sub get_usersession_config {
                   8361:     my ($dom,$name) = @_;
                   8362:     my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8363:     if (defined($cached)) {
                   8364:         return $usersessionconf;
                   8365:     } else {
                   8366:         my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
1.525     raeburn  8367:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
                   8368:         return $domconfig{'usersessions'};
1.447     raeburn  8369:     }
                   8370:     return;
                   8371: }
1.200     matthew  8372: 
1.534     raeburn  8373: sub get_usersearch_config {
                   8374:     my ($dom,$name) = @_;
                   8375:     my ($usersearchconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8376:     if (defined($cached)) {
                   8377:         return $usersearchconf;
                   8378:     } else {
                   8379:         my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$dom);
                   8380:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'directorysrch'},600);
                   8381:         return $domconfig{'directorysrch'};
                   8382:     }
                   8383:     return;
                   8384: }
                   8385: 
1.525     raeburn  8386: sub get_prohibited {
                   8387:     my ($dom) = @_;
                   8388:     my $name = 'trust';
                   8389:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8390:     unless (defined($cached)) {
                   8391:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$dom);
                   8392:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'trust'},3600);
                   8393:         $trustconfig = $domconfig{'trust'};
                   8394:     }
                   8395:     my %prohibited;
                   8396:     if (ref($trustconfig)) {
                   8397:         foreach my $prefix (keys(%{$trustconfig})) {
                   8398:             if (ref($trustconfig->{$prefix}) eq 'HASH') {
                   8399:                 my $reject;
                   8400:                 if (ref($trustconfig->{$prefix}->{'exc'}) eq 'ARRAY') {
                   8401:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'exc'}})) {
                   8402:                         $reject = 1;
                   8403:                     }
                   8404:                 }
                   8405:                 if (ref($trustconfig->{$prefix}->{'inc'}) eq 'ARRAY') {
                   8406:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'inc'}})) {
                   8407:                         $reject = 0;
                   8408:                     } else {
                   8409:                         $reject = 1;
                   8410:                     }
                   8411:                 }
                   8412:                 if ($reject) {
                   8413:                     $prohibited{$prefix} = 1;
                   8414:                 }
                   8415:             }
                   8416:         }
                   8417:     }
                   8418:     return %prohibited;
                   8419: }
1.450     raeburn  8420: 
1.471     raeburn  8421: sub distro_and_arch {
                   8422:     return $dist.':'.$arch;
                   8423: }
                   8424: 
1.61      harris41 8425: # ----------------------------------- POD (plain old documentation, CPAN style)
                   8426: 
                   8427: =head1 NAME
                   8428: 
                   8429: lond - "LON Daemon" Server (port "LOND" 5663)
                   8430: 
                   8431: =head1 SYNOPSIS
                   8432: 
1.74      harris41 8433: Usage: B<lond>
                   8434: 
                   8435: Should only be run as user=www.  This is a command-line script which
                   8436: is invoked by B<loncron>.  There is no expectation that a typical user
                   8437: will manually start B<lond> from the command-line.  (In other words,
                   8438: DO NOT START B<lond> YOURSELF.)
1.61      harris41 8439: 
                   8440: =head1 DESCRIPTION
                   8441: 
1.74      harris41 8442: There are two characteristics associated with the running of B<lond>,
                   8443: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   8444: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   8445: subscriptions, etc).  These are described in two large
                   8446: sections below.
                   8447: 
                   8448: B<PROCESS MANAGEMENT>
                   8449: 
1.61      harris41 8450: Preforker - server who forks first. Runs as a daemon. HUPs.
                   8451: Uses IDEA encryption
                   8452: 
1.74      harris41 8453: B<lond> forks off children processes that correspond to the other servers
                   8454: in the network.  Management of these processes can be done at the
                   8455: parent process level or the child process level.
                   8456: 
                   8457: B<logs/lond.log> is the location of log messages.
                   8458: 
                   8459: The process management is now explained in terms of linux shell commands,
                   8460: subroutines internal to this code, and signal assignments:
                   8461: 
                   8462: =over 4
                   8463: 
                   8464: =item *
                   8465: 
                   8466: PID is stored in B<logs/lond.pid>
                   8467: 
                   8468: This is the process id number of the parent B<lond> process.
                   8469: 
                   8470: =item *
                   8471: 
                   8472: SIGTERM and SIGINT
                   8473: 
                   8474: Parent signal assignment:
                   8475:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   8476: 
                   8477: Child signal assignment:
                   8478:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   8479: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   8480:  to restart a new child.)
                   8481: 
                   8482: Command-line invocations:
                   8483:  B<kill> B<-s> SIGTERM I<PID>
                   8484:  B<kill> B<-s> SIGINT I<PID>
                   8485: 
                   8486: Subroutine B<HUNTSMAN>:
                   8487:  This is only invoked for the B<lond> parent I<PID>.
                   8488: This kills all the children, and then the parent.
                   8489: The B<lonc.pid> file is cleared.
                   8490: 
                   8491: =item *
                   8492: 
                   8493: SIGHUP
                   8494: 
                   8495: Current bug:
                   8496:  This signal can only be processed the first time
                   8497: on the parent process.  Subsequent SIGHUP signals
                   8498: have no effect.
                   8499: 
                   8500: Parent signal assignment:
                   8501:  $SIG{HUP}  = \&HUPSMAN;
                   8502: 
                   8503: Child signal assignment:
                   8504:  none (nothing happens)
                   8505: 
                   8506: Command-line invocations:
                   8507:  B<kill> B<-s> SIGHUP I<PID>
                   8508: 
                   8509: Subroutine B<HUPSMAN>:
                   8510:  This is only invoked for the B<lond> parent I<PID>,
                   8511: This kills all the children, and then the parent.
                   8512: The B<lond.pid> file is cleared.
                   8513: 
                   8514: =item *
                   8515: 
                   8516: SIGUSR1
                   8517: 
                   8518: Parent signal assignment:
                   8519:  $SIG{USR1} = \&USRMAN;
                   8520: 
                   8521: Child signal assignment:
                   8522:  $SIG{USR1}= \&logstatus;
                   8523: 
                   8524: Command-line invocations:
                   8525:  B<kill> B<-s> SIGUSR1 I<PID>
                   8526: 
                   8527: Subroutine B<USRMAN>:
                   8528:  When invoked for the B<lond> parent I<PID>,
                   8529: SIGUSR1 is sent to all the children, and the status of
                   8530: each connection is logged.
1.144     foxr     8531: 
                   8532: =item *
                   8533: 
                   8534: SIGUSR2
                   8535: 
                   8536: Parent Signal assignment:
                   8537:     $SIG{USR2} = \&UpdateHosts
                   8538: 
                   8539: Child signal assignment:
                   8540:     NONE
                   8541: 
1.74      harris41 8542: 
                   8543: =item *
                   8544: 
                   8545: SIGCHLD
                   8546: 
                   8547: Parent signal assignment:
                   8548:  $SIG{CHLD} = \&REAPER;
                   8549: 
                   8550: Child signal assignment:
                   8551:  none
                   8552: 
                   8553: Command-line invocations:
                   8554:  B<kill> B<-s> SIGCHLD I<PID>
                   8555: 
                   8556: Subroutine B<REAPER>:
                   8557:  This is only invoked for the B<lond> parent I<PID>.
                   8558: Information pertaining to the child is removed.
                   8559: The socket port is cleaned up.
                   8560: 
                   8561: =back
                   8562: 
                   8563: B<SERVER-SIDE ACTIVITIES>
                   8564: 
                   8565: Server-side information can be accepted in an encrypted or non-encrypted
                   8566: method.
                   8567: 
                   8568: =over 4
                   8569: 
                   8570: =item ping
                   8571: 
                   8572: Query a client in the hosts.tab table; "Are you there?"
                   8573: 
                   8574: =item pong
                   8575: 
                   8576: Respond to a ping query.
                   8577: 
                   8578: =item ekey
                   8579: 
                   8580: Read in encrypted key, make cipher.  Respond with a buildkey.
                   8581: 
                   8582: =item load
                   8583: 
                   8584: Respond with CPU load based on a computation upon /proc/loadavg.
                   8585: 
                   8586: =item currentauth
                   8587: 
                   8588: Reply with current authentication information (only over an
                   8589: encrypted channel).
                   8590: 
                   8591: =item auth
                   8592: 
                   8593: Only over an encrypted channel, reply as to whether a user's
                   8594: authentication information can be validated.
                   8595: 
                   8596: =item passwd
                   8597: 
                   8598: Allow for a password to be set.
                   8599: 
                   8600: =item makeuser
                   8601: 
                   8602: Make a user.
                   8603: 
1.517     raeburn  8604: =item changeuserauth
1.74      harris41 8605: 
                   8606: Allow for authentication mechanism and password to be changed.
                   8607: 
                   8608: =item home
1.61      harris41 8609: 
1.74      harris41 8610: Respond to a question "are you the home for a given user?"
                   8611: 
                   8612: =item update
                   8613: 
                   8614: Update contents of a subscribed resource.
                   8615: 
                   8616: =item unsubscribe
                   8617: 
                   8618: The server is unsubscribing from a resource.
                   8619: 
                   8620: =item subscribe
                   8621: 
                   8622: The server is subscribing to a resource.
                   8623: 
                   8624: =item log
                   8625: 
                   8626: Place in B<logs/lond.log>
                   8627: 
                   8628: =item put
                   8629: 
                   8630: stores hash in namespace
                   8631: 
1.496     raeburn  8632: =item rolesput
1.74      harris41 8633: 
                   8634: put a role into a user's environment
                   8635: 
                   8636: =item get
                   8637: 
                   8638: returns hash with keys from array
                   8639: reference filled in from namespace
                   8640: 
                   8641: =item eget
                   8642: 
                   8643: returns hash with keys from array
                   8644: reference filled in from namesp (encrypts the return communication)
                   8645: 
                   8646: =item rolesget
                   8647: 
                   8648: get a role from a user's environment
                   8649: 
                   8650: =item del
                   8651: 
                   8652: deletes keys out of array from namespace
                   8653: 
                   8654: =item keys
                   8655: 
                   8656: returns namespace keys
                   8657: 
                   8658: =item dump
                   8659: 
                   8660: dumps the complete (or key matching regexp) namespace into a hash
                   8661: 
                   8662: =item store
                   8663: 
                   8664: stores hash permanently
                   8665: for this url; hashref needs to be given and should be a \%hashname; the
                   8666: remaining args aren't required and if they aren't passed or are '' they will
                   8667: be derived from the ENV
                   8668: 
                   8669: =item restore
                   8670: 
                   8671: returns a hash for a given url
                   8672: 
                   8673: =item querysend
                   8674: 
                   8675: Tells client about the lonsql process that has been launched in response
                   8676: to a sent query.
                   8677: 
                   8678: =item queryreply
                   8679: 
                   8680: Accept information from lonsql and make appropriate storage in temporary
                   8681: file space.
                   8682: 
                   8683: =item idput
                   8684: 
                   8685: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   8686: for each student, defined perhaps by the institutional Registrar.)
                   8687: 
                   8688: =item idget
                   8689: 
                   8690: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   8691: for each student, defined perhaps by the institutional Registrar.)
                   8692: 
1.517     raeburn  8693: =item iddel
                   8694: 
                   8695: Deletes one or more ids in a domain's id database.
                   8696: 
1.74      harris41 8697: =item tmpput
                   8698: 
                   8699: Accept and store information in temporary space.
                   8700: 
                   8701: =item tmpget
                   8702: 
                   8703: Send along temporarily stored information.
                   8704: 
                   8705: =item ls
                   8706: 
                   8707: List part of a user's directory.
                   8708: 
1.135     foxr     8709: =item pushtable
                   8710: 
                   8711: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   8712: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   8713: must be restored manually in case of a problem with the new table file.
                   8714: pushtable requires that the request be encrypted and validated via
                   8715: ValidateManager.  The form of the command is:
                   8716: enc:pushtable tablename <tablecontents> \n
                   8717: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   8718: cleartext newline.
                   8719: 
1.74      harris41 8720: =item Hanging up (exit or init)
                   8721: 
                   8722: What to do when a client tells the server that they (the client)
                   8723: are leaving the network.
                   8724: 
                   8725: =item unknown command
                   8726: 
                   8727: If B<lond> is sent an unknown command (not in the list above),
                   8728: it replys to the client "unknown_cmd".
1.135     foxr     8729: 
1.74      harris41 8730: 
                   8731: =item UNKNOWN CLIENT
                   8732: 
                   8733: If the anti-spoofing algorithm cannot verify the client,
                   8734: the client is rejected (with a "refused" message sent
                   8735: to the client, and the connection is closed.
                   8736: 
                   8737: =back
1.61      harris41 8738: 
                   8739: =head1 PREREQUISITES
                   8740: 
                   8741: IO::Socket
                   8742: IO::File
                   8743: Apache::File
                   8744: POSIX
                   8745: Crypt::IDEA
                   8746: GDBM_File
                   8747: Authen::Krb4
1.91      albertel 8748: Authen::Krb5
1.61      harris41 8749: 
                   8750: =head1 COREQUISITES
                   8751: 
1.490     droeschl 8752: none
                   8753: 
1.61      harris41 8754: =head1 OSNAMES
                   8755: 
                   8756: linux
                   8757: 
                   8758: =head1 SCRIPT CATEGORIES
                   8759: 
                   8760: Server/Process
                   8761: 
                   8762: =cut
1.409     foxr     8763: 
                   8764: 
                   8765: =pod
                   8766: 
                   8767: =head1 LOG MESSAGES
                   8768: 
                   8769: The messages below can be emitted in the lond log.  This log is located
                   8770: in ~httpd/perl/logs/lond.log  Many log messages have HTML encapsulation
                   8771: to provide coloring if examined from inside a web page. Some do not.
                   8772: Where color is used, the colors are; Red for sometihhng to get excited
                   8773: about and to follow up on. Yellow for something to keep an eye on to
                   8774: be sure it does not get worse, Green,and Blue for informational items.
                   8775: 
                   8776: In the discussions below, sometimes reference is made to ~httpd
                   8777: when describing file locations.  There isn't really an httpd 
                   8778: user, however there is an httpd directory that gets installed in the
                   8779: place that user home directories go.  On linux, this is usually
                   8780: (always?) /home/httpd.
                   8781: 
                   8782: 
                   8783: Some messages are colorless.  These are usually (not always)
                   8784: Green/Blue color level messages.
                   8785: 
                   8786: =over 2
                   8787: 
                   8788: =item (Red)  LocalConnection rejecting non local: <ip> ne 127.0.0.1
                   8789: 
                   8790: A local connection negotiation was attempted by
                   8791: a host whose IP address was not 127.0.0.1.
                   8792: The socket is closed and the child will exit.
                   8793: lond has three ways to establish an encyrption
                   8794: key with a client:
                   8795: 
                   8796: =over 2
                   8797: 
                   8798: =item local 
                   8799: 
                   8800: The key is written and read from a file.
                   8801: This is only valid for connections from localhost.
                   8802: 
                   8803: =item insecure 
                   8804: 
                   8805: The key is generated by the server and
                   8806: transmitted to the client.
                   8807: 
                   8808: =item  ssl (secure)
                   8809: 
                   8810: An ssl connection is negotiated with the client,
                   8811: the key is generated by the server and sent to the 
                   8812: client across this ssl connection before the
                   8813: ssl connectionis terminated and clear text
                   8814: transmission resumes.
                   8815: 
                   8816: =back
                   8817: 
                   8818: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
                   8819: 
                   8820: The client is local but has not sent an initialization
                   8821: string that is the literal "init:local"  The connection
                   8822: is closed and the child exits.
                   8823: 
                   8824: =item Red CRITICAL Can't get key file <error>        
                   8825: 
                   8826: SSL key negotiation is being attempted but the call to
                   8827: lonssl::KeyFile  failed.  This usually means that the
                   8828: configuration file is not correctly defining or protecting
                   8829: the directories/files lonCertificateDirectory or
                   8830: lonnetPrivateKey
                   8831: <error> is a string that describes the reason that
                   8832: the key file could not be located.
                   8833: 
                   8834: =item (Red) CRITICAL  Can't get certificates <error>  
                   8835: 
                   8836: SSL key negotiation failed because we were not able to retrives our certificate
                   8837: or the CA's certificate in the call to lonssl::CertificateFile
                   8838: <error> is the textual reason this failed.  Usual reasons:
                   8839: 
                   8840: =over 2
1.490     droeschl 8841: 
1.409     foxr     8842: =item Apache config file for loncapa  incorrect:
1.490     droeschl 8843: 
1.409     foxr     8844: one of the variables 
                   8845: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
                   8846: undefined or incorrect
                   8847: 
                   8848: =item Permission error:
                   8849: 
                   8850: The directory pointed to by lonCertificateDirectory is not readable by lond
                   8851: 
                   8852: =item Permission error:
                   8853: 
                   8854: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
                   8855: 
                   8856: =item Installation error:                         
                   8857: 
                   8858: Either the certificate authority file or the certificate have not
                   8859: been installed in lonCertificateDirectory.
                   8860: 
                   8861: =item (Red) CRITICAL SSL Socket promotion failed:  <err> 
                   8862: 
                   8863: The promotion of the connection from plaintext to SSL failed
                   8864: <err> is the reason for the failure.  There are two
                   8865: system calls involved in the promotion (one of which failed), 
                   8866: a dup to produce
                   8867: a second fd on the raw socket over which the encrypted data
                   8868: will flow and IO::SOcket::SSL->new_from_fd which creates
                   8869: the SSL connection on the duped fd.
                   8870: 
                   8871: =item (Blue)   WARNING client did not respond to challenge 
                   8872: 
                   8873: This occurs on an insecure (non SSL) connection negotiation request.
                   8874: lond generates some number from the time, the PID and sends it to
                   8875: the client.  The client must respond by echoing this information back.
                   8876: If the client does not do so, that's a violation of the challenge
                   8877: protocols and the connection will be failed.
                   8878: 
                   8879: =item (Red) No manager table. Nobody can manage!!    
                   8880: 
                   8881: lond has the concept of privileged hosts that
                   8882: can perform remote management function such
                   8883: as update the hosts.tab.   The manager hosts
                   8884: are described in the 
                   8885: ~httpd/lonTabs/managers.tab file.
                   8886: this message is logged if this file is missing.
                   8887: 
                   8888: 
                   8889: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
                   8890: 
                   8891: Reports the successful parse and registration
                   8892: of a specific manager. 
                   8893: 
                   8894: =item Green existing host <clustername:dnsname>  
                   8895: 
                   8896: The manager host is already defined in the hosts.tab
                   8897: the information in that table, rather than the info in the
                   8898: manager table will be used to determine the manager's ip.
                   8899: 
                   8900: =item (Red) Unable to craete <filename>                 
                   8901: 
                   8902: lond has been asked to create new versions of an administrative
                   8903: file (by a manager).  When this is done, the new file is created
                   8904: in a temp file and then renamed into place so that there are always
                   8905: usable administrative files, even if the update fails.  This failure
                   8906: message means that the temp file could not be created.
                   8907: The update is abandoned, and the old file is available for use.
                   8908: 
                   8909: =item (Green) CopyFile from <oldname> to <newname> failed
                   8910: 
                   8911: In an update of administrative files, the copy of the existing file to a
                   8912: backup file failed.  The installation of the new file may still succeed,
                   8913: but there will not be a back up file to rever to (this should probably
                   8914: be yellow).
                   8915: 
                   8916: =item (Green) Pushfile: backed up <oldname> to <newname>
                   8917: 
                   8918: See above, the backup of the old administrative file succeeded.
                   8919: 
                   8920: =item (Red)  Pushfile: Unable to install <filename> <reason>
                   8921: 
                   8922: The new administrative file could not be installed.  In this case,
                   8923: the old administrative file is still in use.
                   8924: 
                   8925: =item (Green) Installed new < filename>.                      
                   8926: 
                   8927: The new administrative file was successfullly installed.                                               
                   8928: 
                   8929: =item (Red) Reinitializing lond pid=<pid>                    
                   8930: 
                   8931: The lonc child process <pid> will be sent a USR2 
                   8932: signal.
                   8933: 
                   8934: =item (Red) Reinitializing self                                    
                   8935: 
                   8936: We've been asked to re-read our administrative files,and
                   8937: are doing so.
                   8938: 
                   8939: =item (Yellow) error:Invalid process identifier <ident>  
                   8940: 
                   8941: A reinit command was received, but the target part of the 
                   8942: command was not valid.  It must be either
                   8943: 'lond' or 'lonc' but was <ident>
                   8944: 
                   8945: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
                   8946: 
                   8947: Checking to see if lond has been handed a valid edit
                   8948: command.  It is possible the edit command is not valid
                   8949: in that case there are no log messages to indicate that.
                   8950: 
                   8951: =item Result of password change for  <username> pwchange_success
                   8952: 
                   8953: The password for <username> was
                   8954: successfully changed.
                   8955: 
                   8956: =item Unable to open <user> passwd to change password
                   8957: 
                   8958: Could not rewrite the 
                   8959: internal password file for a user
                   8960: 
                   8961: =item Result of password change for <user> : <result>
1.490     droeschl 8962: 
1.409     foxr     8963: A unix password change for <user> was attempted 
                   8964: and the pipe returned <result>  
                   8965: 
                   8966: =item LWP GET: <message> for <fname> (<remoteurl>)
                   8967: 
                   8968: The lightweight process fetch for a resource failed
                   8969: with <message> the local filename that should
                   8970: have existed/been created was  <fname> the
                   8971: corresponding URI: <remoteurl>  This is emitted in several
                   8972: places.
                   8973: 
                   8974: =item Unable to move <transname> to <destname>     
                   8975: 
                   8976: From fetch_user_file_handler - the user file was replicated but could not
                   8977: be mv'd to its final location.
                   8978: 
                   8979: =item Looking for <domain> <username>              
                   8980: 
                   8981: From user_has_session_handler - This should be a Debug call instead
                   8982: it indicates lond is about to check whether the specified user has a 
                   8983: session active on the specified domain on the local host.
                   8984: 
                   8985: =item Client <ip> (<name>) hanging up: <input>     
                   8986: 
                   8987: lond has been asked to exit by its client.  The <ip> and <name> identify the
                   8988: client systemand <input> is the full exit command sent to the server.
                   8989: 
                   8990: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
1.490     droeschl 8991: 
1.409     foxr     8992: A lond child terminated.  NOte that this termination can also occur when the
                   8993: child receives the QUIT or DIE signals.  <pid> is the process id of the child,
                   8994: <hostname> the host lond is working for, and <message> the reason the child died
                   8995: to the best of our ability to get it (I would guess that any numeric value
                   8996: represents and errno value).  This is immediately followed by
                   8997: 
                   8998: =item  Famous last words: Catching exception - <log> 
                   8999: 
                   9000: Where log is some recent information about the state of the child.
                   9001: 
                   9002: =item Red CRITICAL: TIME OUT <pid>                     
                   9003: 
                   9004: Some timeout occured for server <pid>.  THis is normally a timeout on an LWP
                   9005: doing an HTTP::GET.
                   9006: 
                   9007: =item child <pid> died                              
                   9008: 
                   9009: The reaper caught a SIGCHILD for the lond child process <pid>
                   9010: This should be modified to also display the IP of the dying child
                   9011: $children{$pid}
                   9012: 
                   9013: =item Unknown child 0 died                           
                   9014: A child died but the wait for it returned a pid of zero which really should not
                   9015: ever happen. 
                   9016: 
                   9017: =item Child <which> - <pid> looks like we missed it's death 
                   9018: 
                   9019: When a sigchild is received, the reaper process checks all children to see if they are
                   9020: alive.  If children are dying quite quickly, the lack of signal queuing can mean
                   9021: that a signal hearalds the death of more than one child.  If so this message indicates
                   9022: which other one died. <which> is the ip of a dead child
                   9023: 
                   9024: =item Free socket: <shutdownretval>                
                   9025: 
                   9026: The HUNTSMAN sub was called due to a SIGINT in a child process.  The socket is being shutdown.
                   9027: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
                   9028: to return anything. This is followed by: 
                   9029: 
                   9030: =item Red CRITICAL: Shutting down                       
                   9031: 
                   9032: Just prior to exit.
                   9033: 
                   9034: =item Free socket: <shutdownretval>                 
                   9035: 
                   9036: The HUPSMAN sub was called due to a SIGHUP.  all children get killsed, and lond execs itself.
                   9037: This is followed by:
                   9038: 
                   9039: =item (Red) CRITICAL: Restarting                         
                   9040: 
                   9041: lond is about to exec itself to restart.
                   9042: 
                   9043: =item (Blue) Updating connections                        
                   9044: 
                   9045: (In response to a USR2).  All the children (except the one for localhost)
                   9046: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
                   9047: 
                   9048: =item (Blue) UpdateHosts killing child <pid> for ip <ip>   
                   9049: 
                   9050: Due to USR2 as above.
                   9051: 
                   9052: =item (Green) keeping child for ip <ip> (pid = <pid>)    
                   9053: 
                   9054: In response to USR2 as above, the child indicated is not being restarted because
                   9055: it's assumed that we'll always need a child for the localhost.
                   9056: 
                   9057: 
                   9058: =item Going to check on the children                
                   9059: 
                   9060: Parent is about to check on the health of the child processes.
                   9061: Note that this is in response to a USR1 sent to the parent lond.
                   9062: there may be one or more of the next two messages:
                   9063: 
                   9064: =item <pid> is dead                                 
                   9065: 
                   9066: A child that we have in our child hash as alive has evidently died.
                   9067: 
                   9068: =item  Child <pid> did not respond                   
                   9069: 
                   9070: In the health check the child <pid> did not update/produce a pid_.txt
                   9071: file when sent it's USR1 signal.  That process is killed with a 9 signal, as it's
                   9072: assumed to be hung in some un-fixable way.
                   9073: 
                   9074: =item Finished checking children                   
1.490     droeschl 9075: 
1.409     foxr     9076: Master processs's USR1 processing is cojmplete.
                   9077: 
                   9078: =item (Red) CRITICAL: ------- Starting ------            
                   9079: 
                   9080: (There are more '-'s on either side).  Lond has forked itself off to 
                   9081: form a new session and is about to start actual initialization.
                   9082: 
                   9083: =item (Green) Attempting to start child (<client>)       
                   9084: 
                   9085: Started a new child process for <client>.  Client is IO::Socket object
                   9086: connected to the child.  This was as a result of a TCP/IP connection from a client.
                   9087: 
                   9088: =item Unable to determine who caller was, getpeername returned nothing
1.490     droeschl 9089: 
1.409     foxr     9090: In child process initialization.  either getpeername returned undef or
                   9091: a zero sized object was returned.  Processing continues, but in my opinion,
                   9092: this should be cause for the child to exit.
                   9093: 
                   9094: =item Unable to determine clientip                  
                   9095: 
                   9096: In child process initialization.  The peer address from getpeername was not defined.
                   9097: The client address is stored as "Unavailable" and processing continues.
                   9098: 
                   9099: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
1.490     droeschl 9100: 
1.409     foxr     9101: In child initialization.  A good connectionw as received from <ip>.
                   9102: 
                   9103: =over 2
                   9104: 
                   9105: =item <name> 
                   9106: 
                   9107: is the name of the client from hosts.tab.
                   9108: 
                   9109: =item <type> 
                   9110: 
                   9111: Is the connection type which is either 
                   9112: 
                   9113: =over 2
                   9114: 
                   9115: =item manager 
                   9116: 
                   9117: The connection is from a manager node, not in hosts.tab
                   9118: 
                   9119: =item client  
                   9120: 
                   9121: the connection is from a non-manager in the hosts.tab
                   9122: 
                   9123: =item both
                   9124: 
                   9125: The connection is from a manager in the hosts.tab.
                   9126: 
                   9127: =back
                   9128: 
                   9129: =back
                   9130: 
                   9131: =item (Blue) Certificates not installed -- trying insecure auth
                   9132: 
                   9133: One of the certificate file, key file or
                   9134: certificate authority file could not be found for a client attempting
                   9135: SSL connection intiation.  COnnection will be attemptied in in-secure mode.
                   9136: (this would be a system with an up to date lond that has not gotten a 
                   9137: certificate from us).
                   9138: 
                   9139: =item (Green)  Successful local authentication            
                   9140: 
                   9141: A local connection successfully negotiated the encryption key. 
                   9142: In this case the IDEA key is in a file (that is hopefully well protected).
                   9143: 
                   9144: =item (Green) Successful ssl authentication with <client>  
                   9145: 
                   9146: The client (<client> is the peer's name in hosts.tab), has successfully
                   9147: negotiated an SSL connection with this child process.
                   9148: 
                   9149: =item (Green) Successful insecure authentication with <client>
1.490     droeschl 9150: 
1.409     foxr     9151: 
                   9152: The client has successfully negotiated an  insecure connection withthe child process.
                   9153: 
                   9154: =item (Yellow) Attempted insecure connection disallowed    
                   9155: 
                   9156: The client attempted and failed to successfully negotiate a successful insecure
                   9157: connection.  This can happen either because the variable londAllowInsecure is false
                   9158: or undefined, or becuse the child did not successfully echo back the challenge
                   9159: string.
                   9160: 
                   9161: 
                   9162: =back
                   9163: 
1.441     raeburn  9164: =back
                   9165: 
1.409     foxr     9166: 
                   9167: =cut

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