Annotation of loncom/lond, revision 1.536

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

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