Annotation of loncom/lond, revision 1.537

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

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