Annotation of loncom/lond, revision 1.535

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

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