Annotation of loncom/lond, revision 1.547

1.1       albertel    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60      www         4: #
1.547   ! raeburn     5: # $Id: lond,v 1.546 2018/08/09 13:27:55 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.547   ! raeburn    68: my $VERSION='$Revision: 1.546 $'; #' 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.545     raeburn   111: my %crlchecked;                 # Will contain clients for which the client's SSL
                    112:                                 # has been checked against the cluster's Certificate
                    113:                                 # Revocation List.
                    114: 
1.480     raeburn   115: my $dist;
                    116: 
1.178     foxr      117: #
1.207     foxr      118: #   The hash below is used for command dispatching, and is therefore keyed on the request keyword.
                    119: #    Each element of the hash contains a reference to an array that contains:
                    120: #          A reference to a sub that executes the request corresponding to the keyword.
                    121: #          A flag that is true if the request must be encoded to be acceptable.
                    122: #          A mask with bits as follows:
                    123: #                      CLIENT_OK    - Set when the function is allowed by ordinary clients
                    124: #                      MANAGER_OK   - Set when the function is allowed to manager clients.
                    125: #
                    126: my $CLIENT_OK  = 1;
                    127: my $MANAGER_OK = 2;
                    128: my %Dispatcher;
                    129: 
                    130: 
                    131: #
1.178     foxr      132: #  The array below are password error strings."
                    133: #
                    134: my $lastpwderror    = 13;		# Largest error number from lcpasswd.
                    135: my @passwderrors = ("ok",
1.287     foxr      136: 		   "pwchange_failure - lcpasswd must be run as user 'www'",
                    137: 		   "pwchange_failure - lcpasswd got incorrect number of arguments",
                    138: 		   "pwchange_failure - lcpasswd did not get the right nubmer of input text lines",
                    139: 		   "pwchange_failure - lcpasswd too many simultaneous pwd changes in progress",
                    140: 		   "pwchange_failure - lcpasswd User does not exist.",
                    141: 		   "pwchange_failure - lcpasswd Incorrect current passwd",
                    142: 		   "pwchange_failure - lcpasswd Unable to su to root.",
                    143: 		   "pwchange_failure - lcpasswd Cannot set new passwd.",
                    144: 		   "pwchange_failure - lcpasswd Username has invalid characters",
                    145: 		   "pwchange_failure - lcpasswd Invalid characters in password",
                    146: 		   "pwchange_failure - lcpasswd User already exists", 
                    147:                    "pwchange_failure - lcpasswd Something went wrong with user addition.",
                    148: 		   "pwchange_failure - lcpasswd Password mismatch",
                    149: 		   "pwchange_failure - lcpasswd Error filename is invalid");
1.97      foxr      150: 
                    151: 
1.412     foxr      152: # This array are the errors from lcinstallfile:
                    153: 
                    154: my @installerrors = ("ok",
                    155: 		     "Initial user id of client not that of www",
                    156: 		     "Usage error, not enough command line arguments",
1.500     bisitz    157: 		     "Source filename does not exist",
                    158: 		     "Destination filename does not exist",
1.412     foxr      159: 		     "Some file operation failed",
                    160: 		     "Invalid table filename."
                    161: 		     );
1.207     foxr      162: 
                    163: #
1.525     raeburn   164: # The %trust hash classifies commands according to type of trust 
                    165: # required for execution of the command.
                    166: #
                    167: # When clients from a different institution request execution of a
                    168: # particular command, the trust settings for that institution set
                    169: # for this domain (or default domain for a multi-domain server) will
                    170: # be checked to see if running the command is allowed.
                    171: #
                    172: # Trust types which depend on the "Trust" domain configuration
                    173: # for the machine's default domain are:
                    174: #
                    175: # content   ("Access to this domain's content by others")
                    176: # shared    ("Access to other domain's content by this domain")
                    177: # enroll    ("Enrollment in this domain's courses by others")
                    178: # coaurem   ("Co-author roles for this domain's users elsewhere")
                    179: # domroles  ("Domain roles in this domain assignable to others")
                    180: # catalog   ("Course Catalog for this domain displayed elsewhere")
                    181: # reqcrs    ("Requests for creation of courses in this domain by others")
                    182: # msg       ("Users in other domains can send messages to this domain")
                    183: # 
                    184: # Trust type which depends on the User Session Hosting (remote) 
                    185: # domain configuration for machine's default domain is: "remote".
                    186: #
                    187: # Trust types which depend on contents of manager.tab in 
                    188: # /home/httpd/lonTabs is: "manageronly".
                    189: # 
                    190: # Trust type which requires client to share the same LON-CAPA
                    191: # "internet domain" (i.e., same institution as this server) is:
                    192: # "institutiononly".
                    193: #
                    194: 
                    195: my %trust = (
                    196:                auth => {remote => 1},
                    197:                autocreatepassword => {remote => 1},
                    198:                autocrsreqchecks => {remote => 1, reqcrs => 1},
                    199:                autocrsrequpdate => {remote => 1},
                    200:                autocrsreqvalidation => {remote => 1},
                    201:                autogetsections => {remote => 1},
                    202:                autoinstcodedefaults => {remote => 1, catalog => 1},
                    203:                autoinstcodeformat => {remote => 1, catalog => 1},
                    204:                autonewcourse => {remote => 1, reqcrs => 1},
                    205:                autophotocheck => {remote => 1, enroll => 1},
                    206:                autophotochoice => {remote => 1},
                    207:                autophotopermission => {remote => 1, enroll => 1},
                    208:                autopossibleinstcodes => {remote => 1, reqcrs => 1},
                    209:                autoretrieve => {remote => 1, enroll => 1, catalog => 1},
                    210:                autorun => {remote => 1, enroll => 1, reqcrs => 1},
                    211:                autovalidateclass_sec => {catalog => 1},
                    212:                autovalidatecourse => {remote => 1, enroll => 1},
                    213:                autovalidateinstcode => {domroles => 1, remote => 1, enroll => 1},
                    214:                changeuserauth => {remote => 1, domroles => 1},
                    215:                chatretr => {remote => 1, enroll => 1},
                    216:                chatsend => {remote => 1, enroll => 1},
                    217:                courseiddump => {remote => 1, domroles => 1, enroll => 1},
                    218:                courseidput => {remote => 1, domroles => 1, enroll => 1},
                    219:                courseidputhash => {remote => 1, domroles => 1, enroll => 1},
                    220:                courselastaccess => {remote => 1, domroles => 1, enroll => 1},
                    221:                currentauth => {remote => 1, domroles => 1, enroll => 1},
                    222:                currentdump => {remote => 1, enroll => 1},
                    223:                currentversion => {remote=> 1, content => 1},
                    224:                dcmaildump => {remote => 1, domroles => 1},
                    225:                dcmailput => {remote => 1, domroles => 1},
                    226:                del => {remote => 1, domroles => 1, enroll => 1, content => 1},
                    227:                deldom => {remote => 1, domroles => 1}, # not currently used
                    228:                devalidatecache => {institutiononly => 1},
                    229:                domroleput => {remote => 1, enroll => 1},
                    230:                domrolesdump => {remote => 1, catalog => 1},
                    231:                du => {remote => 1, enroll => 1},
                    232:                du2 => {remote => 1, enroll => 1},
                    233:                dump => {remote => 1, enroll => 1, domroles => 1},
                    234:                edit => {institutiononly => 1},  #not used currently
                    235:                eget => {remote => 1, domroles => 1, enroll => 1}, #not used currently
1.536     raeburn   236:                egetdom => {remote => 1, domroles => 1, enroll => 1, },
1.525     raeburn   237:                ekey => {}, #not used currently
                    238:                exit => {anywhere => 1},
                    239:                fetchuserfile => {remote => 1, enroll => 1},
                    240:                get => {remote => 1, domroles => 1, enroll => 1},
                    241:                getdom => {anywhere => 1},
                    242:                home => {anywhere => 1},
                    243:                iddel => {remote => 1, enroll => 1},
                    244:                idget => {remote => 1, enroll => 1},
                    245:                idput => {remote => 1, domroles => 1, enroll => 1},
                    246:                inc => {remote => 1, enroll => 1},
                    247:                init => {anywhere => 1},
                    248:                inst_usertypes => {remote => 1, domroles => 1, enroll => 1},
                    249:                instemailrules => {remote => 1, domroles => 1},
                    250:                instidrulecheck => {remote => 1, domroles => 1,},
                    251:                instidrules => {remote => 1, domroles => 1,},
                    252:                instrulecheck => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
                    253:                instselfcreatecheck => {institutiononly => 1},
                    254:                instuserrules => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
                    255:                keys => {remote => 1,},
                    256:                load => {anywhere => 1},
                    257:                log => {anywhere => 1},
                    258:                ls => {remote => 1, enroll => 1, content => 1,},
                    259:                ls2 => {remote => 1, enroll => 1, content => 1,},
                    260:                ls3 => {remote => 1, enroll => 1, content => 1,},
                    261:                makeuser => {remote => 1, enroll => 1, domroles => 1,},
                    262:                mkdiruserfile => {remote => 1, enroll => 1,},
                    263:                newput => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1,},
                    264:                passwd => {remote => 1},
                    265:                ping => {anywhere => 1},
                    266:                pong => {anywhere => 1},
                    267:                pushfile => {manageronly => 1},
                    268:                put => {remote => 1, enroll => 1, domroles => 1, msg => 1, content => 1, shared => 1},
                    269:                putdom => {remote => 1, domroles => 1,},
                    270:                putstore => {remote => 1, enroll => 1},
                    271:                queryreply => {anywhere => 1},
                    272:                querysend => {anywhere => 1},
1.535     raeburn   273:                querysend_activitylog => {remote => 1},
                    274:                querysend_allusers => {remote => 1, domroles => 1},
                    275:                querysend_courselog => {remote => 1},
                    276:                querysend_fetchenrollment => {remote => 1},
                    277:                querysend_getinstuser => {remote => 1},
                    278:                querysend_getmultinstusers => {remote => 1},
                    279:                querysend_instdirsearch => {remote => 1, domroles => 1, coaurem => 1},
                    280:                querysend_institutionalphotos => {remote => 1},
                    281:                querysend_portfolio_metadata => {remote => 1, content => 1},
                    282:                querysend_userlog => {remote => 1, domroles => 1},
                    283:                querysend_usersearch => {remote => 1, enroll => 1, coaurem => 1},
1.525     raeburn   284:                quit => {anywhere => 1},
                    285:                readlonnetglobal => {institutiononly => 1},
                    286:                reinit => {manageronly => 1}, #not used currently
                    287:                removeuserfile => {remote => 1, enroll => 1},
                    288:                renameuserfile => {remote => 1,},
                    289:                restore => {remote => 1, enroll => 1, reqcrs => 1,},
                    290:                rolesdel => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
                    291:                rolesput => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
1.527     raeburn   292:                servercerts => {institutiononly => 1},
1.528     raeburn   293:                serverdistarch => {anywhere => 1},
1.525     raeburn   294:                serverhomeID => {anywhere => 1},
                    295:                serverloncaparev => {anywhere => 1},
                    296:                servertimezone => {remote => 1, enroll => 1},
                    297:                setannounce => {remote => 1, domroles => 1},
                    298:                sethost => {anywhere => 1},
                    299:                store => {remote => 1, enroll => 1, reqcrs => 1,},
                    300:                studentphoto => {remote => 1, enroll => 1},
                    301:                sub => {content => 1,},
                    302:                tmpdel => {anywhere => 1},
                    303:                tmpget => {anywhere => 1},
                    304:                tmpput => {anywhere => 1},
                    305:                tokenauthuserfile => {anywhere => 1},
                    306:                unsub => {content => 1,},
                    307:                update => {shared => 1},
                    308:                updateclickers => {remote => 1},
                    309:                userhassession => {anywhere => 1},
                    310:                userload => {anywhere => 1},
                    311:                version => {anywhere => 1}, #not used
                    312:             );
                    313: 
                    314: #
1.207     foxr      315: #   Statistics that are maintained and dislayed in the status line.
                    316: #
1.212     foxr      317: my $Transactions = 0;		# Number of attempted transactions.
                    318: my $Failures     = 0;		# Number of transcations failed.
1.207     foxr      319: 
                    320: #   ResetStatistics: 
                    321: #      Resets the statistics counters:
                    322: #
                    323: sub ResetStatistics {
                    324:     $Transactions = 0;
                    325:     $Failures     = 0;
                    326: }
                    327: 
1.200     matthew   328: #------------------------------------------------------------------------
                    329: #
                    330: #   LocalConnection
                    331: #     Completes the formation of a locally authenticated connection.
                    332: #     This function will ensure that the 'remote' client is really the
                    333: #     local host.  If not, the connection is closed, and the function fails.
                    334: #     If so, initcmd is parsed for the name of a file containing the
                    335: #     IDEA session key.  The fie is opened, read, deleted and the session
                    336: #     key returned to the caller.
                    337: #
                    338: # Parameters:
                    339: #   $Socket      - Socket open on client.
                    340: #   $initcmd     - The full text of the init command.
                    341: #
                    342: # Returns:
                    343: #     IDEA session key on success.
                    344: #     undef on failure.
                    345: #
                    346: sub LocalConnection {
                    347:     my ($Socket, $initcmd) = @_;
1.373     albertel  348:     Debug("Attempting local connection: $initcmd client: $clientip");
1.277     albertel  349:     if($clientip ne "127.0.0.1") {
1.200     matthew   350: 	&logthis('<font color="red"> LocalConnection rejecting non local: '
1.373     albertel  351: 		 ."$clientip ne 127.0.0.1 </font>");
1.200     matthew   352: 	close $Socket;
                    353: 	return undef;
1.224     foxr      354:     }  else {
1.200     matthew   355: 	chomp($initcmd);	# Get rid of \n in filename.
                    356: 	my ($init, $type, $name) = split(/:/, $initcmd);
                    357: 	Debug(" Init command: $init $type $name ");
                    358: 
                    359: 	# Require that $init = init, and $type = local:  Otherwise
                    360: 	# the caller is insane:
                    361: 
                    362: 	if(($init ne "init") && ($type ne "local")) {
                    363: 	    &logthis('<font color = "red"> LocalConnection: caller is insane! '
                    364: 		     ."init = $init, and type = $type </font>");
                    365: 	    close($Socket);;
                    366: 	    return undef;
                    367: 		
                    368: 	}
                    369: 	#  Now get the key filename:
                    370: 
                    371: 	my $IDEAKey = lonlocal::ReadKeyFile($name);
                    372: 	return $IDEAKey;
                    373:     }
                    374: }
                    375: #------------------------------------------------------------------------------
                    376: #
                    377: #  SSLConnection
                    378: #   Completes the formation of an ssh authenticated connection. The
                    379: #   socket is promoted to an ssl socket.  If this promotion and the associated
                    380: #   certificate exchange are successful, the IDEA key is generated and sent
                    381: #   to the remote peer via the SSL tunnel. The IDEA key is also returned to
                    382: #   the caller after the SSL tunnel is torn down.
                    383: #
                    384: # Parameters:
                    385: #   Name              Type             Purpose
                    386: #   $Socket          IO::Socket::INET  Plaintext socket.
                    387: #
                    388: # Returns:
                    389: #    IDEA key on success.
                    390: #    undef on failure.
                    391: #
                    392: sub SSLConnection {
                    393:     my $Socket   = shift;
                    394: 
                    395:     Debug("SSLConnection: ");
                    396:     my $KeyFile         = lonssl::KeyFile();
                    397:     if(!$KeyFile) {
                    398: 	my $err = lonssl::LastError();
                    399: 	&logthis("<font color=\"red\"> CRITICAL"
                    400: 		 ."Can't get key file $err </font>");
                    401: 	return undef;
                    402:     }
                    403:     my ($CACertificate,
                    404: 	$Certificate) = lonssl::CertificateFile();
                    405: 
                    406: 
                    407:     # If any of the key, certificate or certificate authority 
                    408:     # certificate filenames are not defined, this can't work.
                    409: 
                    410:     if((!$Certificate) || (!$CACertificate)) {
                    411: 	my $err = lonssl::LastError();
                    412: 	&logthis("<font color=\"red\"> CRITICAL"
                    413: 		 ."Can't get certificates: $err </font>");
                    414: 
                    415: 	return undef;
                    416:     }
                    417:     Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
                    418: 
                    419:     # Indicate to our peer that we can procede with
                    420:     # a transition to ssl authentication:
                    421: 
                    422:     print $Socket "ok:ssl\n";
                    423: 
                    424:     Debug("Approving promotion -> ssl");
                    425:     #  And do so:
                    426: 
1.545     raeburn   427:     my $CRLFile;
                    428:     unless ($crlchecked{$clientname}) {
                    429:         $CRLFile = lonssl::CRLFile();
                    430:         $crlchecked{$clientname} = 1;
                    431:     }
                    432: 
1.200     matthew   433:     my $SSLSocket = lonssl::PromoteServerSocket($Socket,
                    434: 						$CACertificate,
                    435: 						$Certificate,
1.544     raeburn   436: 						$KeyFile,
1.545     raeburn   437: 						$clientname,
1.546     raeburn   438:                                                 $CRLFile,
                    439:                                                 $clientversion);
1.200     matthew   440:     if(! ($SSLSocket) ) {	# SSL socket promotion failed.
                    441: 	my $err = lonssl::LastError();
                    442: 	&logthis("<font color=\"red\"> CRITICAL "
                    443: 		 ."SSL Socket promotion failed: $err </font>");
                    444: 	return undef;
                    445:     }
                    446:     Debug("SSL Promotion successful");
                    447: 
                    448:     # 
                    449:     #  The only thing we'll use the socket for is to send the IDEA key
                    450:     #  to the peer:
                    451: 
                    452:     my $Key = lonlocal::CreateCipherKey();
                    453:     print $SSLSocket "$Key\n";
                    454: 
                    455:     lonssl::Close($SSLSocket); 
                    456: 
                    457:     Debug("Key exchange complete: $Key");
                    458: 
                    459:     return $Key;
                    460: }
                    461: #
                    462: #     InsecureConnection: 
                    463: #        If insecure connections are allowd,
                    464: #        exchange a challenge with the client to 'validate' the
                    465: #        client (not really, but that's the protocol):
                    466: #        We produce a challenge string that's sent to the client.
                    467: #        The client must then echo the challenge verbatim to us.
                    468: #
                    469: #  Parameter:
                    470: #      Socket      - Socket open on the client.
                    471: #  Returns:
                    472: #      1           - success.
                    473: #      0           - failure (e.g.mismatch or insecure not allowed).
                    474: #
                    475: sub InsecureConnection {
                    476:     my $Socket  =  shift;
                    477: 
                    478:     #   Don't even start if insecure connections are not allowed.
1.532     raeburn   479:     #   return 0 if Insecure connections not allowed.
                    480:     #
                    481:     if (ref($secureconf{'connfrom'}) eq 'HASH') {
                    482:         if ($clientsamedom) {
                    483:             if ($secureconf{'connfrom'}{'dom'} eq 'req') {
                    484:                 return 0;
                    485:             } 
                    486:         } elsif ($clientsameinst) {
                    487:             if ($secureconf{'connfrom'}{'intdom'} eq 'req') {
                    488:                 return 0;
                    489:             }
                    490:         } else {
                    491:             if ($secureconf{'connfrom'}{'other'} eq 'req') {
                    492:                 return 0;
                    493:             }
                    494:         }
                    495:     } elsif (!$perlvar{londAllowInsecure}) {
1.200     matthew   496: 	return 0;
                    497:     }
                    498: 
                    499:     #   Fabricate a challenge string and send it..
                    500: 
                    501:     my $challenge = "$$".time;	# pid + time.
                    502:     print $Socket "$challenge\n";
                    503:     &status("Waiting for challenge reply");
                    504: 
                    505:     my $answer = <$Socket>;
                    506:     $answer    =~s/\W//g;
                    507:     if($challenge eq $answer) {
                    508: 	return 1;
1.224     foxr      509:     } else {
1.200     matthew   510: 	logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
                    511: 	&status("No challenge reqply");
                    512: 	return 0;
                    513:     }
                    514:     
                    515: 
                    516: }
1.251     foxr      517: #
                    518: #   Safely execute a command (as long as it's not a shel command and doesn
                    519: #   not require/rely on shell escapes.   The function operates by doing a
                    520: #   a pipe based fork and capturing stdout and stderr  from the pipe.
                    521: #
                    522: # Formal Parameters:
                    523: #     $line                    - A line of text to be executed as a command.
                    524: # Returns:
                    525: #     The output from that command.  If the output is multiline the caller
                    526: #     must know how to split up the output.
                    527: #
                    528: #
                    529: sub execute_command {
                    530:     my ($line)    = @_;
                    531:     my @words     = split(/\s/, $line);	# Bust the command up into words.
                    532:     my $output    = "";
                    533: 
                    534:     my $pid = open(CHILD, "-|");
                    535:     
                    536:     if($pid) {			# Parent process
                    537: 	Debug("In parent process for execute_command");
                    538: 	my @data = <CHILD>;	# Read the child's outupt...
                    539: 	close CHILD;
                    540: 	foreach my $output_line (@data) {
                    541: 	    Debug("Adding $output_line");
                    542: 	    $output .= $output_line; # Presumably has a \n on it.
                    543: 	}
                    544: 
                    545:     } else {			# Child process
                    546: 	close (STDERR);
                    547: 	open  (STDERR, ">&STDOUT");# Combine stderr, and stdout...
                    548: 	exec(@words);		# won't return.
                    549:     }
                    550:     return $output;
                    551: }
                    552: 
1.200     matthew   553: 
1.140     foxr      554: #   GetCertificate: Given a transaction that requires a certificate,
                    555: #   this function will extract the certificate from the transaction
                    556: #   request.  Note that at this point, the only concept of a certificate
                    557: #   is the hostname to which we are connected.
                    558: #
                    559: #   Parameter:
                    560: #      request   - The request sent by our client (this parameterization may
                    561: #                  need to change when we really use a certificate granting
                    562: #                  authority.
                    563: #
                    564: sub GetCertificate {
                    565:     my $request = shift;
                    566: 
                    567:     return $clientip;
                    568: }
1.161     foxr      569: 
1.178     foxr      570: #
                    571: #   Return true if client is a manager.
                    572: #
                    573: sub isManager {
                    574:     return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
                    575: }
                    576: #
                    577: #   Return tru if client can do client functions
                    578: #
                    579: sub isClient {
                    580:     return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
                    581: }
1.161     foxr      582: 
                    583: 
1.156     foxr      584: #
                    585: #   ReadManagerTable: Reads in the current manager table. For now this is
                    586: #                     done on each manager authentication because:
                    587: #                     - These authentications are not frequent
                    588: #                     - This allows dynamic changes to the manager table
                    589: #                       without the need to signal to the lond.
                    590: #
                    591: sub ReadManagerTable {
                    592: 
1.412     foxr      593:     &Debug("Reading manager table");
1.156     foxr      594:     #   Clean out the old table first..
                    595: 
1.166     foxr      596:    foreach my $key (keys %managers) {
                    597:       delete $managers{$key};
                    598:    }
                    599: 
                    600:    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
                    601:    if (!open (MANAGERS, $tablename)) {
1.473     raeburn   602:        my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
                    603:        if (&Apache::lonnet::is_LC_dns($hostname)) {
1.472     raeburn   604:            &logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
                    605:        }
                    606:        return;
1.166     foxr      607:    }
                    608:    while(my $host = <MANAGERS>) {
                    609:       chomp($host);
                    610:       if ($host =~ "^#") {                  # Comment line.
                    611:          next;
                    612:       }
1.368     albertel  613:       if (!defined &Apache::lonnet::get_host_ip($host)) { # This is a non cluster member
1.161     foxr      614: 	    #  The entry is of the form:
                    615: 	    #    cluname:hostname
                    616: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
                    617: 	    #            the host key.
                    618: 	    #  hostname- The dns name of the host.
                    619: 	    #
1.166     foxr      620:           my($cluname, $dnsname) = split(/:/, $host);
                    621:           
                    622:           my $ip = gethostbyname($dnsname);
                    623:           if(defined($ip)) {                 # bad names don't deserve entry.
                    624:             my $hostip = inet_ntoa($ip);
                    625:             $managers{$hostip} = $cluname;
                    626:             logthis('<font color="green"> registering manager '.
                    627:                     "$dnsname as $cluname with $hostip </font>\n");
                    628:          }
                    629:       } else {
                    630:          logthis('<font color="green"> existing host'." $host</font>\n");
1.472     raeburn   631:          $managers{&Apache::lonnet::get_host_ip($host)} = $host;  # Use info from cluster tab if cluster memeber
1.166     foxr      632:       }
                    633:    }
1.156     foxr      634: }
1.140     foxr      635: 
                    636: #
                    637: #  ValidManager: Determines if a given certificate represents a valid manager.
                    638: #                in this primitive implementation, the 'certificate' is
                    639: #                just the connecting loncapa client name.  This is checked
                    640: #                against a valid client list in the configuration.
                    641: #
                    642: #                  
                    643: sub ValidManager {
                    644:     my $certificate = shift; 
                    645: 
1.163     foxr      646:     return isManager;
1.140     foxr      647: }
                    648: #
1.143     foxr      649: #  CopyFile:  Called as part of the process of installing a 
                    650: #             new configuration file.  This function copies an existing
                    651: #             file to a backup file.
                    652: # Parameters:
                    653: #     oldfile  - Name of the file to backup.
                    654: #     newfile  - Name of the backup file.
                    655: # Return:
                    656: #     0   - Failure (errno has failure reason).
                    657: #     1   - Success.
                    658: #
                    659: sub CopyFile {
1.192     foxr      660: 
                    661:     my ($oldfile, $newfile) = @_;
1.143     foxr      662: 
1.281     matthew   663:     if (! copy($oldfile,$newfile)) {
                    664:         return 0;
1.143     foxr      665:     }
1.281     matthew   666:     chmod(0660, $newfile);
                    667:     return 1;
1.143     foxr      668: }
1.157     foxr      669: #
                    670: #  Host files are passed out with externally visible host IPs.
                    671: #  If, for example, we are behind a fire-wall or NAT host, our 
                    672: #  internally visible IP may be different than the externally
                    673: #  visible IP.  Therefore, we always adjust the contents of the
                    674: #  host file so that the entry for ME is the IP that we believe
                    675: #  we have.  At present, this is defined as the entry that
                    676: #  DNS has for us.  If by some chance we are not able to get a
                    677: #  DNS translation for us, then we assume that the host.tab file
                    678: #  is correct.  
                    679: #    BUGBUGBUG - in the future, we really should see if we can
                    680: #       easily query the interface(s) instead.
                    681: # Parameter(s):
                    682: #     contents    - The contents of the host.tab to check.
                    683: # Returns:
                    684: #     newcontents - The adjusted contents.
                    685: #
                    686: #
                    687: sub AdjustHostContents {
                    688:     my $contents  = shift;
                    689:     my $adjusted;
                    690:     my $me        = $perlvar{'lonHostID'};
                    691: 
1.354     albertel  692:     foreach my $line (split(/\n/,$contents)) {
1.472     raeburn   693: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/) ||
                    694:              ($line =~ /^\s*\^/))) {
1.157     foxr      695: 	    chomp($line);
                    696: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
                    697: 	    if ($id eq $me) {
1.354     albertel  698: 		my $ip = gethostbyname($name);
                    699: 		my $ipnew = inet_ntoa($ip);
                    700: 		$ip = $ipnew;
1.157     foxr      701: 		#  Reconstruct the host line and append to adjusted:
                    702: 		
1.354     albertel  703: 		my $newline = "$id:$domain:$role:$name:$ip";
                    704: 		if($maxcon ne "") { # Not all hosts have loncnew tuning params
                    705: 		    $newline .= ":$maxcon:$idleto:$mincon";
                    706: 		}
                    707: 		$adjusted .= $newline."\n";
1.157     foxr      708: 		
1.354     albertel  709: 	    } else {		# Not me, pass unmodified.
                    710: 		$adjusted .= $line."\n";
                    711: 	    }
1.157     foxr      712: 	} else {                  # Blank or comment never re-written.
                    713: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
                    714: 	}
1.354     albertel  715:     }
                    716:     return $adjusted;
1.157     foxr      717: }
1.143     foxr      718: #
                    719: #   InstallFile: Called to install an administrative file:
1.412     foxr      720: #       - The file is created int a temp directory called <name>.tmp
                    721: #       - lcinstall file is called to install the file.
                    722: #         since the web app has no direct write access to the table directory
1.143     foxr      723: #
                    724: #  Parameters:
                    725: #       Name of the file
                    726: #       File Contents.
                    727: #  Return:
                    728: #      nonzero - success.
                    729: #      0       - failure and $! has an errno.
1.412     foxr      730: # Assumptions:
                    731: #    File installtion is a relatively infrequent
1.143     foxr      732: #
                    733: sub InstallFile {
1.192     foxr      734: 
                    735:     my ($Filename, $Contents) = @_;
1.412     foxr      736: #     my $TempFile = $Filename.".tmp";
                    737:     my $exedir = $perlvar{'lonDaemons'};
                    738:     my $tmpdir = $exedir.'/tmp/';
                    739:     my $TempFile = $tmpdir."TempTableFile.tmp";
1.143     foxr      740: 
                    741:     #  Open the file for write:
                    742: 
                    743:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
                    744:     if(!(defined $fh)) {
                    745: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
                    746: 	return 0;
                    747:     }
                    748:     #  write the contents of the file:
                    749: 
                    750:     print $fh ($Contents); 
                    751:     $fh->close;			# In case we ever have a filesystem w. locking
                    752: 
1.412     foxr      753:     chmod(0664, $TempFile);	# Everyone can write it.
                    754: 
                    755:     # Use lcinstall file to put the file in the table directory...
                    756: 
                    757:     &Debug("Opening pipe to $exedir/lcinstallfile $TempFile $Filename");
                    758:     my $pf = IO::File->new("| $exedir/lcinstallfile   $TempFile $Filename > $exedir/logs/lcinstallfile.log");
                    759:     close $pf;
                    760:     my $err = $?;
                    761:     &Debug("Status is $err");
                    762:     if ($err != 0) {
                    763: 	my $msg = $err;
                    764: 	if ($err < @installerrors) {
                    765: 	    $msg = $installerrors[$err];
                    766: 	}
                    767: 	&logthis("Install failed for table file $Filename : $msg");
                    768: 	return 0;
                    769:     }
                    770: 
                    771:     # Remove the temp file:
1.143     foxr      772: 
1.412     foxr      773:     unlink($TempFile);
1.143     foxr      774: 
                    775:     return 1;
                    776: }
1.200     matthew   777: 
                    778: 
1.169     foxr      779: #
                    780: #   ConfigFileFromSelector: converts a configuration file selector
1.411     foxr      781: #                 into a configuration file pathname.
1.472     raeburn   782: #                 Supports the following file selectors: 
                    783: #                 hosts, domain, dns_hosts, dns_domain  
1.411     foxr      784: #
1.169     foxr      785: #
                    786: #  Parameters:
                    787: #      selector  - Configuration file selector.
                    788: #  Returns:
                    789: #      Full path to the file or undef if the selector is invalid.
                    790: #
                    791: sub ConfigFileFromSelector {
                    792:     my $selector   = shift;
                    793:     my $tablefile;
                    794: 
                    795:     my $tabledir = $perlvar{'lonTabDir'}.'/';
1.472     raeburn   796:     if (($selector eq "hosts") || ($selector eq "domain") || 
                    797:         ($selector eq "dns_hosts") || ($selector eq "dns_domain")) {
1.411     foxr      798: 	$tablefile =  $tabledir.$selector.'.tab';
1.169     foxr      799:     }
                    800:     return $tablefile;
                    801: }
1.143     foxr      802: #
1.141     foxr      803: #   PushFile:  Called to do an administrative push of a file.
                    804: #              - Ensure the file being pushed is one we support.
                    805: #              - Backup the old file to <filename.saved>
                    806: #              - Separate the contents of the new file out from the
                    807: #                rest of the request.
                    808: #              - Write the new file.
                    809: #  Parameter:
                    810: #     Request - The entire user request.  This consists of a : separated
                    811: #               string pushfile:tablename:contents.
                    812: #     NOTE:  The contents may have :'s in it as well making things a bit
                    813: #            more interesting... but not much.
                    814: #  Returns:
                    815: #     String to send to client ("ok" or "refused" if bad file).
                    816: #
                    817: sub PushFile {
1.510     raeburn   818:     my $request = shift;
1.141     foxr      819:     my ($command, $filename, $contents) = split(":", $request, 3);
1.412     foxr      820:     &Debug("PushFile");
1.141     foxr      821:     
                    822:     #  At this point in time, pushes for only the following tables are
                    823:     #  supported:
                    824:     #   hosts.tab  ($filename eq host).
                    825:     #   domain.tab ($filename eq domain).
1.472     raeburn   826:     #   dns_hosts.tab ($filename eq dns_host).
                    827:     #   dns_domain.tab ($filename eq dns_domain). 
1.141     foxr      828:     # Construct the destination filename or reject the request.
                    829:     #
                    830:     # lonManage is supposed to ensure this, however this session could be
                    831:     # part of some elaborate spoof that managed somehow to authenticate.
                    832:     #
                    833: 
1.169     foxr      834: 
                    835:     my $tablefile = ConfigFileFromSelector($filename);
                    836:     if(! (defined $tablefile)) {
1.141     foxr      837: 	return "refused";
                    838:     }
1.412     foxr      839: 
1.157     foxr      840:     #  If the file being pushed is the host file, we adjust the entry for ourself so that the
                    841:     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
                    842:     #  to conceive of conditions where we don't have a DNS entry locally.  This is possible in a 
                    843:     #  network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
                    844:     #  that possibilty.
                    845: 
                    846:     if($filename eq "host") {
                    847: 	$contents = AdjustHostContents($contents);
1.510     raeburn   848:     } elsif ($filename eq 'dns_host' || $filename eq 'dns_domain') {
                    849:         if ($contents eq '') {
                    850:             &logthis('<font color="red"> Pushfile: unable to install '
                    851:                     .$tablefile." - no data received from push. </font>");
                    852:             return 'error: push had no data';
                    853:         }
                    854:         if (&Apache::lonnet::get_host_ip($clientname)) {
                    855:             my $clienthost = &Apache::lonnet::hostname($clientname);
                    856:             if ($managers{$clientip} eq $clientname) {
                    857:                 my $clientprotocol = $Apache::lonnet::protocol{$clientname};
                    858:                 $clientprotocol = 'http' if ($clientprotocol ne 'https');
                    859:                 my $url = '/adm/'.$filename;
                    860:                 $url =~ s{_}{/};
                    861:                 my $request=new HTTP::Request('GET',"$clientprotocol://$clienthost$url");
1.523     raeburn   862:                 my $response = LONCAPA::LWPReq::makerequest($clientname,$request,'',\%perlvar,60,0);
1.510     raeburn   863:                 if ($response->is_error()) {
                    864:                     &logthis('<font color="red"> Pushfile: unable to install '
                    865:                             .$tablefile." - error attempting to pull data. </font>");
                    866:                     return 'error: pull failed';
                    867:                 } else {
                    868:                     my $result = $response->content;
                    869:                     chomp($result);
                    870:                     unless ($result eq $contents) {
                    871:                         &logthis('<font color="red"> Pushfile: unable to install '
                    872:                                 .$tablefile." - pushed data and pulled data differ. </font>");
                    873:                         my $pushleng = length($contents);
                    874:                         my $pullleng = length($result);
                    875:                         if ($pushleng != $pullleng) {
                    876:                             return "error: $pushleng vs $pullleng bytes";
                    877:                         } else {
                    878:                             return "error: mismatch push and pull";
                    879:                         }
                    880:                     }
                    881:                 }
                    882:             }
                    883:         }
1.157     foxr      884:     }
                    885: 
1.141     foxr      886:     #  Install the new file:
                    887: 
1.412     foxr      888:     &logthis("Installing new $tablefile contents:\n$contents");
1.143     foxr      889:     if(!InstallFile($tablefile, $contents)) {
                    890: 	&logthis('<font color="red"> Pushfile: unable to install '
1.145     foxr      891: 	 .$tablefile." $! </font>");
1.143     foxr      892: 	return "error:$!";
1.224     foxr      893:     } else {
1.143     foxr      894: 	&logthis('<font color="green"> Installed new '.$tablefile
1.473     raeburn   895: 		 ." - transaction by: $clientname ($clientip)</font>");
1.472     raeburn   896:         my $adminmail = $perlvar{'lonAdmEMail'};
                    897:         my $admindom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                    898:         if ($admindom ne '') {
                    899:             my %domconfig =
                    900:                 &Apache::lonnet::get_dom('configuration',['contacts'],$admindom);
                    901:             if (ref($domconfig{'contacts'}) eq 'HASH') {
                    902:                 if ($domconfig{'contacts'}{'adminemail'} ne '') {
                    903:                     $adminmail = $domconfig{'contacts'}{'adminemail'};
                    904:                 }
                    905:             }
                    906:         }
                    907:         if ($adminmail =~ /^[^\@]+\@[^\@]+$/) {
                    908:             my $msg = new Mail::Send;
                    909:             $msg->to($adminmail);
                    910:             $msg->subject('LON-CAPA DNS update on '.$perlvar{'lonHostID'});
                    911:             $msg->add('Content-type','text/plain; charset=UTF-8');
                    912:             if (my $fh = $msg->open()) {
                    913:                 print $fh 'Update to '.$tablefile.' from Cluster Manager '.
1.473     raeburn   914:                           "$clientname ($clientip)\n";
1.472     raeburn   915:                 $fh->close;
                    916:             }
                    917:         }
1.143     foxr      918:     }
                    919: 
1.141     foxr      920:     #  Indicate success:
                    921:  
                    922:     return "ok";
                    923: 
                    924: }
1.145     foxr      925: 
                    926: #
                    927: #  Called to re-init either lonc or lond.
                    928: #
                    929: #  Parameters:
                    930: #    request   - The full request by the client.  This is of the form
                    931: #                reinit:<process>  
                    932: #                where <process> is allowed to be either of 
                    933: #                lonc or lond
                    934: #
                    935: #  Returns:
                    936: #     The string to be sent back to the client either:
                    937: #   ok         - Everything worked just fine.
                    938: #   error:why  - There was a failure and why describes the reason.
                    939: #
                    940: #
                    941: sub ReinitProcess {
                    942:     my $request = shift;
                    943: 
1.146     foxr      944: 
                    945:     # separate the request (reinit) from the process identifier and
                    946:     # validate it producing the name of the .pid file for the process.
                    947:     #
                    948:     #
                    949:     my ($junk, $process) = split(":", $request);
1.147     foxr      950:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
1.146     foxr      951:     if($process eq 'lonc') {
                    952: 	$processpidfile = $processpidfile."lonc.pid";
1.147     foxr      953: 	if (!open(PIDFILE, "< $processpidfile")) {
                    954: 	    return "error:Open failed for $processpidfile";
                    955: 	}
                    956: 	my $loncpid = <PIDFILE>;
                    957: 	close(PIDFILE);
                    958: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
                    959: 		."</font>");
                    960: 	kill("USR2", $loncpid);
1.146     foxr      961:     } elsif ($process eq 'lond') {
1.147     foxr      962: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
                    963: 	&UpdateHosts;			# Lond is us!!
1.146     foxr      964:     } else {
                    965: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
                    966: 		 ."</font>");
                    967: 	return "error:Invalid process identifier $process";
                    968:     }
1.145     foxr      969:     return 'ok';
                    970: }
1.168     foxr      971: #   Validate a line in a configuration file edit script:
                    972: #   Validation includes:
                    973: #     - Ensuring the command is valid.
                    974: #     - Ensuring the command has sufficient parameters
                    975: #   Parameters:
                    976: #     scriptline - A line to validate (\n has been stripped for what it's worth).
1.167     foxr      977: #
1.168     foxr      978: #   Return:
                    979: #      0     - Invalid scriptline.
                    980: #      1     - Valid scriptline
                    981: #  NOTE:
                    982: #     Only the command syntax is checked, not the executability of the
                    983: #     command.
                    984: #
                    985: sub isValidEditCommand {
                    986:     my $scriptline = shift;
                    987: 
                    988:     #   Line elements are pipe separated:
                    989: 
                    990:     my ($command, $key, $newline)  = split(/\|/, $scriptline);
                    991:     &logthis('<font color="green"> isValideditCommand checking: '.
                    992: 	     "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
                    993:     
                    994:     if ($command eq "delete") {
                    995: 	#
                    996: 	#   key with no newline.
                    997: 	#
                    998: 	if( ($key eq "") || ($newline ne "")) {
                    999: 	    return 0;		# Must have key but no newline.
                   1000: 	} else {
                   1001: 	    return 1;		# Valid syntax.
                   1002: 	}
1.169     foxr     1003:     } elsif ($command eq "replace") {
1.168     foxr     1004: 	#
                   1005: 	#   key and newline:
                   1006: 	#
                   1007: 	if (($key eq "") || ($newline eq "")) {
                   1008: 	    return 0;
                   1009: 	} else {
                   1010: 	    return 1;
                   1011: 	}
1.169     foxr     1012:     } elsif ($command eq "append") {
                   1013: 	if (($key ne "") && ($newline eq "")) {
                   1014: 	    return 1;
                   1015: 	} else {
                   1016: 	    return 0;
                   1017: 	}
1.168     foxr     1018:     } else {
                   1019: 	return 0;		# Invalid command.
                   1020:     }
                   1021:     return 0;			# Should not get here!!!
                   1022: }
1.169     foxr     1023: #
                   1024: #   ApplyEdit - Applies an edit command to a line in a configuration 
                   1025: #               file.  It is the caller's responsiblity to validate the
                   1026: #               edit line.
                   1027: #   Parameters:
                   1028: #      $directive - A single edit directive to apply.  
                   1029: #                   Edit directives are of the form:
                   1030: #                  append|newline      - Appends a new line to the file.
                   1031: #                  replace|key|newline - Replaces the line with key value 'key'
                   1032: #                  delete|key          - Deletes the line with key value 'key'.
                   1033: #      $editor   - A config file editor object that contains the
                   1034: #                  file being edited.
                   1035: #
                   1036: sub ApplyEdit {
1.192     foxr     1037: 
                   1038:     my ($directive, $editor) = @_;
1.169     foxr     1039: 
                   1040:     # Break the directive down into its command and its parameters
                   1041:     # (at most two at this point.  The meaning of the parameters, if in fact
                   1042:     #  they exist depends on the command).
                   1043: 
                   1044:     my ($command, $p1, $p2) = split(/\|/, $directive);
                   1045: 
                   1046:     if($command eq "append") {
                   1047: 	$editor->Append($p1);	          # p1 - key p2 null.
                   1048:     } elsif ($command eq "replace") {
                   1049: 	$editor->ReplaceLine($p1, $p2);   # p1 - key p2 = newline.
                   1050:     } elsif ($command eq "delete") {
                   1051: 	$editor->DeleteLine($p1);         # p1 - key p2 null.
                   1052:     } else {			          # Should not get here!!!
                   1053: 	die "Invalid command given to ApplyEdit $command"
                   1054:     }
                   1055: }
                   1056: #
                   1057: # AdjustOurHost:
                   1058: #           Adjusts a host file stored in a configuration file editor object
                   1059: #           for the true IP address of this host. This is necessary for hosts
                   1060: #           that live behind a firewall.
                   1061: #           Those hosts have a publicly distributed IP of the firewall, but
                   1062: #           internally must use their actual IP.  We assume that a given
                   1063: #           host only has a single IP interface for now.
                   1064: # Formal Parameters:
                   1065: #     editor   - The configuration file editor to adjust.  This
                   1066: #                editor is assumed to contain a hosts.tab file.
                   1067: # Strategy:
                   1068: #    - Figure out our hostname.
                   1069: #    - Lookup the entry for this host.
                   1070: #    - Modify the line to contain our IP
                   1071: #    - Do a replace for this host.
                   1072: sub AdjustOurHost {
                   1073:     my $editor        = shift;
                   1074: 
                   1075:     # figure out who I am.
                   1076: 
                   1077:     my $myHostName    = $perlvar{'lonHostID'}; # LonCAPA hostname.
                   1078: 
                   1079:     #  Get my host file entry.
                   1080: 
                   1081:     my $ConfigLine    = $editor->Find($myHostName);
                   1082:     if(! (defined $ConfigLine)) {
                   1083: 	die "AdjustOurHost - no entry for me in hosts file $myHostName";
                   1084:     }
                   1085:     # figure out my IP:
                   1086:     #   Use the config line to get my hostname.
                   1087:     #   Use gethostbyname to translate that into an IP address.
                   1088:     #
1.338     albertel 1089:     my ($id,$domain,$role,$name,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
1.169     foxr     1090:     #
                   1091:     #  Reassemble the config line from the elements in the list.
                   1092:     #  Note that if the loncnew items were not present before, they will
                   1093:     #  be now even if they would be empty
                   1094:     #
                   1095:     my $newConfigLine = $id;
1.338     albertel 1096:     foreach my $item ($domain, $role, $name, $maxcon, $idleto, $mincon) {
1.169     foxr     1097: 	$newConfigLine .= ":".$item;
                   1098:     }
                   1099:     #  Replace the line:
                   1100: 
                   1101:     $editor->ReplaceLine($id, $newConfigLine);
                   1102:     
                   1103: }
                   1104: #
                   1105: #   ReplaceConfigFile:
                   1106: #              Replaces a configuration file with the contents of a
                   1107: #              configuration file editor object.
                   1108: #              This is done by:
                   1109: #              - Copying the target file to <filename>.old
                   1110: #              - Writing the new file to <filename>.tmp
                   1111: #              - Moving <filename.tmp>  -> <filename>
                   1112: #              This laborious process ensures that the system is never without
                   1113: #              a configuration file that's at least valid (even if the contents
                   1114: #              may be dated).
                   1115: #   Parameters:
                   1116: #        filename   - Name of the file to modify... this is a full path.
                   1117: #        editor     - Editor containing the file.
                   1118: #
                   1119: sub ReplaceConfigFile {
1.192     foxr     1120:     
                   1121:     my ($filename, $editor) = @_;
1.168     foxr     1122: 
1.169     foxr     1123:     CopyFile ($filename, $filename.".old");
                   1124: 
                   1125:     my $contents  = $editor->Get(); # Get the contents of the file.
                   1126: 
                   1127:     InstallFile($filename, $contents);
                   1128: }
1.168     foxr     1129: #   
                   1130: #
                   1131: #   Called to edit a configuration table  file
1.167     foxr     1132: #   Parameters:
                   1133: #      request           - The entire command/request sent by lonc or lonManage
                   1134: #   Return:
                   1135: #      The reply to send to the client.
1.168     foxr     1136: #
1.167     foxr     1137: sub EditFile {
                   1138:     my $request = shift;
                   1139: 
                   1140:     #  Split the command into it's pieces:  edit:filetype:script
                   1141: 
1.339     albertel 1142:     my ($cmd, $filetype, $script) = split(/:/, $request,3);	# : in script
1.167     foxr     1143: 
                   1144:     #  Check the pre-coditions for success:
                   1145: 
1.339     albertel 1146:     if($cmd != "edit") {	# Something is amiss afoot alack.
1.167     foxr     1147: 	return "error:edit request detected, but request != 'edit'\n";
                   1148:     }
                   1149:     if( ($filetype ne "hosts")  &&
                   1150: 	($filetype ne "domain")) {
                   1151: 	return "error:edit requested with invalid file specifier: $filetype \n";
                   1152:     }
                   1153: 
                   1154:     #   Split the edit script and check it's validity.
1.168     foxr     1155: 
                   1156:     my @scriptlines = split(/\n/, $script);  # one line per element.
                   1157:     my $linecount   = scalar(@scriptlines);
                   1158:     for(my $i = 0; $i < $linecount; $i++) {
                   1159: 	chomp($scriptlines[$i]);
                   1160: 	if(!isValidEditCommand($scriptlines[$i])) {
                   1161: 	    return "error:edit with bad script line: '$scriptlines[$i]' \n";
                   1162: 	}
                   1163:     }
1.145     foxr     1164: 
1.167     foxr     1165:     #   Execute the edit operation.
1.169     foxr     1166:     #   - Create a config file editor for the appropriate file and 
                   1167:     #   - execute each command in the script:
                   1168:     #
                   1169:     my $configfile = ConfigFileFromSelector($filetype);
                   1170:     if (!(defined $configfile)) {
                   1171: 	return "refused\n";
                   1172:     }
                   1173:     my $editor = ConfigFileEdit->new($configfile);
1.167     foxr     1174: 
1.169     foxr     1175:     for (my $i = 0; $i < $linecount; $i++) {
                   1176: 	ApplyEdit($scriptlines[$i], $editor);
                   1177:     }
                   1178:     # If the file is the host file, ensure that our host is
                   1179:     # adjusted to have our ip:
                   1180:     #
                   1181:     if($filetype eq "host") {
                   1182: 	AdjustOurHost($editor);
                   1183:     }
                   1184:     #  Finally replace the current file with our file.
                   1185:     #
                   1186:     ReplaceConfigFile($configfile, $editor);
1.167     foxr     1187: 
                   1188:     return "ok\n";
                   1189: }
1.207     foxr     1190: 
1.255     foxr     1191: #   read_profile
                   1192: #
                   1193: #   Returns a set of specific entries from a user's profile file.
                   1194: #   this is a utility function that is used by both get_profile_entry and
                   1195: #   get_profile_entry_encrypted.
                   1196: #
                   1197: # Parameters:
                   1198: #    udom       - Domain in which the user exists.
                   1199: #    uname      - User's account name (loncapa account)
                   1200: #    namespace  - The profile namespace to open.
                   1201: #    what       - A set of & separated queries.
                   1202: # Returns:
                   1203: #    If all ok: - The string that needs to be shipped back to the user.
                   1204: #    If failure - A string that starts with error: followed by the failure
                   1205: #                 reason.. note that this probabyl gets shipped back to the
                   1206: #                 user as well.
                   1207: #
                   1208: sub read_profile {
                   1209:     my ($udom, $uname, $namespace, $what) = @_;
                   1210:     
                   1211:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   1212: 				 &GDBM_READER());
                   1213:     if ($hashref) {
                   1214:         my @queries=split(/\&/,$what);
1.440     raeburn  1215:         if ($namespace eq 'roles') {
                   1216:             @queries = map { &unescape($_); } @queries; 
                   1217:         }
1.255     foxr     1218:         my $qresult='';
                   1219: 	
                   1220: 	for (my $i=0;$i<=$#queries;$i++) {
                   1221: 	    $qresult.="$hashref->{$queries[$i]}&";    # Presumably failure gives empty string.
                   1222: 	}
                   1223: 	$qresult=~s/\&$//;              # Remove trailing & from last lookup.
1.311     albertel 1224: 	if (&untie_user_hash($hashref)) {
1.255     foxr     1225: 	    return $qresult;
                   1226: 	} else {
                   1227: 	    return "error: ".($!+0)." untie (GDBM) Failed";
                   1228: 	}
                   1229:     } else {
                   1230: 	if ($!+0 == 2) {
                   1231: 	    return "error:No such file or GDBM reported bad block error";
                   1232: 	} else {
                   1233: 	    return "error: ".($!+0)." tie (GDBM) Failed";
                   1234: 	}
                   1235:     }
                   1236: 
                   1237: }
1.214     foxr     1238: #--------------------- Request Handlers --------------------------------------------
                   1239: #
1.215     foxr     1240: #   By convention each request handler registers itself prior to the sub 
                   1241: #   declaration:
1.214     foxr     1242: #
                   1243: 
1.216     foxr     1244: #++
                   1245: #
1.214     foxr     1246: #  Handles ping requests.
                   1247: #  Parameters:
                   1248: #      $cmd    - the actual keyword that invoked us.
                   1249: #      $tail   - the tail of the request that invoked us.
                   1250: #      $replyfd- File descriptor connected to the client
                   1251: #  Implicit Inputs:
                   1252: #      $currenthostid - Global variable that carries the name of the host we are
                   1253: #                       known as.
                   1254: #  Returns:
                   1255: #      1       - Ok to continue processing.
                   1256: #      0       - Program should exit.
                   1257: #  Side effects:
                   1258: #      Reply information is sent to the client.
                   1259: sub ping_handler {
                   1260:     my ($cmd, $tail, $client) = @_;
                   1261:     Debug("$cmd $tail $client .. $currenthostid:");
                   1262:    
1.387     albertel 1263:     Reply( $client,\$currenthostid,"$cmd:$tail");
1.214     foxr     1264:    
                   1265:     return 1;
                   1266: }
                   1267: &register_handler("ping", \&ping_handler, 0, 1, 1);       # Ping unencoded, client or manager.
                   1268: 
1.216     foxr     1269: #++
1.215     foxr     1270: #
                   1271: # Handles pong requests.  Pong replies with our current host id, and
                   1272: #                         the results of a ping sent to us via our lonc.
                   1273: #
                   1274: # Parameters:
                   1275: #      $cmd    - the actual keyword that invoked us.
                   1276: #      $tail   - the tail of the request that invoked us.
                   1277: #      $replyfd- File descriptor connected to the client
                   1278: #  Implicit Inputs:
                   1279: #      $currenthostid - Global variable that carries the name of the host we are
                   1280: #                       connected to.
                   1281: #  Returns:
                   1282: #      1       - Ok to continue processing.
                   1283: #      0       - Program should exit.
                   1284: #  Side effects:
                   1285: #      Reply information is sent to the client.
                   1286: sub pong_handler {
                   1287:     my ($cmd, $tail, $replyfd) = @_;
                   1288: 
1.365     albertel 1289:     my $reply=&Apache::lonnet::reply("ping",$clientname);
1.215     foxr     1290:     &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail"); 
                   1291:     return 1;
                   1292: }
                   1293: &register_handler("pong", \&pong_handler, 0, 1, 1);       # Pong unencoded, client or manager
                   1294: 
1.216     foxr     1295: #++
                   1296: #      Called to establish an encrypted session key with the remote client.
                   1297: #      Note that with secure lond, in most cases this function is never
                   1298: #      invoked.  Instead, the secure session key is established either
                   1299: #      via a local file that's locked down tight and only lives for a short
                   1300: #      time, or via an ssl tunnel...and is generated from a bunch-o-random
                   1301: #      bits from /dev/urandom, rather than the predictable pattern used by
                   1302: #      by this sub.  This sub is only used in the old-style insecure
                   1303: #      key negotiation.
                   1304: # Parameters:
                   1305: #      $cmd    - the actual keyword that invoked us.
                   1306: #      $tail   - the tail of the request that invoked us.
                   1307: #      $replyfd- File descriptor connected to the client
                   1308: #  Implicit Inputs:
                   1309: #      $currenthostid - Global variable that carries the name of the host
                   1310: #                       known as.
1.448     raeburn  1311: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.216     foxr     1312: #  Returns:
                   1313: #      1       - Ok to continue processing.
                   1314: #      0       - Program should exit.
                   1315: #  Implicit Outputs:
                   1316: #      Reply information is sent to the client.
                   1317: #      $cipher is set with a reference to a new IDEA encryption object.
                   1318: #
                   1319: sub establish_key_handler {
                   1320:     my ($cmd, $tail, $replyfd) = @_;
                   1321: 
                   1322:     my $buildkey=time.$$.int(rand 100000);
                   1323:     $buildkey=~tr/1-6/A-F/;
                   1324:     $buildkey=int(rand 100000).$buildkey.int(rand 100000);
                   1325:     my $key=$currenthostid.$clientname;
                   1326:     $key=~tr/a-z/A-Z/;
                   1327:     $key=~tr/G-P/0-9/;
                   1328:     $key=~tr/Q-Z/0-9/;
                   1329:     $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
                   1330:     $key=substr($key,0,32);
                   1331:     my $cipherkey=pack("H32",$key);
                   1332:     $cipher=new IDEA $cipherkey;
1.387     albertel 1333:     &Reply($replyfd, \$buildkey, "$cmd:$tail"); 
1.216     foxr     1334:    
                   1335:     return 1;
                   1336: 
                   1337: }
                   1338: &register_handler("ekey", \&establish_key_handler, 0, 1,1);
                   1339: 
1.217     foxr     1340: #     Handler for the load command.  Returns the current system load average
                   1341: #     to the requestor.
                   1342: #
                   1343: # Parameters:
                   1344: #      $cmd    - the actual keyword that invoked us.
                   1345: #      $tail   - the tail of the request that invoked us.
                   1346: #      $replyfd- File descriptor connected to the client
                   1347: #  Implicit Inputs:
                   1348: #      $currenthostid - Global variable that carries the name of the host
                   1349: #                       known as.
1.448     raeburn  1350: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1351: #  Returns:
                   1352: #      1       - Ok to continue processing.
                   1353: #      0       - Program should exit.
                   1354: #  Side effects:
                   1355: #      Reply information is sent to the client.
                   1356: sub load_handler {
                   1357:     my ($cmd, $tail, $replyfd) = @_;
                   1358: 
1.463     foxr     1359: 
                   1360: 
1.217     foxr     1361:    # Get the load average from /proc/loadavg and calculate it as a percentage of
                   1362:    # the allowed load limit as set by the perl global variable lonLoadLim
                   1363: 
                   1364:     my $loadavg;
                   1365:     my $loadfile=IO::File->new('/proc/loadavg');
                   1366:    
                   1367:     $loadavg=<$loadfile>;
                   1368:     $loadavg =~ s/\s.*//g;                      # Extract the first field only.
                   1369:    
                   1370:     my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
                   1371: 
1.387     albertel 1372:     &Reply( $replyfd, \$loadpercent, "$cmd:$tail");
1.217     foxr     1373:    
                   1374:     return 1;
                   1375: }
1.263     albertel 1376: &register_handler("load", \&load_handler, 0, 1, 0);
1.217     foxr     1377: 
                   1378: #
                   1379: #   Process the userload request.  This sub returns to the client the current
                   1380: #  user load average.  It can be invoked either by clients or managers.
                   1381: #
                   1382: # Parameters:
                   1383: #      $cmd    - the actual keyword that invoked us.
                   1384: #      $tail   - the tail of the request that invoked us.
                   1385: #      $replyfd- File descriptor connected to the client
                   1386: #  Implicit Inputs:
                   1387: #      $currenthostid - Global variable that carries the name of the host
                   1388: #                       known as.
1.448     raeburn  1389: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1390: #  Returns:
                   1391: #      1       - Ok to continue processing.
                   1392: #      0       - Program should exit
                   1393: # Implicit inputs:
                   1394: #     whatever the userload() function requires.
                   1395: #  Implicit outputs:
                   1396: #     the reply is written to the client.
                   1397: #
                   1398: sub user_load_handler {
                   1399:     my ($cmd, $tail, $replyfd) = @_;
                   1400: 
1.365     albertel 1401:     my $userloadpercent=&Apache::lonnet::userload();
1.387     albertel 1402:     &Reply($replyfd, \$userloadpercent, "$cmd:$tail");
1.217     foxr     1403:     
                   1404:     return 1;
                   1405: }
1.263     albertel 1406: &register_handler("userload", \&user_load_handler, 0, 1, 0);
1.217     foxr     1407: 
1.218     foxr     1408: #   Process a request for the authorization type of a user:
                   1409: #   (userauth).
                   1410: #
                   1411: # Parameters:
                   1412: #      $cmd    - the actual keyword that invoked us.
                   1413: #      $tail   - the tail of the request that invoked us.
                   1414: #      $replyfd- File descriptor connected to the client
                   1415: #  Returns:
                   1416: #      1       - Ok to continue processing.
                   1417: #      0       - Program should exit
                   1418: # Implicit outputs:
                   1419: #    The user authorization type is written to the client.
                   1420: #
                   1421: sub user_authorization_type {
                   1422:     my ($cmd, $tail, $replyfd) = @_;
                   1423:    
                   1424:     my $userinput = "$cmd:$tail";
                   1425:    
                   1426:     #  Pull the domain and username out of the command tail.
1.222     foxr     1427:     # and call get_auth_type to determine the authentication type.
1.218     foxr     1428:    
                   1429:     my ($udom,$uname)=split(/:/,$tail);
1.222     foxr     1430:     my $result = &get_auth_type($udom, $uname);
1.218     foxr     1431:     if($result eq "nouser") {
                   1432: 	&Failure( $replyfd, "unknown_user\n", $userinput);
                   1433:     } else {
                   1434: 	#
1.222     foxr     1435: 	# We only want to pass the second field from get_auth_type
1.218     foxr     1436: 	# for ^krb.. otherwise we'll be handing out the encrypted
                   1437: 	# password for internals e.g.
                   1438: 	#
                   1439: 	my ($type,$otherinfo) = split(/:/,$result);
                   1440: 	if($type =~ /^krb/) {
                   1441: 	    $type = $result;
1.269     raeburn  1442: 	} else {
                   1443:             $type .= ':';
                   1444:         }
1.387     albertel 1445: 	&Reply( $replyfd, \$type, $userinput);
1.218     foxr     1446:     }
                   1447:   
                   1448:     return 1;
                   1449: }
                   1450: &register_handler("currentauth", \&user_authorization_type, 1, 1, 0);
                   1451: 
                   1452: #   Process a request by a manager to push a hosts or domain table 
                   1453: #   to us.  We pick apart the command and pass it on to the subs
                   1454: #   that already exist to do this.
                   1455: #
                   1456: # Parameters:
                   1457: #      $cmd    - the actual keyword that invoked us.
                   1458: #      $tail   - the tail of the request that invoked us.
                   1459: #      $client - File descriptor connected to the client
                   1460: #  Returns:
                   1461: #      1       - Ok to continue processing.
                   1462: #      0       - Program should exit
                   1463: # Implicit Output:
                   1464: #    a reply is written to the client.
                   1465: sub push_file_handler {
                   1466:     my ($cmd, $tail, $client) = @_;
1.412     foxr     1467:     &Debug("In push file handler");
1.218     foxr     1468:     my $userinput = "$cmd:$tail";
                   1469: 
                   1470:     # At this time we only know that the IP of our partner is a valid manager
                   1471:     # the code below is a hook to do further authentication (e.g. to resolve
                   1472:     # spoofing).
                   1473: 
                   1474:     my $cert = &GetCertificate($userinput);
1.412     foxr     1475:     if(&ValidManager($cert)) {
                   1476: 	&Debug("Valid manager: $client");
1.218     foxr     1477: 
                   1478: 	# Now presumably we have the bona fides of both the peer host and the
                   1479: 	# process making the request.
                   1480:       
                   1481: 	my $reply = &PushFile($userinput);
1.387     albertel 1482: 	&Reply($client, \$reply, $userinput);
1.218     foxr     1483: 
                   1484:     } else {
1.412     foxr     1485: 	&logthis("push_file_handler $client is not valid");
1.218     foxr     1486: 	&Failure( $client, "refused\n", $userinput);
                   1487:     } 
1.219     foxr     1488:     return 1;
1.218     foxr     1489: }
                   1490: &register_handler("pushfile", \&push_file_handler, 1, 0, 1);
                   1491: 
1.399     raeburn  1492: # The du_handler routine should be considered obsolete and is retained
                   1493: # for communication with legacy servers.  Please see the du2_handler.
1.243     banghart 1494: #
1.399     raeburn  1495: #   du  - list the disk usage of a directory recursively. 
1.243     banghart 1496: #    
                   1497: #   note: stolen code from the ls file handler
                   1498: #   under construction by Rick Banghart 
                   1499: #    .
                   1500: # Parameters:
                   1501: #    $cmd        - The command that dispatched us (du).
                   1502: #    $ududir     - The directory path to list... I'm not sure what this
                   1503: #                  is relative as things like ls:. return e.g.
                   1504: #                  no_such_dir.
                   1505: #    $client     - Socket open on the client.
                   1506: # Returns:
                   1507: #     1 - indicating that the daemon should not disconnect.
                   1508: # Side Effects:
                   1509: #   The reply is written to  $client.
                   1510: #
                   1511: sub du_handler {
                   1512:     my ($cmd, $ududir, $client) = @_;
1.339     albertel 1513:     ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
1.251     foxr     1514:     my $userinput = "$cmd:$ududir";
                   1515: 
1.245     albertel 1516:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
                   1517: 	&Failure($client,"refused\n","$cmd:$ududir");
                   1518: 	return 1;
                   1519:     }
1.249     foxr     1520:     #  Since $ududir could have some nasties in it,
                   1521:     #  we will require that ududir is a valid
                   1522:     #  directory.  Just in case someone tries to
                   1523:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1524:     #  etc.
                   1525:     #
                   1526:     if (-d $ududir) {
1.292     albertel 1527: 	my $total_size=0;
                   1528: 	my $code=sub { 
                   1529: 	    if ($_=~/\.\d+\./) { return;} 
                   1530: 	    if ($_=~/\.meta$/) { return;}
1.362     albertel 1531: 	    if (-d $_)         { return;}
1.292     albertel 1532: 	    $total_size+=(stat($_))[7];
                   1533: 	};
1.295     raeburn  1534: 	chdir($ududir);
1.292     albertel 1535: 	find($code,$ududir);
                   1536: 	$total_size=int($total_size/1024);
1.387     albertel 1537: 	&Reply($client,\$total_size,"$cmd:$ududir");
1.249     foxr     1538:     } else {
1.251     foxr     1539: 	&Failure($client, "bad_directory:$ududir\n","$cmd:$ududir"); 
1.249     foxr     1540:     }
1.243     banghart 1541:     return 1;
                   1542: }
                   1543: &register_handler("du", \&du_handler, 0, 1, 0);
1.218     foxr     1544: 
1.399     raeburn  1545: # Please also see the du_handler, which is obsoleted by du2. 
                   1546: # du2_handler differs from du_handler in that required path to directory
                   1547: # provided by &propath() is prepended in the handler instead of on the 
                   1548: # client side.
1.239     foxr     1549: #
1.399     raeburn  1550: #   du2  - list the disk usage of a directory recursively.
                   1551: #
                   1552: # Parameters:
                   1553: #    $cmd        - The command that dispatched us (du).
                   1554: #    $tail       - The tail of the request that invoked us.
                   1555: #                  $tail is a : separated list of the following:
                   1556: #                   - $ududir - directory path to list (before prepending)
                   1557: #                   - $getpropath = 1 if &propath() should prepend
                   1558: #                   - $uname - username to use for &propath or user dir
                   1559: #                   - $udom - domain to use for &propath or user dir
                   1560: #                   All are escaped.
                   1561: #    $client     - Socket open on the client.
                   1562: # Returns:
                   1563: #     1 - indicating that the daemon should not disconnect.
                   1564: # Side Effects:
                   1565: #   The reply is written to $client.
                   1566: #
                   1567: 
                   1568: sub du2_handler {
                   1569:     my ($cmd, $tail, $client) = @_;
                   1570:     my ($ududir,$getpropath,$uname,$udom) = map { &unescape($_) } (split(/:/, $tail));
                   1571:     my $userinput = "$cmd:$tail";
                   1572:     if (($ududir=~/\.\./) || (($ududir!~m|^/home/httpd/|) && (!$getpropath))) {
                   1573:         &Failure($client,"refused\n","$cmd:$tail");
                   1574:         return 1;
                   1575:     }
                   1576:     if ($getpropath) {
                   1577:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1578:             $ududir = &propath($udom,$uname).'/'.$ududir;
                   1579:         } else {
                   1580:             &Failure($client,"refused\n","$cmd:$tail");
                   1581:             return 1;
                   1582:         }
                   1583:     }
                   1584:     #  Since $ududir could have some nasties in it,
                   1585:     #  we will require that ududir is a valid
                   1586:     #  directory.  Just in case someone tries to
                   1587:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1588:     #  etc.
                   1589:     #
                   1590:     if (-d $ududir) {
                   1591:         my $total_size=0;
                   1592:         my $code=sub {
                   1593:             if ($_=~/\.\d+\./) { return;}
                   1594:             if ($_=~/\.meta$/) { return;}
                   1595:             if (-d $_)         { return;}
                   1596:             $total_size+=(stat($_))[7];
                   1597:         };
                   1598:         chdir($ududir);
                   1599:         find($code,$ududir);
                   1600:         $total_size=int($total_size/1024);
                   1601:         &Reply($client,\$total_size,"$cmd:$ududir");
                   1602:     } else {
                   1603:         &Failure($client, "bad_directory:$ududir\n","$cmd:$tail");
                   1604:     }
                   1605:     return 1;
                   1606: }
                   1607: &register_handler("du2", \&du2_handler, 0, 1, 0);
                   1608: 
                   1609: #
                   1610: # The ls_handler routine should be considered obsolete and is retained
                   1611: # for communication with legacy servers.  Please see the ls3_handler.
1.280     matthew  1612: #
1.239     foxr     1613: #   ls  - list the contents of a directory.  For each file in the
                   1614: #    selected directory the filename followed by the full output of
                   1615: #    the stat function is returned.  The returned info for each
                   1616: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1617: #
                   1618: #    If the requested path contains /../ or is:
                   1619: #
                   1620: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1621: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1622: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1623: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
                   1624: #    or is:
                   1625: #
1.538     raeburn  1626: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1627: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1628: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1629: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529     raeburn  1630: #
                   1631: #    the response will be "refused".
                   1632: #
1.239     foxr     1633: # Parameters:
                   1634: #    $cmd        - The command that dispatched us (ls).
                   1635: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1636: #                  is relative as things like ls:. return e.g.
                   1637: #                  no_such_dir.
                   1638: #    $client     - Socket open on the client.
                   1639: # Returns:
                   1640: #     1 - indicating that the daemon should not disconnect.
                   1641: # Side Effects:
                   1642: #   The reply is written to  $client.
                   1643: #
                   1644: sub ls_handler {
1.280     matthew  1645:     # obsoleted by ls2_handler
1.239     foxr     1646:     my ($cmd, $ulsdir, $client) = @_;
                   1647: 
                   1648:     my $userinput = "$cmd:$ulsdir";
                   1649: 
                   1650:     my $obs;
                   1651:     my $rights;
                   1652:     my $ulsout='';
                   1653:     my $ulsfn;
1.529     raeburn  1654:     if ($ulsdir =~m{/\.\./}) {
                   1655:         &Failure($client,"refused\n",$userinput);
                   1656:         return 1;
                   1657:     }
1.239     foxr     1658:     if (-e $ulsdir) {
                   1659: 	if(-d $ulsdir) {
1.539     raeburn  1660:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1661:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529     raeburn  1662:                 &Failure($client,"refused\n",$userinput);
                   1663:                 return 1;
                   1664:             }
1.239     foxr     1665: 	    if (opendir(LSDIR,$ulsdir)) {
                   1666: 		while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1667: 		    undef($obs);
                   1668: 		    undef($rights); 
1.239     foxr     1669: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1670: 		    #We do some obsolete checking here
                   1671: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1672: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1673: 			my @obsolete=<FILE>;
                   1674: 			foreach my $obsolete (@obsolete) {
1.301     www      1675: 			    if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.239     foxr     1676: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
                   1677: 			}
                   1678: 		    }
                   1679: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
                   1680: 		    if($obs eq '1') { $ulsout.="&1"; }
                   1681: 		    else { $ulsout.="&0"; }
                   1682: 		    if($rights eq '1') { $ulsout.="&1:"; }
                   1683: 		    else { $ulsout.="&0:"; }
                   1684: 		}
                   1685: 		closedir(LSDIR);
                   1686: 	    }
                   1687: 	} else {
1.539     raeburn  1688:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1689:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529     raeburn  1690:                 &Failure($client,"refused\n",$userinput);
                   1691:                 return 1;
                   1692:             }
1.239     foxr     1693: 	    my @ulsstats=stat($ulsdir);
                   1694: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1695: 	}
                   1696:     } else {
                   1697: 	$ulsout='no_such_dir';
                   1698:     }
                   1699:     if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1700:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.239     foxr     1701:     
                   1702:     return 1;
                   1703: 
                   1704: }
                   1705: &register_handler("ls", \&ls_handler, 0, 1, 0);
                   1706: 
1.399     raeburn  1707: # The ls2_handler routine should be considered obsolete and is retained
                   1708: # for communication with legacy servers.  Please see the ls3_handler.
                   1709: # Please also see the ls_handler, which was itself obsoleted by ls2.
1.280     matthew  1710: # ls2_handler differs from ls_handler in that it escapes its return 
                   1711: # values before concatenating them together with ':'s.
                   1712: #
                   1713: #   ls2  - list the contents of a directory.  For each file in the
                   1714: #    selected directory the filename followed by the full output of
                   1715: #    the stat function is returned.  The returned info for each
                   1716: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1717: #
                   1718: #    If the requested path contains /../ or is:
                   1719: #
                   1720: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1721: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1722: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1723: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
                   1724: #    or is:
                   1725: #
1.538     raeburn  1726: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1727: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1728: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1729: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529     raeburn  1730: #
                   1731: #    the response will be "refused".
                   1732: #
1.280     matthew  1733: # Parameters:
                   1734: #    $cmd        - The command that dispatched us (ls).
                   1735: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1736: #                  is relative as things like ls:. return e.g.
                   1737: #                  no_such_dir.
                   1738: #    $client     - Socket open on the client.
                   1739: # Returns:
                   1740: #     1 - indicating that the daemon should not disconnect.
                   1741: # Side Effects:
                   1742: #   The reply is written to  $client.
                   1743: #
                   1744: sub ls2_handler {
                   1745:     my ($cmd, $ulsdir, $client) = @_;
                   1746: 
                   1747:     my $userinput = "$cmd:$ulsdir";
                   1748: 
                   1749:     my $obs;
                   1750:     my $rights;
                   1751:     my $ulsout='';
                   1752:     my $ulsfn;
1.529     raeburn  1753:     if ($ulsdir =~m{/\.\./}) {
                   1754:         &Failure($client,"refused\n",$userinput);
                   1755:         return 1;
                   1756:     }
1.280     matthew  1757:     if (-e $ulsdir) {
                   1758:         if(-d $ulsdir) {
1.539     raeburn  1759:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1760:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529     raeburn  1761:                 &Failure($client,"refused\n","$userinput");
                   1762:                 return 1;
                   1763:             }
1.280     matthew  1764:             if (opendir(LSDIR,$ulsdir)) {
                   1765:                 while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1766:                     undef($obs);
                   1767: 		    undef($rights); 
1.280     matthew  1768:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1769:                     #We do some obsolete checking here
                   1770:                     if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1771:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1772:                         my @obsolete=<FILE>;
                   1773:                         foreach my $obsolete (@obsolete) {
1.301     www      1774:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.280     matthew  1775:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1776:                                 $rights = 1;
                   1777:                             }
                   1778:                         }
                   1779:                     }
                   1780:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1781:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1782:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1783:                     $ulsout.= &escape($tmp).':';
                   1784:                 }
                   1785:                 closedir(LSDIR);
                   1786:             }
                   1787:         } else {
1.539     raeburn  1788:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1789:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529     raeburn  1790:                 &Failure($client,"refused\n",$userinput);
                   1791:                 return 1;
                   1792:             }
1.280     matthew  1793:             my @ulsstats=stat($ulsdir);
                   1794:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1795:         }
                   1796:     } else {
                   1797:         $ulsout='no_such_dir';
                   1798:    }
                   1799:    if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1800:    &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.280     matthew  1801:    return 1;
                   1802: }
                   1803: &register_handler("ls2", \&ls2_handler, 0, 1, 0);
1.399     raeburn  1804: #
                   1805: #   ls3  - list the contents of a directory.  For each file in the
                   1806: #    selected directory the filename followed by the full output of
                   1807: #    the stat function is returned.  The returned info for each
                   1808: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1809: #
                   1810: #    If the requested path (after prepending) contains /../ or is:
                   1811: #
                   1812: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1813: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1814: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1815: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
1.539     raeburn  1816: #        (d) /home/httpd/html/priv/<domain> and client is the homeserver
1.529     raeburn  1817: #
1.530     raeburn  1818: #    or is:
1.529     raeburn  1819: #
1.538     raeburn  1820: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1821: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1822: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1823: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
                   1824: #        (d) /home/httpd/html/priv/<domain>/<username>/ and client is the homeserver
1.529     raeburn  1825: #
                   1826: #    the response will be "refused".
                   1827: #
1.399     raeburn  1828: # Parameters:
                   1829: #    $cmd        - The command that dispatched us (ls).
                   1830: #    $tail       - The tail of the request that invoked us.
                   1831: #                  $tail is a : separated list of the following:
                   1832: #                   - $ulsdir - directory path to list (before prepending)
                   1833: #                   - $getpropath = 1 if &propath() should prepend
                   1834: #                   - $getuserdir = 1 if path to user dir in lonUsers should
                   1835: #                                     prepend
                   1836: #                   - $alternate_root - path to prepend
                   1837: #                   - $uname - username to use for &propath or user dir
                   1838: #                   - $udom - domain to use for &propath or user dir
                   1839: #            All of these except $getpropath and &getuserdir are escaped.    
                   1840: #                  no_such_dir.
                   1841: #    $client     - Socket open on the client.
                   1842: # Returns:
                   1843: #     1 - indicating that the daemon should not disconnect.
                   1844: # Side Effects:
                   1845: #   The reply is written to $client.
                   1846: #
                   1847: 
                   1848: sub ls3_handler {
                   1849:     my ($cmd, $tail, $client) = @_;
                   1850:     my $userinput = "$cmd:$tail";
                   1851:     my ($ulsdir,$getpropath,$getuserdir,$alternate_root,$uname,$udom) =
                   1852:         split(/:/,$tail);
                   1853:     if (defined($ulsdir)) {
                   1854:         $ulsdir = &unescape($ulsdir);
                   1855:     }
                   1856:     if (defined($alternate_root)) {
                   1857:         $alternate_root = &unescape($alternate_root);
                   1858:     }
                   1859:     if (defined($uname)) {
                   1860:         $uname = &unescape($uname);
                   1861:     }
                   1862:     if (defined($udom)) {
                   1863:         $udom = &unescape($udom);
                   1864:     }
                   1865: 
                   1866:     my $dir_root = $perlvar{'lonDocRoot'};
1.529     raeburn  1867:     if (($getpropath) || ($getuserdir)) {
1.399     raeburn  1868:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1869:             $dir_root = &propath($udom,$uname);
                   1870:             $dir_root =~ s/\/$//;
                   1871:         } else {
1.529     raeburn  1872:             &Failure($client,"refused\n",$userinput);
1.399     raeburn  1873:             return 1;
                   1874:         }
1.400     raeburn  1875:     } elsif ($alternate_root ne '') {
1.399     raeburn  1876:         $dir_root = $alternate_root;
                   1877:     }
1.408     raeburn  1878:     if (($dir_root ne '') && ($dir_root ne '/')) {
1.400     raeburn  1879:         if ($ulsdir =~ /^\//) {
                   1880:             $ulsdir = $dir_root.$ulsdir;
                   1881:         } else {
                   1882:             $ulsdir = $dir_root.'/'.$ulsdir;
                   1883:         }
1.399     raeburn  1884:     }
1.529     raeburn  1885:     if ($ulsdir =~m{/\.\./}) {
                   1886:         &Failure($client,"refused\n",$userinput);
                   1887:         return 1;
                   1888:     }
                   1889:     my $islocal;
                   1890:     my @machine_ids = &Apache::lonnet::current_machine_ids();
                   1891:     if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   1892:         $islocal = 1;
                   1893:     }
1.399     raeburn  1894:     my $obs;
                   1895:     my $rights;
                   1896:     my $ulsout='';
                   1897:     my $ulsfn;
1.547   ! raeburn  1898: 
        !          1899:     my ($crscheck,$toplevel,$currdom,$currnum,$skip);
        !          1900:     unless ($islocal) {
        !          1901:         my ($major,$minor) = split(/\./,$clientversion);
        !          1902:         if (($major < 2) || ($major == 2 && $minor < 12)) {
        !          1903:             $crscheck = 1;
        !          1904:         }
        !          1905:     }
1.399     raeburn  1906:     if (-e $ulsdir) {
                   1907:         if(-d $ulsdir) {
1.529     raeburn  1908:             unless (($getpropath) || ($getuserdir) ||
1.539     raeburn  1909:                     ($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1910:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles}) ||
                   1911:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain}) && ($islocal))) {
1.529     raeburn  1912:                 &Failure($client,"refused\n",$userinput);
                   1913:                 return 1;
                   1914:             }
1.547   ! raeburn  1915:             if (($crscheck) &&
        !          1916:                 ($ulsdir =~ m{^/home/httpd/html/res/($LONCAPA::match_domain)(/?$|/$LONCAPA::match_courseid)})) {
        !          1917:                 ($currdom,my $posscnum) = ($1,$2);
        !          1918:                 if (($posscnum eq '') || ($posscnum eq '/')) {
        !          1919:                     $toplevel = 1;
        !          1920:                 } else {
        !          1921:                     $posscnum =~ s{^/+}{};
        !          1922:                     if (&LONCAPA::Lond::is_course($currdom,$posscnum)) {
        !          1923:                         $skip = 1;
        !          1924:                     }
        !          1925:                 }
        !          1926:             }
        !          1927:             if ((!$skip) && (opendir(LSDIR,$ulsdir))) {
1.399     raeburn  1928:                 while ($ulsfn=readdir(LSDIR)) {
1.547   ! raeburn  1929:                     if (($crscheck) && ($toplevel) && ($currdom ne '') &&
        !          1930:                         ($ulsfn =~ /^$LONCAPA::match_courseid$/) && (-d "$ulsdir/$ulsfn")) {
        !          1931:                         if (&LONCAPA::Lond::is_course($currdom,$ulsfn)) {
        !          1932:                             next;
        !          1933:                         }
        !          1934:                     }
1.399     raeburn  1935:                     undef($obs);
                   1936:                     undef($rights);
                   1937:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1938:                     #We do some obsolete checking here
                   1939:                     if(-e $ulsdir.'/'.$ulsfn.".meta") {
                   1940:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1941:                         my @obsolete=<FILE>;
                   1942:                         foreach my $obsolete (@obsolete) {
                   1943:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
                   1944:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1945:                                 $rights = 1;
                   1946:                             }
                   1947:                         }
                   1948:                     }
                   1949:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1950:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1951:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1952:                     $ulsout.= &escape($tmp).':';
                   1953:                 }
                   1954:                 closedir(LSDIR);
                   1955:             }
                   1956:         } else {
1.529     raeburn  1957:             unless (($getpropath) || ($getuserdir) ||
1.539     raeburn  1958:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1959:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/}) ||
                   1960:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain/$LONCAPA::match_name/}) && ($islocal))) {
1.529     raeburn  1961:                 &Failure($client,"refused\n",$userinput);
                   1962:                 return 1;
                   1963:             }
1.399     raeburn  1964:             my @ulsstats=stat($ulsdir);
                   1965:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1966:         }
                   1967:     } else {
                   1968:         $ulsout='no_such_dir';
1.400     raeburn  1969:     }
                   1970:     if ($ulsout eq '') { $ulsout='empty'; }
                   1971:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
                   1972:     return 1;
1.399     raeburn  1973: }
                   1974: &register_handler("ls3", \&ls3_handler, 0, 1, 0);
1.280     matthew  1975: 
1.477     raeburn  1976: sub read_lonnet_global {
                   1977:     my ($cmd,$tail,$client) = @_;
                   1978:     my $userinput = "$cmd:$tail";
                   1979:     my $requested = &Apache::lonnet::thaw_unescape($tail);
                   1980:     my $result;
1.480     raeburn  1981:     my %packagevars = (
                   1982:                         spareid => \%Apache::lonnet::spareid,
                   1983:                         perlvar => \%Apache::lonnet::perlvar,
                   1984:                       );
                   1985:     my %limit_to = (
                   1986:                     perlvar => {
1.531     raeburn  1987:                                  lonOtherAuthen  => 1,
                   1988:                                  lonBalancer     => 1,
                   1989:                                  lonVersion      => 1,
                   1990:                                  lonAdmEMail     => 1,
                   1991:                                  lonSupportEMail => 1,  
                   1992:                                  lonSysEMail     => 1,
                   1993:                                  lonHostID       => 1,
                   1994:                                  lonRole         => 1,
                   1995:                                  lonDefDomain    => 1,
                   1996:                                  lonLoadLim      => 1,
                   1997:                                  lonUserLoadLim  => 1,
1.480     raeburn  1998:                                }
                   1999:                   );
1.477     raeburn  2000:     if (ref($requested) eq 'HASH') {
                   2001:         foreach my $what (keys(%{$requested})) {
                   2002:             my $response;
1.480     raeburn  2003:             my $items = {};
                   2004:             if (exists($packagevars{$what})) {
                   2005:                 if (ref($limit_to{$what}) eq 'HASH') {
                   2006:                     foreach my $varname (keys(%{$packagevars{$what}})) {
                   2007:                         if ($limit_to{$what}{$varname}) {
                   2008:                             $items->{$varname} = $packagevars{$what}{$varname};
                   2009:                         }
                   2010:                     }
                   2011:                 } else {
                   2012:                     $items = $packagevars{$what};
1.477     raeburn  2013:                 }
1.480     raeburn  2014:                 if ($what eq 'perlvar') {
                   2015:                     if (!exists($packagevars{$what}{'lonBalancer'})) {
                   2016:                         if ($dist =~ /^(centos|rhes|fedora|scientific)/) {
                   2017:                             my $othervarref=LONCAPA::Configuration::read_conf('httpd.conf');
                   2018:                             if (ref($othervarref) eq 'HASH') {
                   2019:                                 $items->{'lonBalancer'} = $othervarref->{'lonBalancer'};
                   2020:                             }
                   2021:                         }
                   2022:                     }
1.477     raeburn  2023:                 }
1.480     raeburn  2024:                 $response = &Apache::lonnet::freeze_escape($items);
1.477     raeburn  2025:             }
1.478     raeburn  2026:             $result .= &escape($what).'='.$response.'&';
1.477     raeburn  2027:         }
                   2028:     }
                   2029:     $result =~ s/\&$//;
                   2030:     &Reply($client,\$result,$userinput);
                   2031:     return 1;
                   2032: }
                   2033: &register_handler("readlonnetglobal", \&read_lonnet_global, 0, 1, 0);
                   2034: 
1.479     raeburn  2035: sub server_devalidatecache_handler {
                   2036:     my ($cmd,$tail,$client) = @_;
                   2037:     my $userinput = "$cmd:$tail";
1.503     raeburn  2038:     my $items = &unescape($tail);
                   2039:     my @cached = split(/\&/,$items);
                   2040:     foreach my $key (@cached) {
                   2041:         if ($key =~ /:/) {
                   2042:             my ($name,$id) = map { &unescape($_); } split(/:/,$key);
                   2043:             &Apache::lonnet::devalidate_cache_new($name,$id);
                   2044:         }
                   2045:     }
1.479     raeburn  2046:     my $result = 'ok';
                   2047:     &Reply($client,\$result,$userinput);
                   2048:     return 1;
                   2049: }
1.481     raeburn  2050: &register_handler("devalidatecache", \&server_devalidatecache_handler, 0, 1, 0);
1.479     raeburn  2051: 
1.410     raeburn  2052: sub server_timezone_handler {
                   2053:     my ($cmd,$tail,$client) = @_;
                   2054:     my $userinput = "$cmd:$tail";
                   2055:     my $timezone;
                   2056:     my $clockfile = '/etc/sysconfig/clock'; # Fedora/CentOS/SuSE
                   2057:     my $tzfile = '/etc/timezone'; # Debian/Ubuntu
                   2058:     if (-e $clockfile) {
                   2059:         if (open(my $fh,"<$clockfile")) {
                   2060:             while (<$fh>) {
                   2061:                 next if (/^[\#\s]/);
                   2062:                 if (/^(?:TIME)?ZONE\s*=\s*['"]?\s*([\w\/]+)/) {
                   2063:                     $timezone = $1;
                   2064:                     last;
                   2065:                 }
                   2066:             }
                   2067:             close($fh);
                   2068:         }
                   2069:     } elsif (-e $tzfile) {
                   2070:         if (open(my $fh,"<$tzfile")) {
                   2071:             $timezone = <$fh>;
                   2072:             close($fh);
                   2073:             chomp($timezone);
                   2074:             if ($timezone =~ m{^Etc/(\w+)$}) {
                   2075:                 $timezone = $1;
                   2076:             }
                   2077:         }
                   2078:     }
                   2079:     &Reply($client,\$timezone,$userinput); # This supports debug logging.
                   2080:     return 1;
                   2081: }
                   2082: &register_handler("servertimezone", \&server_timezone_handler, 0, 1, 0);
                   2083: 
1.413     raeburn  2084: sub server_loncaparev_handler {
                   2085:     my ($cmd,$tail,$client) = @_;
                   2086:     my $userinput = "$cmd:$tail";
                   2087:     &Reply($client,\$perlvar{'lonVersion'},$userinput);
                   2088:     return 1;
                   2089: }
                   2090: &register_handler("serverloncaparev", \&server_loncaparev_handler, 0, 1, 0);
                   2091: 
1.448     raeburn  2092: sub server_homeID_handler {
                   2093:     my ($cmd,$tail,$client) = @_;
                   2094:     my $userinput = "$cmd:$tail";
                   2095:     &Reply($client,\$perlvar{'lonHostID'},$userinput);
                   2096:     return 1;
                   2097: }
                   2098: &register_handler("serverhomeID", \&server_homeID_handler, 0, 1, 0);
                   2099: 
1.471     raeburn  2100: sub server_distarch_handler {
                   2101:     my ($cmd,$tail,$client) = @_;
                   2102:     my $userinput = "$cmd:$tail";
                   2103:     my $reply = &distro_and_arch();
                   2104:     &Reply($client,\$reply,$userinput);
                   2105:     return 1;
                   2106: }
                   2107: &register_handler("serverdistarch", \&server_distarch_handler, 0, 1, 0);
                   2108: 
1.523     raeburn  2109: sub server_certs_handler {
                   2110:     my ($cmd,$tail,$client) = @_;
                   2111:     my $userinput = "$cmd:$tail";
                   2112:     my $result;
                   2113:     my $result = &LONCAPA::Lond::server_certs(\%perlvar);
                   2114:     &Reply($client,\$result,$userinput);
                   2115:     return;
                   2116: }
                   2117: &register_handler("servercerts", \&server_certs_handler, 0, 1, 0);
                   2118: 
1.218     foxr     2119: #   Process a reinit request.  Reinit requests that either
                   2120: #   lonc or lond be reinitialized so that an updated 
                   2121: #   host.tab or domain.tab can be processed.
                   2122: #
                   2123: # Parameters:
                   2124: #      $cmd    - the actual keyword that invoked us.
                   2125: #      $tail   - the tail of the request that invoked us.
                   2126: #      $client - File descriptor connected to the client
                   2127: #  Returns:
                   2128: #      1       - Ok to continue processing.
                   2129: #      0       - Program should exit
                   2130: #  Implicit output:
                   2131: #     a reply is sent to the client.
                   2132: #
                   2133: sub reinit_process_handler {
                   2134:     my ($cmd, $tail, $client) = @_;
                   2135:    
                   2136:     my $userinput = "$cmd:$tail";
                   2137:    
                   2138:     my $cert = &GetCertificate($userinput);
                   2139:     if(&ValidManager($cert)) {
                   2140: 	chomp($userinput);
                   2141: 	my $reply = &ReinitProcess($userinput);
1.387     albertel 2142: 	&Reply( $client,  \$reply, $userinput);
1.218     foxr     2143:     } else {
                   2144: 	&Failure( $client, "refused\n", $userinput);
                   2145:     }
                   2146:     return 1;
                   2147: }
                   2148: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
                   2149: 
                   2150: #  Process the editing script for a table edit operation.
                   2151: #  the editing operation must be encrypted and requested by
                   2152: #  a manager host.
                   2153: #
                   2154: # Parameters:
                   2155: #      $cmd    - the actual keyword that invoked us.
                   2156: #      $tail   - the tail of the request that invoked us.
                   2157: #      $client - File descriptor connected to the client
                   2158: #  Returns:
                   2159: #      1       - Ok to continue processing.
                   2160: #      0       - Program should exit
                   2161: #  Implicit output:
                   2162: #     a reply is sent to the client.
                   2163: #
                   2164: sub edit_table_handler {
                   2165:     my ($command, $tail, $client) = @_;
                   2166:    
                   2167:     my $userinput = "$command:$tail";
                   2168: 
                   2169:     my $cert = &GetCertificate($userinput);
                   2170:     if(&ValidManager($cert)) {
                   2171: 	my($filetype, $script) = split(/:/, $tail);
                   2172: 	if (($filetype eq "hosts") || 
                   2173: 	    ($filetype eq "domain")) {
                   2174: 	    if($script ne "") {
                   2175: 		&Reply($client,              # BUGBUG - EditFile
                   2176: 		      &EditFile($userinput), #   could fail.
                   2177: 		      $userinput);
                   2178: 	    } else {
                   2179: 		&Failure($client,"refused\n",$userinput);
                   2180: 	    }
                   2181: 	} else {
                   2182: 	    &Failure($client,"refused\n",$userinput);
                   2183: 	}
                   2184:     } else {
                   2185: 	&Failure($client,"refused\n",$userinput);
                   2186:     }
                   2187:     return 1;
                   2188: }
1.263     albertel 2189: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
1.218     foxr     2190: 
1.220     foxr     2191: #
                   2192: #   Authenticate a user against the LonCAPA authentication
                   2193: #   database.  Note that there are several authentication
                   2194: #   possibilities:
                   2195: #   - unix     - The user can be authenticated against the unix
                   2196: #                password file.
                   2197: #   - internal - The user can be authenticated against a purely 
                   2198: #                internal per user password file.
                   2199: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
                   2200: #                ticket granting authority.
                   2201: #   - user     - The person tailoring LonCAPA can supply a user authentication
                   2202: #                mechanism that is per system.
                   2203: #
                   2204: # Parameters:
                   2205: #    $cmd      - The command that got us here.
                   2206: #    $tail     - Tail of the command (remaining parameters).
                   2207: #    $client   - File descriptor connected to client.
                   2208: # Returns
                   2209: #     0        - Requested to exit, caller should shut down.
                   2210: #     1        - Continue processing.
                   2211: # Implicit inputs:
                   2212: #    The authentication systems describe above have their own forms of implicit
                   2213: #    input into the authentication process that are described above.
                   2214: #
                   2215: sub authenticate_handler {
                   2216:     my ($cmd, $tail, $client) = @_;
                   2217: 
                   2218:     
                   2219:     #  Regenerate the full input line 
                   2220:     
                   2221:     my $userinput  = $cmd.":".$tail;
                   2222:     
                   2223:     #  udom    - User's domain.
                   2224:     #  uname   - Username.
                   2225:     #  upass   - User's password.
1.396     raeburn  2226:     #  checkdefauth - Pass to validate_user() to try authentication
                   2227:     #                 with default auth type(s) if no user account.
1.447     raeburn  2228:     #  clientcancheckhost - Passed by clients with functionality in lonauth.pm
                   2229:     #                       to check if session can be hosted.
1.220     foxr     2230:     
1.447     raeburn  2231:     my ($udom, $uname, $upass, $checkdefauth, $clientcancheckhost)=split(/:/,$tail);
1.399     raeburn  2232:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass,  checkdefauth = $checkdefauth");
1.220     foxr     2233:     chomp($upass);
                   2234:     $upass=&unescape($upass);
                   2235: 
1.396     raeburn  2236:     my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
1.220     foxr     2237:     if($pwdcorrect) {
1.447     raeburn  2238:         my $canhost = 1;
                   2239:         unless ($clientcancheckhost) {
1.448     raeburn  2240:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   2241:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.452     raeburn  2242:             my @intdoms;
                   2243:             my $internet_names = &Apache::lonnet::get_internet_names($clientname);
                   2244:             if (ref($internet_names) eq 'ARRAY') {
                   2245:                 @intdoms = @{$internet_names};
                   2246:             }
1.448     raeburn  2247:             unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
1.447     raeburn  2248:                 my ($remote,$hosted);
                   2249:                 my $remotesession = &get_usersession_config($udom,'remotesession');
                   2250:                 if (ref($remotesession) eq 'HASH') {
1.525     raeburn  2251:                     $remote = $remotesession->{'remote'};
1.447     raeburn  2252:                 }
1.448     raeburn  2253:                 my $hostedsession = &get_usersession_config($clienthomedom,'hostedsession');
1.447     raeburn  2254:                 if (ref($hostedsession) eq 'HASH') {
                   2255:                     $hosted = $hostedsession->{'hosted'};
                   2256:                 }
1.448     raeburn  2257:                 $canhost = &Apache::lonnet::can_host_session($udom,$clientname,
1.492     droeschl 2258:                                                              $clientversion,
1.447     raeburn  2259:                                                              $remote,$hosted);
                   2260:             }
                   2261:         }
                   2262:         if ($canhost) {               
                   2263:             &Reply( $client, "authorized\n", $userinput);
                   2264:         } else {
                   2265:             &Reply( $client, "not_allowed_to_host\n", $userinput);
                   2266:         }
1.220     foxr     2267: 	#
                   2268: 	#  Bad credentials: Failed to authorize
                   2269: 	#
                   2270:     } else {
                   2271: 	&Failure( $client, "non_authorized\n", $userinput);
                   2272:     }
                   2273: 
                   2274:     return 1;
                   2275: }
1.263     albertel 2276: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
1.214     foxr     2277: 
1.222     foxr     2278: #
                   2279: #   Change a user's password.  Note that this function is complicated by
                   2280: #   the fact that a user may be authenticated in more than one way:
                   2281: #   At present, we are not able to change the password for all types of
                   2282: #   authentication methods.  Only for:
                   2283: #      unix    - unix password or shadow passoword style authentication.
                   2284: #      local   - Locally written authentication mechanism.
                   2285: #   For now, kerb4 and kerb5 password changes are not supported and result
                   2286: #   in an error.
                   2287: # FUTURE WORK:
                   2288: #    Support kerberos passwd changes?
                   2289: # Parameters:
                   2290: #    $cmd      - The command that got us here.
                   2291: #    $tail     - Tail of the command (remaining parameters).
                   2292: #    $client   - File descriptor connected to client.
                   2293: # Returns
                   2294: #     0        - Requested to exit, caller should shut down.
                   2295: #     1        - Continue processing.
                   2296: # Implicit inputs:
                   2297: #    The authentication systems describe above have their own forms of implicit
                   2298: #    input into the authentication process that are described above.
                   2299: sub change_password_handler {
                   2300:     my ($cmd, $tail, $client) = @_;
                   2301: 
                   2302:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
                   2303: 
                   2304:     #
                   2305:     #  udom  - user's domain.
                   2306:     #  uname - Username.
                   2307:     #  upass - Current password.
                   2308:     #  npass - New password.
1.346     raeburn  2309:     #  context - Context in which this was called 
                   2310:     #            (preferences or reset_by_email).
1.428     raeburn  2311:     #  lonhost - HostID of server where request originated 
1.222     foxr     2312:    
1.428     raeburn  2313:     my ($udom,$uname,$upass,$npass,$context,$lonhost)=split(/:/,$tail);
1.222     foxr     2314: 
                   2315:     $upass=&unescape($upass);
                   2316:     $npass=&unescape($npass);
                   2317:     &Debug("Trying to change password for $uname");
                   2318: 
                   2319:     # First require that the user can be authenticated with their
1.346     raeburn  2320:     # old password unless context was 'reset_by_email':
                   2321:     
1.428     raeburn  2322:     my ($validated,$failure);
1.346     raeburn  2323:     if ($context eq 'reset_by_email') {
1.428     raeburn  2324:         if ($lonhost eq '') {
                   2325:             $failure = 'invalid_client';
                   2326:         } else {
                   2327:             $validated = 1;
                   2328:         }
1.346     raeburn  2329:     } else {
                   2330:         $validated = &validate_user($udom, $uname, $upass);
                   2331:     }
1.222     foxr     2332:     if($validated) {
                   2333: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
                   2334: 	
                   2335: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
                   2336: 	if ($howpwd eq 'internal') {
                   2337: 	    &Debug("internal auth");
1.518     raeburn  2338:             my $ncpass = &hash_passwd($udom,$npass);
1.222     foxr     2339: 	    if(&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
1.428     raeburn  2340: 		my $msg="Result of password change for $uname: pwchange_success";
                   2341:                 if ($lonhost) {
                   2342:                     $msg .= " - request originated from: $lonhost";
                   2343:                 }
                   2344:                 &logthis($msg);
1.518     raeburn  2345:                 &update_passwd_history($uname,$udom,$howpwd,$context);
1.222     foxr     2346: 		&Reply($client, "ok\n", $userinput);
                   2347: 	    } else {
                   2348: 		&logthis("Unable to open $uname passwd "               
                   2349: 			 ."to change password");
                   2350: 		&Failure( $client, "non_authorized\n",$userinput);
                   2351: 	    }
1.346     raeburn  2352: 	} elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
1.287     foxr     2353: 	    my $result = &change_unix_password($uname, $npass);
1.518     raeburn  2354:             if ($result eq 'ok') {
                   2355:                 &update_passwd_history($uname,$udom,$howpwd,$context);
                   2356:              }
1.222     foxr     2357: 	    &logthis("Result of password change for $uname: ".
1.287     foxr     2358: 		     $result);
1.387     albertel 2359: 	    &Reply($client, \$result, $userinput);
1.222     foxr     2360: 	} else {
                   2361: 	    # this just means that the current password mode is not
                   2362: 	    # one we know how to change (e.g the kerberos auth modes or
                   2363: 	    # locally written auth handler).
                   2364: 	    #
                   2365: 	    &Failure( $client, "auth_mode_error\n", $userinput);
                   2366: 	}  
                   2367: 	
1.224     foxr     2368:     } else {
1.428     raeburn  2369: 	if ($failure eq '') {
                   2370: 	    $failure = 'non_authorized';
                   2371: 	}
                   2372: 	&Failure( $client, "$failure\n", $userinput);
1.222     foxr     2373:     }
                   2374: 
                   2375:     return 1;
                   2376: }
1.263     albertel 2377: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
1.222     foxr     2378: 
1.518     raeburn  2379: sub hash_passwd {
                   2380:     my ($domain,$plainpass,@rest) = @_;
                   2381:     my ($salt,$cost);
                   2382:     if (@rest) {
                   2383:         $cost = $rest[0];
                   2384:         # salt is first 22 characters, base-64 encoded by bcrypt
                   2385:         my $plainsalt = substr($rest[1],0,22);
                   2386:         $salt = Crypt::Eksblowfish::Bcrypt::de_base64($plainsalt);
                   2387:     } else {
1.533     raeburn  2388:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2389:         my $defaultcost = $domdefaults{'intauth_cost'};
1.518     raeburn  2390:         if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   2391:             $cost = 10;
                   2392:         } else {
                   2393:             $cost = $defaultcost;
                   2394:         }
                   2395:         # Generate random 16-octet base64 salt
                   2396:         $salt = "";
                   2397:         $salt .= pack("C", int rand(256)) for 1..16;
                   2398:     }
                   2399:     my $hash = &Crypt::Eksblowfish::Bcrypt::bcrypt_hash({
                   2400:         key_nul => 1,
                   2401:         cost    => $cost,
                   2402:         salt    => $salt,
                   2403:     }, Digest::SHA::sha512(Encode::encode('UTF-8',$plainpass)));
                   2404: 
                   2405:     my $result = join("!", "", "bcrypt", sprintf("%02d",$cost),
                   2406:                 &Crypt::Eksblowfish::Bcrypt::en_base64($salt).
                   2407:                 &Crypt::Eksblowfish::Bcrypt::en_base64($hash));
                   2408:     return $result;
                   2409: }
                   2410: 
1.225     foxr     2411: #
                   2412: #   Create a new user.  User in this case means a lon-capa user.
                   2413: #   The user must either already exist in some authentication realm
                   2414: #   like kerberos or the /etc/passwd.  If not, a user completely local to
                   2415: #   this loncapa system is created.
                   2416: #
                   2417: # Parameters:
                   2418: #    $cmd      - The command that got us here.
                   2419: #    $tail     - Tail of the command (remaining parameters).
                   2420: #    $client   - File descriptor connected to client.
                   2421: # Returns
                   2422: #     0        - Requested to exit, caller should shut down.
                   2423: #     1        - Continue processing.
                   2424: # Implicit inputs:
                   2425: #    The authentication systems describe above have their own forms of implicit
                   2426: #    input into the authentication process that are described above.
                   2427: sub add_user_handler {
                   2428: 
                   2429:     my ($cmd, $tail, $client) = @_;
                   2430: 
                   2431: 
                   2432:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2433:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
                   2434: 
                   2435:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
                   2436: 
                   2437: 
                   2438:     if($udom eq $currentdomainid) { # Reject new users for other domains...
                   2439: 	
                   2440: 	my $oldumask=umask(0077);
                   2441: 	chomp($npass);
                   2442: 	$npass=&unescape($npass);
                   2443: 	my $passfilename  = &password_path($udom, $uname);
                   2444: 	&Debug("Password file created will be:".$passfilename);
                   2445: 	if (-e $passfilename) {
                   2446: 	    &Failure( $client, "already_exists\n", $userinput);
                   2447: 	} else {
                   2448: 	    my $fperror='';
1.264     albertel 2449: 	    if (!&mkpath($passfilename)) {
                   2450: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
                   2451: 		    ."makeuser";
1.225     foxr     2452: 	    }
                   2453: 	    unless ($fperror) {
1.518     raeburn  2454: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2455:                                              $passfilename,'makeuser');
1.390     raeburn  2456: 		&Reply($client,\$result, $userinput);     #BUGBUG - could be fail
1.225     foxr     2457: 	    } else {
1.387     albertel 2458: 		&Failure($client, \$fperror, $userinput);
1.225     foxr     2459: 	    }
                   2460: 	}
                   2461: 	umask($oldumask);
                   2462:     }  else {
                   2463: 	&Failure($client, "not_right_domain\n",
                   2464: 		$userinput);	# Even if we are multihomed.
                   2465:     
                   2466:     }
                   2467:     return 1;
                   2468: 
                   2469: }
                   2470: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
                   2471: 
                   2472: #
                   2473: #   Change the authentication method of a user.  Note that this may
                   2474: #   also implicitly change the user's password if, for example, the user is
                   2475: #   joining an existing authentication realm.  Known authentication realms at
                   2476: #   this time are:
                   2477: #    internal   - Purely internal password file (only loncapa knows this user)
                   2478: #    local      - Institutionally written authentication module.
                   2479: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
                   2480: #    kerb4      - kerberos version 4
                   2481: #    kerb5      - kerberos version 5
                   2482: #
                   2483: # Parameters:
                   2484: #    $cmd      - The command that got us here.
                   2485: #    $tail     - Tail of the command (remaining parameters).
                   2486: #    $client   - File descriptor connected to client.
                   2487: # Returns
                   2488: #     0        - Requested to exit, caller should shut down.
                   2489: #     1        - Continue processing.
                   2490: # Implicit inputs:
                   2491: #    The authentication systems describe above have their own forms of implicit
                   2492: #    input into the authentication process that are described above.
1.287     foxr     2493: # NOTE:
                   2494: #   This is also used to change the authentication credential values (e.g. passwd).
                   2495: #   
1.225     foxr     2496: #
                   2497: sub change_authentication_handler {
                   2498: 
                   2499:     my ($cmd, $tail, $client) = @_;
                   2500:    
                   2501:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
                   2502: 
                   2503:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2504:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
                   2505:     if ($udom ne $currentdomainid) {
                   2506: 	&Failure( $client, "not_right_domain\n", $client);
                   2507:     } else {
                   2508: 	
                   2509: 	chomp($npass);
                   2510: 	
                   2511: 	$npass=&unescape($npass);
1.261     foxr     2512: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
1.225     foxr     2513: 	my $passfilename = &password_path($udom, $uname);
                   2514: 	if ($passfilename) {	# Not allowed to create a new user!!
1.287     foxr     2515: 	    # If just changing the unix passwd. need to arrange to run
1.502     raeburn  2516: 	    # passwd since otherwise make_passwd_file will fail as 
                   2517: 	    # creation of unix authenticated users is no longer supported
                   2518:             # except from the command line, when running make_domain_coordinator.pl
1.287     foxr     2519: 
                   2520: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
                   2521: 		my $result = &change_unix_password($uname, $npass);
                   2522: 		&logthis("Result of password change for $uname: ".$result);
                   2523: 		if ($result eq "ok") {
1.518     raeburn  2524:                     &update_passwd_history($uname,$udom,$umode,'changeuserauth'); 
1.390     raeburn  2525: 		    &Reply($client, \$result);
1.288     albertel 2526: 		} else {
1.387     albertel 2527: 		    &Failure($client, \$result);
1.287     foxr     2528: 		}
1.288     albertel 2529: 	    } else {
1.518     raeburn  2530: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2531:                                              $passfilename,'changeuserauth');
1.287     foxr     2532: 		#
                   2533: 		#  If the current auth mode is internal, and the old auth mode was
                   2534: 		#  unix, or krb*,  and the user is an author for this domain,
                   2535: 		#  re-run manage_permissions for that role in order to be able
                   2536: 		#  to take ownership of the construction space back to www:www
                   2537: 		#
1.502     raeburn  2538: 
                   2539: 
1.387     albertel 2540: 		&Reply($client, \$result, $userinput);
1.261     foxr     2541: 	    }
                   2542: 	       
                   2543: 
1.225     foxr     2544: 	} else {	       
1.251     foxr     2545: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
1.225     foxr     2546: 	}
                   2547:     }
                   2548:     return 1;
                   2549: }
                   2550: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
                   2551: 
1.518     raeburn  2552: sub update_passwd_history {
                   2553:     my ($uname,$udom,$umode,$context) = @_;
                   2554:     my $proname=&propath($udom,$uname);
                   2555:     my $now = time;
                   2556:     if (open(my $fh,">>$proname/passwd.log")) {
                   2557:         print $fh "$now:$umode:$context\n";
                   2558:         close($fh);
                   2559:     }
                   2560:     return;
                   2561: }
                   2562: 
1.225     foxr     2563: #
                   2564: #   Determines if this is the home server for a user.  The home server
                   2565: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
                   2566: #   to do is determine if this file exists.
                   2567: #
                   2568: # Parameters:
                   2569: #    $cmd      - The command that got us here.
                   2570: #    $tail     - Tail of the command (remaining parameters).
                   2571: #    $client   - File descriptor connected to client.
                   2572: # Returns
                   2573: #     0        - Requested to exit, caller should shut down.
                   2574: #     1        - Continue processing.
                   2575: # Implicit inputs:
                   2576: #    The authentication systems describe above have their own forms of implicit
                   2577: #    input into the authentication process that are described above.
                   2578: #
                   2579: sub is_home_handler {
                   2580:     my ($cmd, $tail, $client) = @_;
                   2581:    
                   2582:     my $userinput  = "$cmd:$tail";
                   2583:    
                   2584:     my ($udom,$uname)=split(/:/,$tail);
                   2585:     chomp($uname);
                   2586:     my $passfile = &password_filename($udom, $uname);
                   2587:     if($passfile) {
                   2588: 	&Reply( $client, "found\n", $userinput);
                   2589:     } else {
                   2590: 	&Failure($client, "not_found\n", $userinput);
                   2591:     }
                   2592:     return 1;
                   2593: }
                   2594: &register_handler("home", \&is_home_handler, 0,1,0);
                   2595: 
                   2596: #
1.434     www      2597: #   Process an update request for a resource.
                   2598: #   A resource has been modified that we hold a subscription to.
1.225     foxr     2599: #   If the resource is not local, then we must update, or at least invalidate our
                   2600: #   cached copy of the resource. 
                   2601: # Parameters:
                   2602: #    $cmd      - The command that got us here.
                   2603: #    $tail     - Tail of the command (remaining parameters).
                   2604: #    $client   - File descriptor connected to client.
                   2605: # Returns
                   2606: #     0        - Requested to exit, caller should shut down.
                   2607: #     1        - Continue processing.
                   2608: # Implicit inputs:
                   2609: #    The authentication systems describe above have their own forms of implicit
                   2610: #    input into the authentication process that are described above.
                   2611: #
                   2612: sub update_resource_handler {
                   2613: 
                   2614:     my ($cmd, $tail, $client) = @_;
                   2615:    
                   2616:     my $userinput = "$cmd:$tail";
                   2617:    
                   2618:     my $fname= $tail;		# This allows interactive testing
                   2619: 
                   2620: 
                   2621:     my $ownership=ishome($fname);
                   2622:     if ($ownership eq 'not_owner') {
                   2623: 	if (-e $fname) {
1.434     www      2624:             # Delete preview file, if exists
                   2625:             unlink("$fname.tmp");
                   2626:             # Get usage stats
1.225     foxr     2627: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
                   2628: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
                   2629: 	    my $now=time;
                   2630: 	    my $since=$now-$atime;
1.434     www      2631:             # If the file has not been used within lonExpire seconds,
                   2632:             # unsubscribe from it and delete local copy
1.225     foxr     2633: 	    if ($since>$perlvar{'lonExpire'}) {
1.365     albertel 2634: 		my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
1.308     albertel 2635: 		&devalidate_meta_cache($fname);
1.225     foxr     2636: 		unlink("$fname");
1.334     albertel 2637: 		unlink("$fname.meta");
1.225     foxr     2638: 	    } else {
1.434     www      2639:             # Yes, this is in active use. Get a fresh copy. Since it might be in
                   2640:             # very active use and huge (like a movie), copy it to "in.transfer" filename first.
1.225     foxr     2641: 		my $transname="$fname.in.transfer";
1.365     albertel 2642: 		my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
1.225     foxr     2643: 		my $response;
1.537     raeburn  2644: # FIXME: cannot replicate files that take more than two minutes to transfer -- needs checking now 1200s timeout used
                   2645: # for LWP request.
                   2646: 		my $request=new HTTP::Request('GET',"$remoteurl");
                   2647:                 $response=&LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,0,1);
1.225     foxr     2648: 		if ($response->is_error()) {
1.541     raeburn  2649:                     my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
                   2650:                     &devalidate_meta_cache($fname);
                   2651:                     if (-e $transname) {
                   2652:                         unlink($transname);
                   2653:                     }
                   2654:                     unlink($fname);
1.225     foxr     2655: 		    my $message=$response->status_line;
                   2656: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2657: 		} else {
                   2658: 		    if ($remoteurl!~/\.meta$/) {
1.537     raeburn  2659: 			my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2660:                         my $mresponse = &LONCAPA::LWPReq::makerequest($clientname,$mrequest,$fname.'.meta',\%perlvar,120,0,1);
                   2661: 			if ($mresponse->is_error()) {
                   2662: 			    unlink($fname.'.meta');
1.225     foxr     2663: 			}
                   2664: 		    }
1.434     www      2665:                     # we successfully transfered, copy file over to real name
1.225     foxr     2666: 		    rename($transname,$fname);
1.308     albertel 2667: 		    &devalidate_meta_cache($fname);
1.225     foxr     2668: 		}
                   2669: 	    }
                   2670: 	    &Reply( $client, "ok\n", $userinput);
                   2671: 	} else {
                   2672: 	    &Failure($client, "not_found\n", $userinput);
                   2673: 	}
                   2674:     } else {
                   2675: 	&Failure($client, "rejected\n", $userinput);
                   2676:     }
                   2677:     return 1;
                   2678: }
                   2679: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
                   2680: 
1.308     albertel 2681: sub devalidate_meta_cache {
                   2682:     my ($url) = @_;
                   2683:     use Cache::Memcached;
                   2684:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.365     albertel 2685:     $url = &Apache::lonnet::declutter($url);
1.308     albertel 2686:     $url =~ s-\.meta$--;
                   2687:     my $id = &escape('meta:'.$url);
                   2688:     $memcache->delete($id);
                   2689: }
                   2690: 
1.225     foxr     2691: #
1.226     foxr     2692: #   Fetch a user file from a remote server to the user's home directory
                   2693: #   userfiles subdir.
1.225     foxr     2694: # Parameters:
                   2695: #    $cmd      - The command that got us here.
                   2696: #    $tail     - Tail of the command (remaining parameters).
                   2697: #    $client   - File descriptor connected to client.
                   2698: # Returns
                   2699: #     0        - Requested to exit, caller should shut down.
                   2700: #     1        - Continue processing.
                   2701: #
                   2702: sub fetch_user_file_handler {
                   2703: 
                   2704:     my ($cmd, $tail, $client) = @_;
                   2705: 
                   2706:     my $userinput = "$cmd:$tail";
                   2707:     my $fname           = $tail;
1.232     foxr     2708:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1.225     foxr     2709:     my $udir=&propath($udom,$uname).'/userfiles';
                   2710:     unless (-e $udir) {
                   2711: 	mkdir($udir,0770); 
                   2712:     }
1.232     foxr     2713:     Debug("fetch user file for $fname");
1.225     foxr     2714:     if (-e $udir) {
                   2715: 	$ufile=~s/^[\.\~]+//;
1.232     foxr     2716: 
                   2717: 	# IF necessary, create the path right down to the file.
                   2718: 	# Note that any regular files in the way of this path are
                   2719: 	# wiped out to deal with some earlier folly of mine.
                   2720: 
1.267     raeburn  2721: 	if (!&mkpath($udir.'/'.$ufile)) {
1.264     albertel 2722: 	    &Failure($client, "unable_to_create\n", $userinput);	    
1.232     foxr     2723: 	}
                   2724: 
1.225     foxr     2725: 	my $destname=$udir.'/'.$ufile;
                   2726: 	my $transname=$udir.'/'.$ufile.'.in.transit';
1.476     raeburn  2727:         my $clientprotocol=$Apache::lonnet::protocol{$clientname};
                   2728:         $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.486     raeburn  2729: 	my $clienthost = &Apache::lonnet::hostname($clientname);
                   2730: 	my $remoteurl=$clientprotocol.'://'.$clienthost.'/userfiles/'.$fname;
1.225     foxr     2731: 	my $response;
1.232     foxr     2732: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
1.537     raeburn  2733: 	my $request=new HTTP::Request('GET',"$remoteurl");
                   2734:         my $verifycert = 1;
                   2735:         my @machine_ids = &Apache::lonnet::current_machine_ids();
                   2736:         if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   2737:             $verifycert = 0;
                   2738:         }
                   2739:         $response = &LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,$verifycert);
1.225     foxr     2740: 	if ($response->is_error()) {
                   2741: 	    unlink($transname);
                   2742: 	    my $message=$response->status_line;
                   2743: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2744: 	    &Failure($client, "failed\n", $userinput);
                   2745: 	} else {
1.232     foxr     2746: 	    Debug("Renaming $transname to $destname");
1.225     foxr     2747: 	    if (!rename($transname,$destname)) {
                   2748: 		&logthis("Unable to move $transname to $destname");
                   2749: 		unlink($transname);
                   2750: 		&Failure($client, "failed\n", $userinput);
                   2751: 	    } else {
1.495     raeburn  2752:                 if ($fname =~ /^default.+\.(page|sequence)$/) {
                   2753:                     my ($major,$minor) = split(/\./,$clientversion);
                   2754:                     if (($major < 2) || ($major == 2 && $minor < 11)) {
                   2755:                         my $now = time;
                   2756:                         &Apache::lonnet::do_cache_new('crschange',$udom.'_'.$uname,$now,600);
                   2757:                         my $key = &escape('internal.contentchange');
                   2758:                         my $what = "$key=$now";
                   2759:                         my $hashref = &tie_user_hash($udom,$uname,'environment',
                   2760:                                                      &GDBM_WRCREAT(),"P",$what);
                   2761:                         if ($hashref) {
                   2762:                             $hashref->{$key}=$now;
                   2763:                             if (!&untie_user_hash($hashref)) {
                   2764:                                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   2765:                                          "when updating internal.contentchange");
                   2766:                             }
                   2767:                         }
                   2768:                     }
                   2769:                 }
1.225     foxr     2770: 		&Reply($client, "ok\n", $userinput);
                   2771: 	    }
                   2772: 	}   
                   2773:     } else {
                   2774: 	&Failure($client, "not_home\n", $userinput);
                   2775:     }
                   2776:     return 1;
                   2777: }
                   2778: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
                   2779: 
1.226     foxr     2780: #
                   2781: #   Remove a file from a user's home directory userfiles subdirectory.
                   2782: # Parameters:
                   2783: #    cmd   - the Lond request keyword that got us here.
                   2784: #    tail  - the part of the command past the keyword.
                   2785: #    client- File descriptor connected with the client.
                   2786: #
                   2787: # Returns:
                   2788: #    1    - Continue processing.
                   2789: sub remove_user_file_handler {
                   2790:     my ($cmd, $tail, $client) = @_;
                   2791: 
                   2792:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2793: 
                   2794:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2795:     if ($ufile =~m|/\.\./|) {
                   2796: 	# any files paths with /../ in them refuse 
                   2797: 	# to deal with
                   2798: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2799:     } else {
                   2800: 	my $udir = &propath($udom,$uname);
                   2801: 	if (-e $udir) {
                   2802: 	    my $file=$udir.'/userfiles/'.$ufile;
                   2803: 	    if (-e $file) {
1.253     foxr     2804: 		#
                   2805: 		#   If the file is a regular file unlink is fine...
1.520     raeburn  2806: 		#   However it's possible the client wants a dir 
                   2807: 		#   removed, in which case rmdir is more appropriate.
                   2808: 		#   Note: rmdir will only remove an empty directory.
1.253     foxr     2809: 		#
1.240     banghart 2810: 	        if (-f $file){
1.241     albertel 2811: 		    unlink($file);
1.520     raeburn  2812:                     # for html files remove the associated .bak file 
                   2813:                     # which may have been created by the editor.
                   2814:                     if ($ufile =~ m{^((docs|supplemental)/(?:\d+|default)/\d+(?:|/.+)/)[^/]+\.x?html?$}i) {
                   2815:                         my $path = $1;
                   2816:                         if (-e $file.'.bak') {
                   2817:                             unlink($file.'.bak');
                   2818:                         }
                   2819:                     }
1.241     albertel 2820: 		} elsif(-d $file) {
                   2821: 		    rmdir($file);
1.240     banghart 2822: 		}
1.226     foxr     2823: 		if (-e $file) {
1.253     foxr     2824: 		    #  File is still there after we deleted it ?!?
                   2825: 
1.226     foxr     2826: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2827: 		} else {
                   2828: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2829: 		}
                   2830: 	    } else {
                   2831: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2832: 	    }
                   2833: 	} else {
                   2834: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2835: 	}
                   2836:     }
                   2837:     return 1;
                   2838: }
                   2839: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
                   2840: 
1.236     albertel 2841: #
                   2842: #   make a directory in a user's home directory userfiles subdirectory.
                   2843: # Parameters:
                   2844: #    cmd   - the Lond request keyword that got us here.
                   2845: #    tail  - the part of the command past the keyword.
                   2846: #    client- File descriptor connected with the client.
                   2847: #
                   2848: # Returns:
                   2849: #    1    - Continue processing.
                   2850: sub mkdir_user_file_handler {
                   2851:     my ($cmd, $tail, $client) = @_;
                   2852: 
                   2853:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2854:     $dir=&unescape($dir);
                   2855:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2856:     if ($ufile =~m|/\.\./|) {
                   2857: 	# any files paths with /../ in them refuse 
                   2858: 	# to deal with
                   2859: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2860:     } else {
                   2861: 	my $udir = &propath($udom,$uname);
                   2862: 	if (-e $udir) {
1.264     albertel 2863: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
                   2864: 	    if (!&mkpath($newdir)) {
                   2865: 		&Failure($client, "failed\n", "$cmd:$tail");
1.236     albertel 2866: 	    }
1.264     albertel 2867: 	    &Reply($client, "ok\n", "$cmd:$tail");
1.236     albertel 2868: 	} else {
                   2869: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2870: 	}
                   2871:     }
                   2872:     return 1;
                   2873: }
                   2874: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
                   2875: 
1.237     albertel 2876: #
                   2877: #   rename a file in a user's home directory userfiles subdirectory.
                   2878: # Parameters:
                   2879: #    cmd   - the Lond request keyword that got us here.
                   2880: #    tail  - the part of the command past the keyword.
                   2881: #    client- File descriptor connected with the client.
                   2882: #
                   2883: # Returns:
                   2884: #    1    - Continue processing.
                   2885: sub rename_user_file_handler {
                   2886:     my ($cmd, $tail, $client) = @_;
                   2887: 
                   2888:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
                   2889:     $old=&unescape($old);
                   2890:     $new=&unescape($new);
                   2891:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
                   2892: 	# any files paths with /../ in them refuse to deal with
                   2893: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2894:     } else {
                   2895: 	my $udir = &propath($udom,$uname);
                   2896: 	if (-e $udir) {
                   2897: 	    my $oldfile=$udir.'/userfiles/'.$old;
                   2898: 	    my $newfile=$udir.'/userfiles/'.$new;
                   2899: 	    if (-e $newfile) {
                   2900: 		&Failure($client, "exists\n", "$cmd:$tail");
                   2901: 	    } elsif (! -e $oldfile) {
                   2902: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2903: 	    } else {
                   2904: 		if (!rename($oldfile,$newfile)) {
                   2905: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2906: 		} else {
                   2907: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2908: 		}
                   2909: 	    }
                   2910: 	} else {
                   2911: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2912: 	}
                   2913:     }
                   2914:     return 1;
                   2915: }
                   2916: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
                   2917: 
1.227     foxr     2918: #
1.382     albertel 2919: #  Checks if the specified user has an active session on the server
                   2920: #  return ok if so, not_found if not
                   2921: #
                   2922: # Parameters:
                   2923: #   cmd      - The request keyword that dispatched to tus.
                   2924: #   tail     - The tail of the request (colon separated parameters).
                   2925: #   client   - Filehandle open on the client.
                   2926: # Return:
                   2927: #    1.
                   2928: sub user_has_session_handler {
                   2929:     my ($cmd, $tail, $client) = @_;
                   2930: 
                   2931:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
                   2932:     
                   2933:     opendir(DIR,$perlvar{'lonIDsDir'});
                   2934:     my $filename;
                   2935:     while ($filename=readdir(DIR)) {
                   2936: 	last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
                   2937:     }
                   2938:     if ($filename) {
                   2939: 	&Reply($client, "ok\n", "$cmd:$tail");
                   2940:     } else {
                   2941: 	&Failure($client, "not_found\n", "$cmd:$tail");
                   2942:     }
                   2943:     return 1;
                   2944: 
                   2945: }
                   2946: &register_handler("userhassession", \&user_has_session_handler, 0,1,0);
                   2947: 
                   2948: #
1.263     albertel 2949: #  Authenticate access to a user file by checking that the token the user's 
                   2950: #  passed also exists in their session file
1.227     foxr     2951: #
                   2952: # Parameters:
                   2953: #   cmd      - The request keyword that dispatched to tus.
                   2954: #   tail     - The tail of the request (colon separated parameters).
                   2955: #   client   - Filehandle open on the client.
                   2956: # Return:
                   2957: #    1.
                   2958: sub token_auth_user_file_handler {
                   2959:     my ($cmd, $tail, $client) = @_;
                   2960: 
                   2961:     my ($fname, $session) = split(/:/, $tail);
                   2962:     
                   2963:     chomp($session);
1.393     raeburn  2964:     my $reply="non_auth";
1.343     albertel 2965:     my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
                   2966:     if (open(ENVIN,"$file")) {
1.332     albertel 2967: 	flock(ENVIN,LOCK_SH);
1.343     albertel 2968: 	tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
                   2969: 	if (exists($disk_env{"userfile.$fname"})) {
1.393     raeburn  2970: 	    $reply="ok";
1.343     albertel 2971: 	} else {
                   2972: 	    foreach my $envname (keys(%disk_env)) {
                   2973: 		if ($envname=~ m|^userfile\.\Q$fname\E|) {
1.393     raeburn  2974: 		    $reply="ok";
1.343     albertel 2975: 		    last;
                   2976: 		}
                   2977: 	    }
1.227     foxr     2978: 	}
1.343     albertel 2979: 	untie(%disk_env);
1.227     foxr     2980: 	close(ENVIN);
1.387     albertel 2981: 	&Reply($client, \$reply, "$cmd:$tail");
1.227     foxr     2982:     } else {
                   2983: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
                   2984:     }
                   2985:     return 1;
                   2986: 
                   2987: }
                   2988: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229     foxr     2989: 
                   2990: #
                   2991: #   Unsubscribe from a resource.
                   2992: #
                   2993: # Parameters:
                   2994: #    $cmd      - The command that got us here.
                   2995: #    $tail     - Tail of the command (remaining parameters).
                   2996: #    $client   - File descriptor connected to client.
                   2997: # Returns
                   2998: #     0        - Requested to exit, caller should shut down.
                   2999: #     1        - Continue processing.
                   3000: #
                   3001: sub unsubscribe_handler {
                   3002:     my ($cmd, $tail, $client) = @_;
                   3003: 
                   3004:     my $userinput= "$cmd:$tail";
                   3005:     
                   3006:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
                   3007: 
                   3008:     &Debug("Unsubscribing $fname");
                   3009:     if (-e $fname) {
                   3010: 	&Debug("Exists");
                   3011: 	&Reply($client, &unsub($fname,$clientip), $userinput);
                   3012:     } else {
                   3013: 	&Failure($client, "not_found\n", $userinput);
                   3014:     }
                   3015:     return 1;
                   3016: }
                   3017: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
1.263     albertel 3018: 
1.230     foxr     3019: #   Subscribe to a resource
                   3020: #
                   3021: # Parameters:
                   3022: #    $cmd      - The command that got us here.
                   3023: #    $tail     - Tail of the command (remaining parameters).
                   3024: #    $client   - File descriptor connected to client.
                   3025: # Returns
                   3026: #     0        - Requested to exit, caller should shut down.
                   3027: #     1        - Continue processing.
                   3028: #
                   3029: sub subscribe_handler {
                   3030:     my ($cmd, $tail, $client)= @_;
                   3031: 
                   3032:     my $userinput  = "$cmd:$tail";
                   3033: 
                   3034:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
                   3035: 
                   3036:     return 1;
                   3037: }
                   3038: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
                   3039: 
                   3040: #
1.379     albertel 3041: #   Determine the latest version of a resource (it looks for the highest
                   3042: #   past version and then returns that +1)
1.230     foxr     3043: #
                   3044: # Parameters:
                   3045: #    $cmd      - The command that got us here.
                   3046: #    $tail     - Tail of the command (remaining parameters).
1.379     albertel 3047: #                 (Should consist of an absolute path to a file)
1.230     foxr     3048: #    $client   - File descriptor connected to client.
                   3049: # Returns
                   3050: #     0        - Requested to exit, caller should shut down.
                   3051: #     1        - Continue processing.
                   3052: #
                   3053: sub current_version_handler {
                   3054:     my ($cmd, $tail, $client) = @_;
                   3055: 
                   3056:     my $userinput= "$cmd:$tail";
                   3057:    
                   3058:     my $fname   = $tail;
                   3059:     &Reply( $client, &currentversion($fname)."\n", $userinput);
                   3060:     return 1;
                   3061: 
                   3062: }
                   3063: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
                   3064: 
                   3065: #  Make an entry in a user's activity log.
                   3066: #
                   3067: # Parameters:
                   3068: #    $cmd      - The command that got us here.
                   3069: #    $tail     - Tail of the command (remaining parameters).
                   3070: #    $client   - File descriptor connected to client.
                   3071: # Returns
                   3072: #     0        - Requested to exit, caller should shut down.
                   3073: #     1        - Continue processing.
                   3074: #
                   3075: sub activity_log_handler {
                   3076:     my ($cmd, $tail, $client) = @_;
                   3077: 
                   3078: 
                   3079:     my $userinput= "$cmd:$tail";
                   3080: 
                   3081:     my ($udom,$uname,$what)=split(/:/,$tail);
                   3082:     chomp($what);
                   3083:     my $proname=&propath($udom,$uname);
                   3084:     my $now=time;
                   3085:     my $hfh;
                   3086:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
                   3087: 	print $hfh "$now:$clientname:$what\n";
                   3088: 	&Reply( $client, "ok\n", $userinput); 
                   3089:     } else {
                   3090: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
                   3091: 		 ."while attempting log\n", 
                   3092: 		 $userinput);
                   3093:     }
                   3094: 
                   3095:     return 1;
                   3096: }
1.263     albertel 3097: &register_handler("log", \&activity_log_handler, 0, 1, 0);
1.230     foxr     3098: 
                   3099: #
                   3100: #   Put a namespace entry in a user profile hash.
                   3101: #   My druthers would be for this to be an encrypted interaction too.
                   3102: #   anything that might be an inadvertent covert channel about either
                   3103: #   user authentication or user personal information....
                   3104: #
                   3105: # Parameters:
                   3106: #    $cmd      - The command that got us here.
                   3107: #    $tail     - Tail of the command (remaining parameters).
                   3108: #    $client   - File descriptor connected to client.
                   3109: # Returns
                   3110: #     0        - Requested to exit, caller should shut down.
                   3111: #     1        - Continue processing.
                   3112: #
                   3113: sub put_user_profile_entry {
                   3114:     my ($cmd, $tail, $client)  = @_;
1.229     foxr     3115: 
1.230     foxr     3116:     my $userinput = "$cmd:$tail";
                   3117:     
1.242     raeburn  3118:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
1.230     foxr     3119:     if ($namespace ne 'roles') {
                   3120: 	chomp($what);
                   3121: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3122: 				  &GDBM_WRCREAT(),"P",$what);
                   3123: 	if($hashref) {
                   3124: 	    my @pairs=split(/\&/,$what);
                   3125: 	    foreach my $pair (@pairs) {
                   3126: 		my ($key,$value)=split(/=/,$pair);
                   3127: 		$hashref->{$key}=$value;
                   3128: 	    }
1.311     albertel 3129: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3130: 		&Reply( $client, "ok\n", $userinput);
                   3131: 	    } else {
                   3132: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3133: 			"while attempting put\n", 
                   3134: 			$userinput);
                   3135: 	    }
                   3136: 	} else {
1.316     albertel 3137: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.230     foxr     3138: 		     "while attempting put\n", $userinput);
                   3139: 	}
                   3140:     } else {
                   3141:         &Failure( $client, "refused\n", $userinput);
                   3142:     }
                   3143:     
                   3144:     return 1;
                   3145: }
                   3146: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
                   3147: 
1.283     albertel 3148: #   Put a piece of new data in hash, returns error if entry already exists
                   3149: # Parameters:
                   3150: #    $cmd      - The command that got us here.
                   3151: #    $tail     - Tail of the command (remaining parameters).
                   3152: #    $client   - File descriptor connected to client.
                   3153: # Returns
                   3154: #     0        - Requested to exit, caller should shut down.
                   3155: #     1        - Continue processing.
                   3156: #
                   3157: sub newput_user_profile_entry {
                   3158:     my ($cmd, $tail, $client)  = @_;
                   3159: 
                   3160:     my $userinput = "$cmd:$tail";
                   3161: 
                   3162:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
                   3163:     if ($namespace eq 'roles') {
                   3164:         &Failure( $client, "refused\n", $userinput);
                   3165: 	return 1;
                   3166:     }
                   3167: 
                   3168:     chomp($what);
                   3169: 
                   3170:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3171: 				 &GDBM_WRCREAT(),"N",$what);
                   3172:     if(!$hashref) {
1.316     albertel 3173: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.283     albertel 3174: 		  "while attempting put\n", $userinput);
                   3175: 	return 1;
                   3176:     }
                   3177: 
                   3178:     my @pairs=split(/\&/,$what);
                   3179:     foreach my $pair (@pairs) {
                   3180: 	my ($key,$value)=split(/=/,$pair);
                   3181: 	if (exists($hashref->{$key})) {
1.513     raeburn  3182:             if (!&untie_user_hash($hashref)) {
                   3183:                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   3184:                          "while attempting newput - early out as key exists");
                   3185:             }
                   3186:             &Failure($client, "key_exists: ".$key."\n",$userinput);
                   3187:             return 1;
1.283     albertel 3188: 	}
                   3189:     }
                   3190: 
                   3191:     foreach my $pair (@pairs) {
                   3192: 	my ($key,$value)=split(/=/,$pair);
                   3193: 	$hashref->{$key}=$value;
                   3194:     }
                   3195: 
1.311     albertel 3196:     if (&untie_user_hash($hashref)) {
1.283     albertel 3197: 	&Reply( $client, "ok\n", $userinput);
                   3198:     } else {
                   3199: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3200: 		 "while attempting put\n", 
                   3201: 		 $userinput);
                   3202:     }
                   3203:     return 1;
                   3204: }
                   3205: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
                   3206: 
1.230     foxr     3207: # 
                   3208: #   Increment a profile entry in the user history file.
                   3209: #   The history contains keyword value pairs.  In this case,
                   3210: #   The value itself is a pair of numbers.  The first, the current value
                   3211: #   the second an increment that this function applies to the current
                   3212: #   value.
                   3213: #
                   3214: # Parameters:
                   3215: #    $cmd      - The command that got us here.
                   3216: #    $tail     - Tail of the command (remaining parameters).
                   3217: #    $client   - File descriptor connected to client.
                   3218: # Returns
                   3219: #     0        - Requested to exit, caller should shut down.
                   3220: #     1        - Continue processing.
                   3221: #
                   3222: sub increment_user_value_handler {
                   3223:     my ($cmd, $tail, $client) = @_;
                   3224:     
                   3225:     my $userinput   = "$cmd:$tail";
                   3226:     
                   3227:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
                   3228:     if ($namespace ne 'roles') {
                   3229:         chomp($what);
                   3230: 	my $hashref = &tie_user_hash($udom, $uname,
                   3231: 				     $namespace, &GDBM_WRCREAT(),
                   3232: 				     "P",$what);
                   3233: 	if ($hashref) {
                   3234: 	    my @pairs=split(/\&/,$what);
                   3235: 	    foreach my $pair (@pairs) {
                   3236: 		my ($key,$value)=split(/=/,$pair);
1.284     raeburn  3237:                 $value = &unescape($value);
1.230     foxr     3238: 		# We could check that we have a number...
                   3239: 		if (! defined($value) || $value eq '') {
                   3240: 		    $value = 1;
                   3241: 		}
                   3242: 		$hashref->{$key}+=$value;
1.284     raeburn  3243:                 if ($namespace eq 'nohist_resourcetracker') {
                   3244:                     if ($hashref->{$key} < 0) {
                   3245:                         $hashref->{$key} = 0;
                   3246:                     }
                   3247:                 }
1.230     foxr     3248: 	    }
1.311     albertel 3249: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3250: 		&Reply( $client, "ok\n", $userinput);
                   3251: 	    } else {
                   3252: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3253: 			 "while attempting inc\n", $userinput);
                   3254: 	    }
                   3255: 	} else {
                   3256: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3257: 		     "while attempting inc\n", $userinput);
                   3258: 	}
                   3259:     } else {
                   3260: 	&Failure($client, "refused\n", $userinput);
                   3261:     }
                   3262:     
                   3263:     return 1;
                   3264: }
                   3265: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
                   3266: 
                   3267: #
                   3268: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
                   3269: #   Each 'role' a user has implies a set of permissions.  Adding a new role
                   3270: #   for a person grants the permissions packaged with that role
                   3271: #   to that user when the role is selected.
                   3272: #
                   3273: # Parameters:
                   3274: #    $cmd       - The command string (rolesput).
                   3275: #    $tail      - The remainder of the request line.  For rolesput this
                   3276: #                 consists of a colon separated list that contains:
                   3277: #                 The domain and user that is granting the role (logged).
                   3278: #                 The domain and user that is getting the role.
                   3279: #                 The roles being granted as a set of & separated pairs.
                   3280: #                 each pair a key value pair.
                   3281: #    $client    - File descriptor connected to the client.
                   3282: # Returns:
                   3283: #     0         - If the daemon should exit
                   3284: #     1         - To continue processing.
                   3285: #
                   3286: #
                   3287: sub roles_put_handler {
                   3288:     my ($cmd, $tail, $client) = @_;
                   3289: 
                   3290:     my $userinput  = "$cmd:$tail";
                   3291: 
                   3292:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
                   3293:     
                   3294: 
                   3295:     my $namespace='roles';
                   3296:     chomp($what);
                   3297:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3298: 				 &GDBM_WRCREAT(), "P",
                   3299: 				 "$exedom:$exeuser:$what");
                   3300:     #
                   3301:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
                   3302:     #  handle is open for the minimal amount of time.  Since the flush
                   3303:     #  is done on close this improves the chances the log will be an un-
                   3304:     #  corrupted ordered thing.
                   3305:     if ($hashref) {
1.261     foxr     3306: 	my $pass_entry = &get_auth_type($udom, $uname);
                   3307: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
                   3308: 	$auth_type = $auth_type.":";
1.230     foxr     3309: 	my @pairs=split(/\&/,$what);
                   3310: 	foreach my $pair (@pairs) {
                   3311: 	    my ($key,$value)=split(/=/,$pair);
                   3312: 	    &manage_permissions($key, $udom, $uname,
1.260     foxr     3313: 			       $auth_type);
1.230     foxr     3314: 	    $hashref->{$key}=$value;
                   3315: 	}
1.311     albertel 3316: 	if (&untie_user_hash($hashref)) {
1.230     foxr     3317: 	    &Reply($client, "ok\n", $userinput);
                   3318: 	} else {
                   3319: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3320: 		     "while attempting rolesput\n", $userinput);
                   3321: 	}
                   3322:     } else {
                   3323: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3324: 		 "while attempting rolesput\n", $userinput);
                   3325:     }
                   3326:     return 1;
                   3327: }
                   3328: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
                   3329: 
                   3330: #
1.231     foxr     3331: #   Deletes (removes) a role for a user.   This is equivalent to removing
                   3332: #  a permissions package associated with the role from the user's profile.
                   3333: #
                   3334: # Parameters:
                   3335: #     $cmd                 - The command (rolesdel)
                   3336: #     $tail                - The remainder of the request line. This consists
                   3337: #                             of:
                   3338: #                             The domain and user requesting the change (logged)
                   3339: #                             The domain and user being changed.
                   3340: #                             The roles being revoked.  These are shipped to us
                   3341: #                             as a bunch of & separated role name keywords.
                   3342: #     $client              - The file handle open on the client.
                   3343: # Returns:
                   3344: #     1                    - Continue processing
                   3345: #     0                    - Exit.
                   3346: #
                   3347: sub roles_delete_handler {
                   3348:     my ($cmd, $tail, $client)  = @_;
                   3349: 
                   3350:     my $userinput    = "$cmd:$tail";
                   3351:    
                   3352:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
                   3353:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
                   3354: 	   "what = ".$what);
                   3355:     my $namespace='roles';
                   3356:     chomp($what);
                   3357:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3358: 				 &GDBM_WRCREAT(), "D",
                   3359: 				 "$exedom:$exeuser:$what");
                   3360:     
                   3361:     if ($hashref) {
                   3362: 	my @rolekeys=split(/\&/,$what);
                   3363: 	
                   3364: 	foreach my $key (@rolekeys) {
                   3365: 	    delete $hashref->{$key};
                   3366: 	}
1.315     albertel 3367: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3368: 	    &Reply($client, "ok\n", $userinput);
                   3369: 	} else {
                   3370: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3371: 		     "while attempting rolesdel\n", $userinput);
                   3372: 	}
                   3373:     } else {
                   3374:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3375: 		 "while attempting rolesdel\n", $userinput);
                   3376:     }
                   3377:     
                   3378:     return 1;
                   3379: }
                   3380: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
                   3381: 
                   3382: # Unencrypted get from a user's profile database.  See 
                   3383: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
                   3384: # This function retrieves a keyed item from a specific named database in the
                   3385: # user's directory.
                   3386: #
                   3387: # Parameters:
                   3388: #   $cmd             - Command request keyword (get).
                   3389: #   $tail            - Tail of the command.  This is a colon separated list
                   3390: #                      consisting of the domain and username that uniquely
                   3391: #                      identifies the profile,
                   3392: #                      The 'namespace' which selects the gdbm file to 
                   3393: #                      do the lookup in, 
                   3394: #                      & separated list of keys to lookup.  Note that
                   3395: #                      the values are returned as an & separated list too.
                   3396: #   $client          - File descriptor open on the client.
                   3397: # Returns:
                   3398: #   1       - Continue processing.
                   3399: #   0       - Exit.
                   3400: #
                   3401: sub get_profile_entry {
                   3402:     my ($cmd, $tail, $client) = @_;
                   3403: 
                   3404:     my $userinput= "$cmd:$tail";
                   3405:    
                   3406:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3407:     chomp($what);
1.255     foxr     3408: 
1.390     raeburn  3409: 
1.255     foxr     3410:     my $replystring = read_profile($udom, $uname, $namespace, $what);
                   3411:     my ($first) = split(/:/,$replystring);
                   3412:     if($first ne "error") {
1.387     albertel 3413: 	&Reply($client, \$replystring, $userinput);
1.231     foxr     3414:     } else {
1.255     foxr     3415: 	&Failure($client, $replystring." while attempting get\n", $userinput);
1.231     foxr     3416:     }
                   3417:     return 1;
1.255     foxr     3418: 
                   3419: 
1.231     foxr     3420: }
                   3421: &register_handler("get", \&get_profile_entry, 0,1,0);
                   3422: 
                   3423: #
                   3424: #  Process the encrypted get request.  Note that the request is sent
                   3425: #  in clear, but the reply is encrypted.  This is a small covert channel:
                   3426: #  information about the sensitive keys is given to the snooper.  Just not
                   3427: #  information about the values of the sensitive key.  Hmm if I wanted to
                   3428: #  know these I'd snoop for the egets. Get the profile item names from them
                   3429: #  and then issue a get for them since there's no enforcement of the
                   3430: #  requirement of an encrypted get for particular profile items.  If I
                   3431: #  were re-doing this, I'd force the request to be encrypted as well as the
                   3432: #  reply.  I'd also just enforce encrypted transactions for all gets since
                   3433: #  that would prevent any covert channel snooping.
                   3434: #
                   3435: #  Parameters:
                   3436: #     $cmd               - Command keyword of request (eget).
1.536     raeburn  3437: #     $tail              - Tail of the command.  See GetProfileEntry
                   3438: #                          for more information about this.
1.231     foxr     3439: #     $client            - File open on the client.
                   3440: #  Returns:
                   3441: #     1      - Continue processing
                   3442: #     0      - server should exit.
                   3443: sub get_profile_entry_encrypted {
                   3444:     my ($cmd, $tail, $client) = @_;
                   3445: 
                   3446:     my $userinput = "$cmd:$tail";
                   3447:    
1.339     albertel 3448:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
1.231     foxr     3449:     chomp($what);
1.255     foxr     3450:     my $qresult = read_profile($udom, $uname, $namespace, $what);
                   3451:     my ($first) = split(/:/, $qresult);
                   3452:     if($first ne "error") {
                   3453: 	
                   3454: 	if ($cipher) {
                   3455: 	    my $cmdlength=length($qresult);
                   3456: 	    $qresult.="         ";
                   3457: 	    my $encqresult='';
                   3458: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   3459: 		$encqresult.= unpack("H16", 
                   3460: 				     $cipher->encrypt(substr($qresult,
                   3461: 							     $encidx,
                   3462: 							     8)));
                   3463: 	    }
                   3464: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   3465: 	} else {
1.231     foxr     3466: 		&Failure( $client, "error:no_key\n", $userinput);
                   3467: 	    }
                   3468:     } else {
1.255     foxr     3469: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
                   3470: 
1.231     foxr     3471:     }
                   3472:     
                   3473:     return 1;
                   3474: }
1.255     foxr     3475: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263     albertel 3476: 
1.231     foxr     3477: #
                   3478: #   Deletes a key in a user profile database.
                   3479: #   
                   3480: #   Parameters:
                   3481: #       $cmd                  - Command keyword (del).
                   3482: #       $tail                 - Command tail.  IN this case a colon
                   3483: #                               separated list containing:
                   3484: #                               The domain and user that identifies uniquely
                   3485: #                               the identity of the user.
                   3486: #                               The profile namespace (name of the profile
                   3487: #                               database file).
                   3488: #                               & separated list of keywords to delete.
                   3489: #       $client              - File open on client socket.
                   3490: # Returns:
                   3491: #     1   - Continue processing
                   3492: #     0   - Exit server.
                   3493: #
                   3494: #
                   3495: sub delete_profile_entry {
                   3496:     my ($cmd, $tail, $client) = @_;
                   3497: 
                   3498:     my $userinput = "cmd:$tail";
                   3499: 
                   3500:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3501:     chomp($what);
                   3502:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3503: 				 &GDBM_WRCREAT(),
                   3504: 				 "D",$what);
                   3505:     if ($hashref) {
                   3506:         my @keys=split(/\&/,$what);
                   3507: 	foreach my $key (@keys) {
                   3508: 	    delete($hashref->{$key});
                   3509: 	}
1.315     albertel 3510: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3511: 	    &Reply($client, "ok\n", $userinput);
                   3512: 	} else {
                   3513: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3514: 		    "while attempting del\n", $userinput);
                   3515: 	}
                   3516:     } else {
                   3517: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3518: 		 "while attempting del\n", $userinput);
                   3519:     }
                   3520:     return 1;
                   3521: }
                   3522: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263     albertel 3523: 
1.231     foxr     3524: #
                   3525: #  List the set of keys that are defined in a profile database file.
                   3526: #  A successful reply from this will contain an & separated list of
                   3527: #  the keys. 
                   3528: # Parameters:
                   3529: #     $cmd              - Command request (keys).
                   3530: #     $tail             - Remainder of the request, a colon separated
                   3531: #                         list containing domain/user that identifies the
                   3532: #                         user being queried, and the database namespace
                   3533: #                         (database filename essentially).
                   3534: #     $client           - File open on the client.
                   3535: #  Returns:
                   3536: #    1    - Continue processing.
                   3537: #    0    - Exit the server.
                   3538: #
                   3539: sub get_profile_keys {
                   3540:     my ($cmd, $tail, $client) = @_;
                   3541: 
                   3542:     my $userinput = "$cmd:$tail";
                   3543: 
                   3544:     my ($udom,$uname,$namespace)=split(/:/,$tail);
                   3545:     my $qresult='';
                   3546:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3547: 				  &GDBM_READER());
                   3548:     if ($hashref) {
                   3549: 	foreach my $key (keys %$hashref) {
                   3550: 	    $qresult.="$key&";
                   3551: 	}
1.315     albertel 3552: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3553: 	    $qresult=~s/\&$//;
1.387     albertel 3554: 	    &Reply($client, \$qresult, $userinput);
1.231     foxr     3555: 	} else {
                   3556: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3557: 		    "while attempting keys\n", $userinput);
                   3558: 	}
                   3559:     } else {
                   3560: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3561: 		 "while attempting keys\n", $userinput);
                   3562:     }
                   3563:    
                   3564:     return 1;
                   3565: }
                   3566: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
                   3567: 
                   3568: #
                   3569: #   Dump the contents of a user profile database.
                   3570: #   Note that this constitutes a very large covert channel too since
                   3571: #   the dump will return sensitive information that is not encrypted.
                   3572: #   The naive security assumption is that the session negotiation ensures
                   3573: #   our client is trusted and I don't believe that's assured at present.
                   3574: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
                   3575: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
                   3576: # 
                   3577: #  Parameters:
                   3578: #     $cmd           - The command request keyword (currentdump).
                   3579: #     $tail          - Remainder of the request, consisting of a colon
                   3580: #                      separated list that has the domain/username and
                   3581: #                      the namespace to dump (database file).
                   3582: #     $client        - file open on the remote client.
                   3583: # Returns:
                   3584: #     1    - Continue processing.
                   3585: #     0    - Exit the server.
                   3586: #
                   3587: sub dump_profile_database {
                   3588:     my ($cmd, $tail, $client) = @_;
                   3589: 
1.494     droeschl 3590:     my $res = LONCAPA::Lond::dump_profile_database($tail);
                   3591: 
                   3592:     if ($res =~ /^error:/) {
                   3593:         Failure($client, \$res, "$cmd:$tail");
                   3594:     } else {
                   3595:         Reply($client, \$res, "$cmd:$tail");
                   3596:     }
                   3597: 
                   3598:     return 1;  
                   3599: 
                   3600:     #TODO remove 
1.231     foxr     3601:     my $userinput = "$cmd:$tail";
                   3602:    
                   3603:     my ($udom,$uname,$namespace) = split(/:/,$tail);
                   3604:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3605: 				 &GDBM_READER());
                   3606:     if ($hashref) {
                   3607: 	# Structure of %data:
                   3608: 	# $data{$symb}->{$parameter}=$value;
                   3609: 	# $data{$symb}->{'v.'.$parameter}=$version;
                   3610: 	# since $parameter will be unescaped, we do not
                   3611:  	# have to worry about silly parameter names...
                   3612: 	
                   3613:         my $qresult='';
                   3614: 	my %data = ();                     # A hash of anonymous hashes..
                   3615: 	while (my ($key,$value) = each(%$hashref)) {
                   3616: 	    my ($v,$symb,$param) = split(/:/,$key);
                   3617: 	    next if ($v eq 'version' || $symb eq 'keys');
                   3618: 	    next if (exists($data{$symb}) && 
                   3619: 		     exists($data{$symb}->{$param}) &&
                   3620: 		     $data{$symb}->{'v.'.$param} > $v);
                   3621: 	    $data{$symb}->{$param}=$value;
                   3622: 	    $data{$symb}->{'v.'.$param}=$v;
                   3623: 	}
1.311     albertel 3624: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3625: 	    while (my ($symb,$param_hash) = each(%data)) {
                   3626: 		while(my ($param,$value) = each (%$param_hash)){
                   3627: 		    next if ($param =~ /^v\./);       # Ignore versions...
                   3628: 		    #
                   3629: 		    #   Just dump the symb=value pairs separated by &
                   3630: 		    #
                   3631: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
                   3632: 		}
                   3633: 	    }
                   3634: 	    chop($qresult);
1.387     albertel 3635: 	    &Reply($client , \$qresult, $userinput);
1.231     foxr     3636: 	} else {
                   3637: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3638: 		     "while attempting currentdump\n", $userinput);
                   3639: 	}
                   3640:     } else {
                   3641: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3642: 		"while attempting currentdump\n", $userinput);
                   3643:     }
                   3644: 
                   3645:     return 1;
                   3646: }
                   3647: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
                   3648: 
                   3649: #
                   3650: #   Dump a profile database with an optional regular expression
                   3651: #   to match against the keys.  In this dump, no effort is made
                   3652: #   to separate symb from version information. Presumably the
                   3653: #   databases that are dumped by this command are of a different
                   3654: #   structure.  Need to look at this and improve the documentation of
                   3655: #   both this and the currentdump handler.
                   3656: # Parameters:
                   3657: #    $cmd                     - The command keyword.
                   3658: #    $tail                    - All of the characters after the $cmd:
                   3659: #                               These are expected to be a colon
                   3660: #                               separated list containing:
                   3661: #                               domain/user - identifying the user.
                   3662: #                               namespace   - identifying the database.
                   3663: #                               regexp      - optional regular expression
                   3664: #                                             that is matched against
                   3665: #                                             database keywords to do
                   3666: #                                             selective dumps.
1.488     raeburn  3667: #                               range       - optional range of entries
                   3668: #                                             e.g., 10-20 would return the
                   3669: #                                             10th to 19th items, etc.  
1.231     foxr     3670: #   $client                   - Channel open on the client.
                   3671: # Returns:
                   3672: #    1    - Continue processing.
                   3673: # Side effects:
                   3674: #    response is written to $client.
                   3675: #
                   3676: sub dump_with_regexp {
                   3677:     my ($cmd, $tail, $client) = @_;
                   3678: 
1.494     droeschl 3679:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
1.490     droeschl 3680:     
                   3681:     if ($res =~ /^error:/) {
                   3682:         Failure($client, \$res, "$cmd:$tail");
                   3683:     } else {
                   3684:         Reply($client, \$res, "$cmd:$tail");
                   3685:     }
1.231     foxr     3686: 
                   3687:     return 1;
                   3688: }
                   3689: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
                   3690: 
                   3691: #  Store a set of key=value pairs associated with a versioned name.
                   3692: #
                   3693: #  Parameters:
                   3694: #    $cmd                - Request command keyword.
                   3695: #    $tail               - Tail of the request.  This is a colon
                   3696: #                          separated list containing:
                   3697: #                          domain/user - User and authentication domain.
                   3698: #                          namespace   - Name of the database being modified
                   3699: #                          rid         - Resource keyword to modify.
                   3700: #                          what        - new value associated with rid.
1.512     raeburn  3701: #                          laststore   - (optional) version=timestamp
                   3702: #                                        for most recent transaction for rid
                   3703: #                                        in namespace, when cstore was called
1.231     foxr     3704: #
                   3705: #    $client             - Socket open on the client.
                   3706: #
                   3707: #
                   3708: #  Returns:
                   3709: #      1 (keep on processing).
                   3710: #  Side-Effects:
                   3711: #    Writes to the client
1.512     raeburn  3712: #    Successful storage will cause either 'ok', or, if $laststore was included
                   3713: #    in the tail of the request, and the version number for the last transaction
                   3714: #    is larger than the version in $laststore, delay:$numtrans , where $numtrans
                   3715: #    is the number of store evevnts recorded for rid in namespace since
                   3716: #    lonnet::store() was called by the client.
                   3717: #
1.231     foxr     3718: sub store_handler {
                   3719:     my ($cmd, $tail, $client) = @_;
                   3720:  
                   3721:     my $userinput = "$cmd:$tail";
1.512     raeburn  3722:     chomp($tail);
                   3723:     my ($udom,$uname,$namespace,$rid,$what,$laststore) =split(/:/,$tail);
1.231     foxr     3724:     if ($namespace ne 'roles') {
                   3725: 
                   3726: 	my @pairs=split(/\&/,$what);
                   3727: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
1.268     albertel 3728: 				       &GDBM_WRCREAT(), "S",
1.231     foxr     3729: 				       "$rid:$what");
                   3730: 	if ($hashref) {
                   3731: 	    my $now = time;
1.512     raeburn  3732:             my $numtrans;
                   3733:             if ($laststore) {
                   3734:                 my ($previousversion,$previoustime) = split(/\=/,$laststore);
                   3735:                 my ($lastversion,$lasttime) = (0,0);
                   3736:                 $lastversion = $hashref->{"version:$rid"};
                   3737:                 if ($lastversion) {
                   3738:                     $lasttime = $hashref->{"$lastversion:$rid:timestamp"};
                   3739:                 }
                   3740:                 if (($previousversion) && ($previousversion !~ /\D/)) {
                   3741:                     if (($lastversion > $previousversion) && ($lasttime >= $previoustime)) {
                   3742:                         $numtrans = $lastversion - $previousversion;
                   3743:                     }
                   3744:                 } elsif ($lastversion) {
                   3745:                     $numtrans = $lastversion;
                   3746:                 }
                   3747:                 if ($numtrans) {
                   3748:                     $numtrans =~ s/D//g;
                   3749:                 }
                   3750:             }
1.231     foxr     3751: 	    $hashref->{"version:$rid"}++;
                   3752: 	    my $version=$hashref->{"version:$rid"};
                   3753: 	    my $allkeys=''; 
                   3754: 	    foreach my $pair (@pairs) {
                   3755: 		my ($key,$value)=split(/=/,$pair);
                   3756: 		$allkeys.=$key.':';
                   3757: 		$hashref->{"$version:$rid:$key"}=$value;
                   3758: 	    }
                   3759: 	    $hashref->{"$version:$rid:timestamp"}=$now;
                   3760: 	    $allkeys.='timestamp';
                   3761: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
1.311     albertel 3762: 	    if (&untie_user_hash($hashref)) {
1.512     raeburn  3763:                 my $msg = 'ok';
                   3764:                 if ($numtrans) {
                   3765:                     $msg = 'delay:'.$numtrans;
                   3766:                 }
                   3767: 		&Reply($client, "$msg\n", $userinput);
1.231     foxr     3768: 	    } else {
                   3769: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3770: 			"while attempting store\n", $userinput);
                   3771: 	    }
                   3772: 	} else {
                   3773: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3774: 		     "while attempting store\n", $userinput);
                   3775: 	}
                   3776:     } else {
                   3777: 	&Failure($client, "refused\n", $userinput);
                   3778:     }
                   3779: 
                   3780:     return 1;
                   3781: }
                   3782: &register_handler("store", \&store_handler, 0, 1, 0);
1.263     albertel 3783: 
1.323     albertel 3784: #  Modify a set of key=value pairs associated with a versioned name.
                   3785: #
                   3786: #  Parameters:
                   3787: #    $cmd                - Request command keyword.
                   3788: #    $tail               - Tail of the request.  This is a colon
                   3789: #                          separated list containing:
                   3790: #                          domain/user - User and authentication domain.
                   3791: #                          namespace   - Name of the database being modified
                   3792: #                          rid         - Resource keyword to modify.
                   3793: #                          v           - Version item to modify
                   3794: #                          what        - new value associated with rid.
                   3795: #
                   3796: #    $client             - Socket open on the client.
                   3797: #
                   3798: #
                   3799: #  Returns:
                   3800: #      1 (keep on processing).
                   3801: #  Side-Effects:
                   3802: #    Writes to the client
                   3803: sub putstore_handler {
                   3804:     my ($cmd, $tail, $client) = @_;
                   3805:  
                   3806:     my $userinput = "$cmd:$tail";
                   3807: 
                   3808:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
                   3809:     if ($namespace ne 'roles') {
                   3810: 
                   3811: 	chomp($what);
                   3812: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
                   3813: 				       &GDBM_WRCREAT(), "M",
                   3814: 				       "$rid:$v:$what");
                   3815: 	if ($hashref) {
                   3816: 	    my $now = time;
                   3817: 	    my %data = &hash_extract($what);
                   3818: 	    my @allkeys;
                   3819: 	    while (my($key,$value) = each(%data)) {
                   3820: 		push(@allkeys,$key);
                   3821: 		$hashref->{"$v:$rid:$key"} = $value;
                   3822: 	    }
                   3823: 	    my $allkeys = join(':',@allkeys);
                   3824: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
                   3825: 
                   3826: 	    if (&untie_user_hash($hashref)) {
                   3827: 		&Reply($client, "ok\n", $userinput);
                   3828: 	    } else {
                   3829: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3830: 			"while attempting store\n", $userinput);
                   3831: 	    }
                   3832: 	} else {
                   3833: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3834: 		     "while attempting store\n", $userinput);
                   3835: 	}
                   3836:     } else {
                   3837: 	&Failure($client, "refused\n", $userinput);
                   3838:     }
                   3839: 
                   3840:     return 1;
                   3841: }
                   3842: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
                   3843: 
                   3844: sub hash_extract {
                   3845:     my ($str)=@_;
                   3846:     my %hash;
                   3847:     foreach my $pair (split(/\&/,$str)) {
                   3848: 	my ($key,$value)=split(/=/,$pair);
                   3849: 	$hash{$key}=$value;
                   3850:     }
                   3851:     return (%hash);
                   3852: }
                   3853: sub hash_to_str {
                   3854:     my ($hash_ref)=@_;
                   3855:     my $str;
                   3856:     foreach my $key (keys(%$hash_ref)) {
                   3857: 	$str.=$key.'='.$hash_ref->{$key}.'&';
                   3858:     }
                   3859:     $str=~s/\&$//;
                   3860:     return $str;
                   3861: }
                   3862: 
1.231     foxr     3863: #
                   3864: #  Dump out all versions of a resource that has key=value pairs associated
                   3865: # with it for each version.  These resources are built up via the store
                   3866: # command.
                   3867: #
                   3868: #  Parameters:
                   3869: #     $cmd               - Command keyword.
                   3870: #     $tail              - Remainder of the request which consists of:
                   3871: #                          domain/user   - User and auth. domain.
                   3872: #                          namespace     - name of resource database.
                   3873: #                          rid           - Resource id.
                   3874: #    $client             - socket open on the client.
                   3875: #
                   3876: # Returns:
                   3877: #      1  indicating the caller should not yet exit.
                   3878: # Side-effects:
                   3879: #   Writes a reply to the client.
                   3880: #   The reply is a string of the following shape:
                   3881: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
                   3882: #    Where the 1 above represents version 1.
                   3883: #    this continues for all pairs of keys in all versions.
                   3884: #
                   3885: #
                   3886: #    
                   3887: #
                   3888: sub restore_handler {
                   3889:     my ($cmd, $tail, $client) = @_;
                   3890: 
                   3891:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
1.351     banghart 3892:     my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
1.352     albertel 3893:     $namespace=~s/\//\_/g;
1.350     albertel 3894:     $namespace = &LONCAPA::clean_username($namespace);
1.349     albertel 3895: 
1.231     foxr     3896:     chomp($rid);
                   3897:     my $qresult='';
1.309     albertel 3898:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
                   3899:     if ($hashref) {
                   3900: 	my $version=$hashref->{"version:$rid"};
1.231     foxr     3901: 	$qresult.="version=$version&";
                   3902: 	my $scope;
                   3903: 	for ($scope=1;$scope<=$version;$scope++) {
1.309     albertel 3904: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
1.231     foxr     3905: 	    my @keys=split(/:/,$vkeys);
                   3906: 	    my $key;
                   3907: 	    $qresult.="$scope:keys=$vkeys&";
                   3908: 	    foreach $key (@keys) {
1.309     albertel 3909: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
1.231     foxr     3910: 	    }                                  
                   3911: 	}
1.311     albertel 3912: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3913: 	    $qresult=~s/\&$//;
1.387     albertel 3914: 	    &Reply( $client, \$qresult, $userinput);
1.231     foxr     3915: 	} else {
                   3916: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3917: 		    "while attempting restore\n", $userinput);
                   3918: 	}
                   3919:     } else {
                   3920: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3921: 		"while attempting restore\n", $userinput);
                   3922:     }
                   3923:   
                   3924:     return 1;
                   3925: 
                   3926: 
                   3927: }
                   3928: &register_handler("restore", \&restore_handler, 0,1,0);
1.234     foxr     3929: 
                   3930: #
1.324     raeburn  3931: #   Add a chat message to a synchronous discussion board.
1.234     foxr     3932: #
                   3933: # Parameters:
                   3934: #    $cmd                - Request keyword.
                   3935: #    $tail               - Tail of the command. A colon separated list
                   3936: #                          containing:
                   3937: #                          cdom    - Domain on which the chat board lives
1.324     raeburn  3938: #                          cnum    - Course containing the chat board.
                   3939: #                          newpost - Body of the posting.
                   3940: #                          group   - Optional group, if chat board is only 
                   3941: #                                    accessible in a group within the course 
1.234     foxr     3942: #   $client              - Socket open on the client.
                   3943: # Returns:
                   3944: #   1    - Indicating caller should keep on processing.
                   3945: #
                   3946: # Side-effects:
                   3947: #   writes a reply to the client.
                   3948: #
                   3949: #
                   3950: sub send_chat_handler {
                   3951:     my ($cmd, $tail, $client) = @_;
                   3952: 
                   3953:     
                   3954:     my $userinput = "$cmd:$tail";
                   3955: 
1.324     raeburn  3956:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
                   3957:     &chat_add($cdom,$cnum,$newpost,$group);
1.234     foxr     3958:     &Reply($client, "ok\n", $userinput);
                   3959: 
                   3960:     return 1;
                   3961: }
                   3962: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263     albertel 3963: 
1.234     foxr     3964: #
1.324     raeburn  3965: #   Retrieve the set of chat messages from a discussion board.
1.234     foxr     3966: #
                   3967: #  Parameters:
                   3968: #    $cmd             - Command keyword that initiated the request.
                   3969: #    $tail            - Remainder of the request after the command
                   3970: #                       keyword.  In this case a colon separated list of
                   3971: #                       chat domain    - Which discussion board.
                   3972: #                       chat id        - Discussion thread(?)
                   3973: #                       domain/user    - Authentication domain and username
                   3974: #                                        of the requesting person.
1.324     raeburn  3975: #                       group          - Optional course group containing
                   3976: #                                        the board.      
1.234     foxr     3977: #   $client           - Socket open on the client program.
                   3978: # Returns:
                   3979: #    1     - continue processing
                   3980: # Side effects:
                   3981: #    Response is written to the client.
                   3982: #
                   3983: sub retrieve_chat_handler {
                   3984:     my ($cmd, $tail, $client) = @_;
                   3985: 
                   3986: 
                   3987:     my $userinput = "$cmd:$tail";
                   3988: 
1.324     raeburn  3989:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
1.234     foxr     3990:     my $reply='';
1.324     raeburn  3991:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
1.234     foxr     3992: 	$reply.=&escape($_).':';
                   3993:     }
                   3994:     $reply=~s/\:$//;
1.387     albertel 3995:     &Reply($client, \$reply, $userinput);
1.234     foxr     3996: 
                   3997: 
                   3998:     return 1;
                   3999: }
                   4000: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
                   4001: 
                   4002: #
                   4003: #  Initiate a query of an sql database.  SQL query repsonses get put in
                   4004: #  a file for later retrieval.  This prevents sql query results from
                   4005: #  bottlenecking the system.  Note that with loncnew, perhaps this is
                   4006: #  less of an issue since multiple outstanding requests can be concurrently
                   4007: #  serviced.
                   4008: #
                   4009: #  Parameters:
1.535     raeburn  4010: #     $cmd       - Command keyword that initiated the request.
1.234     foxr     4011: #     $tail      - Remainder of the command after the keyword.
                   4012: #                  For this function, this consists of a query and
                   4013: #                  3 arguments that are self-documentingly labelled
                   4014: #                  in the original arg1, arg2, arg3.
                   4015: #     $client    - Socket open on the client.
                   4016: # Return:
                   4017: #    1   - Indicating processing should continue.
                   4018: # Side-effects:
                   4019: #    a reply is written to $client.
                   4020: #
                   4021: sub send_query_handler {
                   4022:     my ($cmd, $tail, $client) = @_;
                   4023: 
                   4024:     my $userinput = "$cmd:$tail";
                   4025: 
                   4026:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
                   4027:     $query=~s/\n*$//g;
1.534     raeburn  4028:     if (($query eq 'usersearch') || ($query eq 'instdirsearch')) {
                   4029:         my $usersearchconf = &get_usersearch_config($currentdomainid,'directorysrch');
                   4030:         my $earlyout;
                   4031:         if (ref($usersearchconf) eq 'HASH') {
                   4032:             if ($currentdomainid eq $clienthomedom) {
                   4033:                 if ($query eq 'usersearch') {
                   4034:                     if ($usersearchconf->{'lcavailable'} eq '0') {
                   4035:                         $earlyout = 1;
                   4036:                     }
                   4037:                 } else {
                   4038:                     if ($usersearchconf->{'available'} eq '0') {
                   4039:                         $earlyout = 1;
                   4040:                     }
                   4041:                 }
                   4042:             } else {
                   4043:                 if ($query eq 'usersearch') {
                   4044:                     if ($usersearchconf->{'lclocalonly'}) {
                   4045:                         $earlyout = 1;
                   4046:                     }
                   4047:                 } else {
                   4048:                     if ($usersearchconf->{'localonly'}) {
                   4049:                         $earlyout = 1;
                   4050:                     }
                   4051:                 }
                   4052:             }
                   4053:         }
                   4054:         if ($earlyout) {
                   4055:             &Reply($client, "query_not_authorized\n");
                   4056:             return 1;
                   4057:         }
                   4058:     }
1.234     foxr     4059:     &Reply($client, "". &sql_reply("$clientname\&$query".
                   4060: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
                   4061: 	  $userinput);
                   4062:     
                   4063:     return 1;
                   4064: }
                   4065: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
                   4066: 
                   4067: #
                   4068: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
                   4069: #   The query is submitted via a "querysend" transaction.
                   4070: #   There it is passed on to the lonsql daemon, queued and issued to
                   4071: #   mysql.
                   4072: #     This transaction is invoked when the sql transaction is complete
                   4073: #   it stores the query results in flie and indicates query completion.
                   4074: #   presumably local software then fetches this response... I'm guessing
                   4075: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
                   4076: #   lonsql on completion of the query interacts with the lond of our
                   4077: #   client to do a query reply storing two files:
                   4078: #    - id     - The results of the query.
                   4079: #    - id.end - Indicating the transaction completed. 
                   4080: #    NOTE: id is a unique id assigned to the query and querysend time.
                   4081: # Parameters:
                   4082: #    $cmd        - Command keyword that initiated this request.
                   4083: #    $tail       - Remainder of the tail.  In this case that's a colon
                   4084: #                  separated list containing the query Id and the 
                   4085: #                  results of the query.
                   4086: #    $client     - Socket open on the client.
                   4087: # Return:
                   4088: #    1           - Indicating that we should continue processing.
                   4089: # Side effects:
                   4090: #    ok written to the client.
                   4091: #
                   4092: sub reply_query_handler {
                   4093:     my ($cmd, $tail, $client) = @_;
                   4094: 
                   4095: 
                   4096:     my $userinput = "$cmd:$tail";
                   4097: 
1.339     albertel 4098:     my ($id,$reply)=split(/:/,$tail); 
1.234     foxr     4099:     my $store;
                   4100:     my $execdir=$perlvar{'lonDaemons'};
                   4101:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
                   4102: 	$reply=~s/\&/\n/g;
                   4103: 	print $store $reply;
                   4104: 	close $store;
                   4105: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
                   4106: 	print $store2 "done\n";
                   4107: 	close $store2;
                   4108: 	&Reply($client, "ok\n", $userinput);
                   4109:     } else {
                   4110: 	&Failure($client, "error: ".($!+0)
                   4111: 		." IO::File->new Failed ".
                   4112: 		"while attempting queryreply\n", $userinput);
                   4113:     }
                   4114:  
                   4115: 
                   4116:     return 1;
                   4117: }
                   4118: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
                   4119: 
                   4120: #
                   4121: #  Process the courseidput request.  Not quite sure what this means
                   4122: #  at the system level sense.  It appears a gdbm file in the 
                   4123: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
                   4124: #  a set of entries made in that database.
                   4125: #
                   4126: # Parameters:
                   4127: #   $cmd      - The command keyword that initiated this request.
                   4128: #   $tail     - Tail of the command.  In this case consists of a colon
                   4129: #               separated list contaning the domain to apply this to and
                   4130: #               an ampersand separated list of keyword=value pairs.
1.272     raeburn  4131: #               Each value is a colon separated list that includes:  
                   4132: #               description, institutional code and course owner.
                   4133: #               For backward compatibility with versions included
                   4134: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
                   4135: #               code and/or course owner are preserved from the existing 
                   4136: #               record when writing a new record in response to 1.1 or 
                   4137: #               1.2 implementations of lonnet::flushcourselogs().   
                   4138: #                      
1.234     foxr     4139: #   $client   - Socket open on the client.
                   4140: # Returns:
                   4141: #   1    - indicating that processing should continue
                   4142: #
                   4143: # Side effects:
                   4144: #   reply is written to the client.
                   4145: #
                   4146: sub put_course_id_handler {
                   4147:     my ($cmd, $tail, $client) = @_;
                   4148: 
                   4149: 
                   4150:     my $userinput = "$cmd:$tail";
                   4151: 
1.266     raeburn  4152:     my ($udom, $what) = split(/:/, $tail,2);
1.234     foxr     4153:     chomp($what);
                   4154:     my $now=time;
                   4155:     my @pairs=split(/\&/,$what);
                   4156: 
                   4157:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4158:     if ($hashref) {
                   4159: 	foreach my $pair (@pairs) {
1.271     raeburn  4160:             my ($key,$courseinfo) = split(/=/,$pair,2);
                   4161:             $courseinfo =~ s/=/:/g;
1.384     raeburn  4162:             if (defined($hashref->{$key})) {
                   4163:                 my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
                   4164:                 if (ref($value) eq 'HASH') {
                   4165:                     my @items = ('description','inst_code','owner','type');
                   4166:                     my @new_items = split(/:/,$courseinfo,-1);
                   4167:                     my %storehash; 
                   4168:                     for (my $i=0; $i<@new_items; $i++) {
1.391     raeburn  4169:                         $storehash{$items[$i]} = &unescape($new_items[$i]);
1.384     raeburn  4170:                     }
                   4171:                     $hashref->{$key} = 
                   4172:                         &Apache::lonnet::freeze_escape(\%storehash);
                   4173:                     my $unesc_key = &unescape($key);
                   4174:                     $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4175:                     next;
1.383     raeburn  4176:                 }
1.384     raeburn  4177:             }
                   4178:             my @current_items = split(/:/,$hashref->{$key},-1);
                   4179:             shift(@current_items); # remove description
                   4180:             pop(@current_items);   # remove last access
                   4181:             my $numcurrent = scalar(@current_items);
                   4182:             if ($numcurrent > 3) {
                   4183:                 $numcurrent = 3;
                   4184:             }
                   4185:             my @new_items = split(/:/,$courseinfo,-1);
                   4186:             my $numnew = scalar(@new_items);
                   4187:             if ($numcurrent > 0) {
                   4188:                 if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2 
                   4189:                     for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
                   4190:                         $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
1.333     raeburn  4191:                     }
1.272     raeburn  4192:                 }
                   4193:             }
1.384     raeburn  4194:             $hashref->{$key}=$courseinfo.':'.$now;
1.234     foxr     4195: 	}
1.311     albertel 4196: 	if (&untie_domain_hash($hashref)) {
1.253     foxr     4197: 	    &Reply( $client, "ok\n", $userinput);
1.234     foxr     4198: 	} else {
1.253     foxr     4199: 	    &Failure($client, "error: ".($!+0)
1.234     foxr     4200: 		     ." untie(GDBM) Failed ".
                   4201: 		     "while attempting courseidput\n", $userinput);
                   4202: 	}
                   4203:     } else {
1.253     foxr     4204: 	&Failure($client, "error: ".($!+0)
1.234     foxr     4205: 		 ." tie(GDBM) Failed ".
                   4206: 		 "while attempting courseidput\n", $userinput);
                   4207:     }
                   4208: 
                   4209:     return 1;
                   4210: }
                   4211: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
                   4212: 
1.383     raeburn  4213: sub put_course_id_hash_handler {
                   4214:     my ($cmd, $tail, $client) = @_;
                   4215:     my $userinput = "$cmd:$tail";
1.384     raeburn  4216:     my ($udom,$mode,$what) = split(/:/, $tail,3);
1.383     raeburn  4217:     chomp($what);
                   4218:     my $now=time;
                   4219:     my @pairs=split(/\&/,$what);
1.384     raeburn  4220:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
1.383     raeburn  4221:     if ($hashref) {
                   4222:         foreach my $pair (@pairs) {
                   4223:             my ($key,$value)=split(/=/,$pair);
1.384     raeburn  4224:             my $unesc_key = &unescape($key);
                   4225:             if ($mode ne 'timeonly') {
                   4226:                 if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
                   4227:                     my $curritems = &Apache::lonnet::thaw_unescape($key); 
                   4228:                     if (ref($curritems) ne 'HASH') {
                   4229:                         my @current_items = split(/:/,$hashref->{$key},-1);
                   4230:                         my $lasttime = pop(@current_items);
                   4231:                         $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
                   4232:                     } else {
                   4233:                         $hashref->{&escape('lasttime:'.$unesc_key)} = '';
                   4234:                     }
                   4235:                 } 
                   4236:                 $hashref->{$key} = $value;
                   4237:             }
                   4238:             if ($mode ne 'notime') {
                   4239:                 $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4240:             }
1.383     raeburn  4241:         }
                   4242:         if (&untie_domain_hash($hashref)) {
                   4243:             &Reply($client, "ok\n", $userinput);
                   4244:         } else {
                   4245:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4246:                      "while attempting courseidputhash\n", $userinput);
                   4247:         }
                   4248:     } else {
                   4249:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4250:                   "while attempting courseidputhash\n", $userinput);
                   4251:     }
                   4252:     return 1;
                   4253: }
                   4254: &register_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
                   4255: 
1.234     foxr     4256: #  Retrieves the value of a course id resource keyword pattern
                   4257: #  defined since a starting date.  Both the starting date and the
                   4258: #  keyword pattern are optional.  If the starting date is not supplied it
                   4259: #  is treated as the beginning of time.  If the pattern is not found,
                   4260: #  it is treatred as "." matching everything.
                   4261: #
                   4262: #  Parameters:
                   4263: #     $cmd     - Command keyword that resulted in us being dispatched.
                   4264: #     $tail    - The remainder of the command that, in this case, consists
                   4265: #                of a colon separated list of:
                   4266: #                 domain   - The domain in which the course database is 
                   4267: #                            defined.
                   4268: #                 since    - Optional parameter describing the minimum
                   4269: #                            time of definition(?) of the resources that
                   4270: #                            will match the dump.
                   4271: #                 description - regular expression that is used to filter
                   4272: #                            the dump.  Only keywords matching this regexp
                   4273: #                            will be used.
1.272     raeburn  4274: #                 institutional code - optional supplied code to filter 
                   4275: #                            the dump. Only courses with an institutional code 
                   4276: #                            that match the supplied code will be returned.
1.336     raeburn  4277: #                 owner    - optional supplied username and domain of owner to
                   4278: #                            filter the dump.  Only courses for which the course
                   4279: #                            owner matches the supplied username and/or domain
                   4280: #                            will be returned. Pre-2.2.0 legacy entries from 
                   4281: #                            nohist_courseiddump will only contain usernames.
1.384     raeburn  4282: #                 type     - optional parameter for selection 
1.418     raeburn  4283: #                 regexp_ok - if 1 or -1 allow the supplied institutional code
                   4284: #                            filter to behave as a regular expression:
                   4285: #	                      1 will not exclude the course if the instcode matches the RE 
                   4286: #                            -1 will exclude the course if the instcode matches the RE
1.384     raeburn  4287: #                 rtn_as_hash - whether to return the information available for
                   4288: #                            each matched item as a frozen hash of all 
                   4289: #                            key, value pairs in the item's hash, or as a 
                   4290: #                            colon-separated list of (in order) description,
                   4291: #                            institutional code, and course owner.
1.404     raeburn  4292: #                 selfenrollonly - filter by courses allowing self-enrollment  
                   4293: #                                  now or in the future (selfenrollonly = 1).
                   4294: #                 catfilter - filter by course category, assigned to a course 
                   4295: #                             using manually defined categories (i.e., not
1.407     raeburn  4296: #                             self-cataloging based on on institutional code).   
1.404     raeburn  4297: #                 showhidden - include course in results even if course  
1.407     raeburn  4298: #                              was set to be excluded from course catalog (DC only).
1.404     raeburn  4299: #                 caller -  if set to 'coursecatalog', courses set to be hidden
                   4300: #                           from course catalog will be excluded from results (unless
                   4301: #                           overridden by "showhidden".
1.427     raeburn  4302: #                 cloner - escaped username:domain of course cloner (if picking course to
1.419     raeburn  4303: #                          clone).
                   4304: #                 cc_clone_list - escaped comma separated list of courses for which 
                   4305: #                                 course cloner has active CC role (and so can clone
                   4306: #                                 automatically).
1.427     raeburn  4307: #                 cloneonly - filter by courses for which cloner has rights to clone.
                   4308: #                 createdbefore - include courses for which creation date preceeded this date.
                   4309: #                 createdafter - include courses for which creation date followed this date.
                   4310: #                 creationcontext - include courses created in specified context 
1.404     raeburn  4311: #
1.445     raeburn  4312: #                 domcloner - flag to indicate if user can create CCs in course's domain.
1.505     raeburn  4313: #                             If so, ability to clone course is automatic.
                   4314: #                 hasuniquecode - filter by courses for which a six character unique code has 
                   4315: #                                 been set.
1.445     raeburn  4316: #
1.234     foxr     4317: #     $client  - The socket open on the client.
                   4318: # Returns:
                   4319: #    1     - Continue processing.
                   4320: # Side Effects:
                   4321: #   a reply is written to $client.
                   4322: sub dump_course_id_handler {
                   4323:     my ($cmd, $tail, $client) = @_;
1.494     droeschl 4324: 
                   4325:     my $res = LONCAPA::Lond::dump_course_id_handler($tail);
                   4326:     if ($res =~ /^error:/) {
                   4327:         Failure($client, \$res, "$cmd:$tail");
                   4328:     } else {
                   4329:         Reply($client, \$res, "$cmd:$tail");
                   4330:     }
                   4331: 
                   4332:     return 1;  
                   4333: 
                   4334:     #TODO remove
1.234     foxr     4335:     my $userinput = "$cmd:$tail";
                   4336: 
1.333     raeburn  4337:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
1.404     raeburn  4338:         $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
1.427     raeburn  4339:         $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
1.505     raeburn  4340:         $creationcontext,$domcloner,$hasuniquecode) =split(/:/,$tail);
1.397     raeburn  4341:     my $now = time;
1.419     raeburn  4342:     my ($cloneruname,$clonerudom,%cc_clone);
1.234     foxr     4343:     if (defined($description)) {
                   4344: 	$description=&unescape($description);
                   4345:     } else {
                   4346: 	$description='.';
                   4347:     }
1.266     raeburn  4348:     if (defined($instcodefilter)) {
                   4349:         $instcodefilter=&unescape($instcodefilter);
                   4350:     } else {
                   4351:         $instcodefilter='.';
                   4352:     }
1.336     raeburn  4353:     my ($ownerunamefilter,$ownerdomfilter);
1.266     raeburn  4354:     if (defined($ownerfilter)) {
                   4355:         $ownerfilter=&unescape($ownerfilter);
1.336     raeburn  4356:         if ($ownerfilter ne '.' && defined($ownerfilter)) {
                   4357:             if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
                   4358:                  $ownerunamefilter = $1;
                   4359:                  $ownerdomfilter = $2;
                   4360:             } else {
                   4361:                 $ownerunamefilter = $ownerfilter;
                   4362:                 $ownerdomfilter = '';
                   4363:             }
                   4364:         }
1.266     raeburn  4365:     } else {
                   4366:         $ownerfilter='.';
                   4367:     }
1.336     raeburn  4368: 
1.282     raeburn  4369:     if (defined($coursefilter)) {
                   4370:         $coursefilter=&unescape($coursefilter);
                   4371:     } else {
                   4372:         $coursefilter='.';
                   4373:     }
1.333     raeburn  4374:     if (defined($typefilter)) {
                   4375:         $typefilter=&unescape($typefilter);
                   4376:     } else {
                   4377:         $typefilter='.';
                   4378:     }
1.344     raeburn  4379:     if (defined($regexp_ok)) {
                   4380:         $regexp_ok=&unescape($regexp_ok);
                   4381:     }
1.401     raeburn  4382:     if (defined($catfilter)) {
                   4383:         $catfilter=&unescape($catfilter);
                   4384:     }
1.419     raeburn  4385:     if (defined($cloner)) {
                   4386:         $cloner = &unescape($cloner);
                   4387:         ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/); 
                   4388:     }
                   4389:     if (defined($cc_clone_list)) {
                   4390:         $cc_clone_list = &unescape($cc_clone_list);
                   4391:         my @cc_cloners = split('&',$cc_clone_list);
                   4392:         foreach my $cid (@cc_cloners) {
                   4393:             my ($clonedom,$clonenum) = split(':',$cid);
                   4394:             next if ($clonedom ne $udom); 
                   4395:             $cc_clone{$clonedom.'_'.$clonenum} = 1;
                   4396:         } 
                   4397:     }
1.431     raeburn  4398:     if ($createdbefore ne '') {
1.427     raeburn  4399:         $createdbefore = &unescape($createdbefore);
                   4400:     } else {
                   4401:        $createdbefore = 0;
                   4402:     }
1.431     raeburn  4403:     if ($createdafter ne '') {
1.427     raeburn  4404:         $createdafter = &unescape($createdafter);
                   4405:     } else {
                   4406:         $createdafter = 0;
                   4407:     }
1.431     raeburn  4408:     if ($creationcontext ne '') {
1.427     raeburn  4409:         $creationcontext = &unescape($creationcontext);
                   4410:     } else {
                   4411:         $creationcontext = '.';
                   4412:     }
1.505     raeburn  4413:     unless ($hasuniquecode) {
                   4414:         $hasuniquecode = '.';
                   4415:     }
1.384     raeburn  4416:     my $unpack = 1;
1.485     raeburn  4417:     if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' && 
1.384     raeburn  4418:         $typefilter eq '.') {
                   4419:         $unpack = 0;
                   4420:     }
                   4421:     if (!defined($since)) { $since=0; }
1.234     foxr     4422:     my $qresult='';
                   4423:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4424:     if ($hashref) {
1.384     raeburn  4425: 	while (my ($key,$value) = each(%$hashref)) {
1.397     raeburn  4426:             my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
1.427     raeburn  4427:                 %unesc_val,$selfenroll_end,$selfenroll_types,$created,
                   4428:                 $context);
1.384     raeburn  4429:             $unesc_key = &unescape($key);
                   4430:             if ($unesc_key =~ /^lasttime:/) {
                   4431:                 next;
                   4432:             } else {
                   4433:                 $lasttime_key = &escape('lasttime:'.$unesc_key);
                   4434:             }
                   4435:             if ($hashref->{$lasttime_key} ne '') {
                   4436:                 $lasttime = $hashref->{$lasttime_key};
                   4437:                 next if ($lasttime<$since);
                   4438:             }
1.419     raeburn  4439:             my ($canclone,$valchange);
1.384     raeburn  4440:             my $items = &Apache::lonnet::thaw_unescape($value);
                   4441:             if (ref($items) eq 'HASH') {
1.429     raeburn  4442:                 if ($hashref->{$lasttime_key} eq '') {
1.430     raeburn  4443:                     next if ($since > 1);
1.429     raeburn  4444:                 }
1.384     raeburn  4445:                 $is_hash =  1;
1.445     raeburn  4446:                 if ($domcloner) {
                   4447:                     $canclone = 1;
                   4448:                 } elsif (defined($clonerudom)) {
1.419     raeburn  4449:                     if ($items->{'cloners'}) {
                   4450:                         my @cloneable = split(',',$items->{'cloners'});
                   4451:                         if (@cloneable) {
                   4452:                             if (grep(/^\*$/,@cloneable))  {
                   4453:                                 $canclone = 1;
                   4454:                             } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
                   4455:                                 $canclone = 1;
                   4456:                             } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
                   4457:                                 $canclone = 1;
                   4458:                             }
                   4459:                         }
                   4460:                         unless ($canclone) {
                   4461:                             if ($cloneruname ne '' && $clonerudom ne '') {
                   4462:                                 if ($cc_clone{$unesc_key}) {
                   4463:                                     $canclone = 1;
                   4464:                                     $items->{'cloners'} .= ','.$cloneruname.':'.
                   4465:                                                            $clonerudom;
                   4466:                                     $valchange = 1;
                   4467:                                 }
                   4468:                             }
                   4469:                         }
                   4470:                     } elsif (defined($cloneruname)) {
                   4471:                         if ($cc_clone{$unesc_key}) {
                   4472:                             $canclone = 1;
                   4473:                             $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4474:                             $valchange = 1;
                   4475:                         }
1.437     raeburn  4476:                         unless ($canclone) {
                   4477:                             if ($items->{'owner'} =~ /:/) {
                   4478:                                 if ($items->{'owner'} eq $cloner) {
                   4479:                                     $canclone = 1;
                   4480:                                 }
1.444     raeburn  4481:                             } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
1.437     raeburn  4482:                                 $canclone = 1;
                   4483:                             }
                   4484:                             if ($canclone) {
                   4485:                                 $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4486:                                 $valchange = 1;
                   4487:                             }
                   4488:                         }
1.419     raeburn  4489:                     }
                   4490:                 }
1.384     raeburn  4491:                 if ($unpack || !$rtn_as_hash) {
                   4492:                     $unesc_val{'descr'} = $items->{'description'};
                   4493:                     $unesc_val{'inst_code'} = $items->{'inst_code'};
                   4494:                     $unesc_val{'owner'} = $items->{'owner'};
                   4495:                     $unesc_val{'type'} = $items->{'type'};
1.419     raeburn  4496:                     $unesc_val{'cloners'} = $items->{'cloners'};
1.427     raeburn  4497:                     $unesc_val{'created'} = $items->{'created'};
                   4498:                     $unesc_val{'context'} = $items->{'context'};
1.404     raeburn  4499:                 }
                   4500:                 $selfenroll_types = $items->{'selfenroll_types'};
                   4501:                 $selfenroll_end = $items->{'selfenroll_end_date'};
1.427     raeburn  4502:                 $created = $items->{'created'};
                   4503:                 $context = $items->{'context'};
1.505     raeburn  4504:                 if ($hasuniquecode ne '.') {
                   4505:                     next unless ($items->{'uniquecode'});
                   4506:                 }
1.404     raeburn  4507:                 if ($selfenrollonly) {
                   4508:                     next if (!$selfenroll_types);
                   4509:                     if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
                   4510:                         next;
1.397     raeburn  4511:                     }
1.404     raeburn  4512:                 }
1.427     raeburn  4513:                 if ($creationcontext ne '.') {
                   4514:                     next if (($context ne '') && ($context ne $creationcontext));  
                   4515:                 }
                   4516:                 if ($createdbefore > 0) {
                   4517:                     next if (($created eq '') || ($created > $createdbefore));   
                   4518:                 }
                   4519:                 if ($createdafter > 0) {
                   4520:                     next if (($created eq '') || ($created <= $createdafter)); 
                   4521:                 }
1.404     raeburn  4522:                 if ($catfilter ne '') {
1.406     raeburn  4523:                     next if ($items->{'categories'} eq '');
                   4524:                     my @categories = split('&',$items->{'categories'}); 
1.407     raeburn  4525:                     next if (@categories == 0);
                   4526:                     my @subcats = split('&',$catfilter);
                   4527:                     my $matchcat = 0;
                   4528:                     foreach my $cat (@categories) {
                   4529:                         if (grep(/^\Q$cat\E$/,@subcats)) {
                   4530:                             $matchcat = 1;
                   4531:                             last;
                   4532:                         }
                   4533:                     }
                   4534:                     next if (!$matchcat);
1.404     raeburn  4535:                 }
                   4536:                 if ($caller eq 'coursecatalog') {
1.405     raeburn  4537:                     if ($items->{'hidefromcat'} eq 'yes') {
                   4538:                         next if !$showhidden;
1.401     raeburn  4539:                     }
1.384     raeburn  4540:                 }
1.383     raeburn  4541:             } else {
1.401     raeburn  4542:                 next if ($catfilter ne '');
1.419     raeburn  4543:                 next if ($selfenrollonly);
1.427     raeburn  4544:                 next if ($createdbefore || $createdafter);
                   4545:                 next if ($creationcontext ne '.');
1.419     raeburn  4546:                 if ((defined($clonerudom)) && (defined($cloneruname)))  {
                   4547:                     if ($cc_clone{$unesc_key}) {
                   4548:                         $canclone = 1;
                   4549:                         $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
                   4550:                     }
                   4551:                 }
1.384     raeburn  4552:                 $is_hash =  0;
1.388     raeburn  4553:                 my @courseitems = split(/:/,$value);
1.403     raeburn  4554:                 $lasttime = pop(@courseitems);
1.402     raeburn  4555:                 if ($hashref->{$lasttime_key} eq '') {
                   4556:                     next if ($lasttime<$since);
                   4557:                 }
1.384     raeburn  4558: 	        ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
1.383     raeburn  4559:             }
1.419     raeburn  4560:             if ($cloneonly) {
                   4561:                next unless ($canclone);
                   4562:             }
1.266     raeburn  4563:             my $match = 1;
1.384     raeburn  4564: 	    if ($description ne '.') {
                   4565:                 if (!$is_hash) {
                   4566:                     $unesc_val{'descr'} = &unescape($val{'descr'});
                   4567:                 }
                   4568:                 if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
1.266     raeburn  4569:                     $match = 0;
1.384     raeburn  4570:                 }
1.266     raeburn  4571:             }
1.384     raeburn  4572:             if ($instcodefilter ne '.') {
                   4573:                 if (!$is_hash) {
                   4574:                     $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
                   4575:                 }
1.418     raeburn  4576:                 if ($regexp_ok == 1) {
1.384     raeburn  4577:                     if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
1.344     raeburn  4578:                         $match = 0;
                   4579:                     }
1.418     raeburn  4580:                 } elsif ($regexp_ok == -1) {
                   4581:                     if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
                   4582:                         $match = 0;
                   4583:                     }
1.344     raeburn  4584:                 } else {
1.384     raeburn  4585:                     if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
1.344     raeburn  4586:                         $match = 0;
                   4587:                     }
1.266     raeburn  4588:                 }
1.234     foxr     4589: 	    }
1.384     raeburn  4590:             if ($ownerfilter ne '.') {
                   4591:                 if (!$is_hash) {
                   4592:                     $unesc_val{'owner'} = &unescape($val{'owner'});
                   4593:                 }
1.336     raeburn  4594:                 if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
1.384     raeburn  4595:                     if ($unesc_val{'owner'} =~ /:/) {
                   4596:                         if (eval{$unesc_val{'owner'} !~ 
                   4597:                              /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
1.336     raeburn  4598:                             $match = 0;
                   4599:                         } 
                   4600:                     } else {
1.384     raeburn  4601:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4602:                             $match = 0;
                   4603:                         }
                   4604:                     }
                   4605:                 } elsif ($ownerunamefilter ne '') {
1.384     raeburn  4606:                     if ($unesc_val{'owner'} =~ /:/) {
                   4607:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
1.336     raeburn  4608:                              $match = 0;
                   4609:                         }
                   4610:                     } else {
1.384     raeburn  4611:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4612:                             $match = 0;
                   4613:                         }
                   4614:                     }
                   4615:                 } elsif ($ownerdomfilter ne '') {
1.384     raeburn  4616:                     if ($unesc_val{'owner'} =~ /:/) {
                   4617:                         if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
1.336     raeburn  4618:                              $match = 0;
                   4619:                         }
                   4620:                     } else {
                   4621:                         if ($ownerdomfilter ne $udom) {
                   4622:                             $match = 0;
                   4623:                         }
                   4624:                     }
1.266     raeburn  4625:                 }
                   4626:             }
1.384     raeburn  4627:             if ($coursefilter ne '.') {
                   4628:                 if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
1.282     raeburn  4629:                     $match = 0;
                   4630:                 }
                   4631:             }
1.384     raeburn  4632:             if ($typefilter ne '.') {
                   4633:                 if (!$is_hash) {
                   4634:                     $unesc_val{'type'} = &unescape($val{'type'});
                   4635:                 }
                   4636:                 if ($unesc_val{'type'} eq '') {
1.333     raeburn  4637:                     if ($typefilter ne 'Course') {
                   4638:                         $match = 0;
                   4639:                     }
1.383     raeburn  4640:                 } else {
1.384     raeburn  4641:                     if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
1.333     raeburn  4642:                         $match = 0;
                   4643:                     }
                   4644:                 }
                   4645:             }
1.266     raeburn  4646:             if ($match == 1) {
1.384     raeburn  4647:                 if ($rtn_as_hash) {
                   4648:                     if ($is_hash) {
1.419     raeburn  4649:                         if ($valchange) {
                   4650:                             my $newvalue = &Apache::lonnet::freeze_escape($items);
                   4651:                             $qresult.=$key.'='.$newvalue.'&';
                   4652:                         } else {
                   4653:                             $qresult.=$key.'='.$value.'&';
                   4654:                         }
1.384     raeburn  4655:                     } else {
1.388     raeburn  4656:                         my %rtnhash = ( 'description' => &unescape($val{'descr'}),
                   4657:                                         'inst_code' => &unescape($val{'inst_code'}),
                   4658:                                         'owner'     => &unescape($val{'owner'}),
                   4659:                                         'type'      => &unescape($val{'type'}),
1.419     raeburn  4660:                                         'cloners'   => &unescape($val{'cloners'}),
1.384     raeburn  4661:                                       );
                   4662:                         my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
                   4663:                         $qresult.=$key.'='.$items.'&';
                   4664:                     }
1.383     raeburn  4665:                 } else {
1.384     raeburn  4666:                     if ($is_hash) {
                   4667:                         $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
                   4668:                                     &escape($unesc_val{'inst_code'}).':'.
                   4669:                                     &escape($unesc_val{'owner'}).'&';
                   4670:                     } else {
                   4671:                         $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
                   4672:                                     ':'.$val{'owner'}.'&';
                   4673:                     }
1.383     raeburn  4674:                 }
1.266     raeburn  4675:             }
1.234     foxr     4676: 	}
1.311     albertel 4677: 	if (&untie_domain_hash($hashref)) {
1.234     foxr     4678: 	    chop($qresult);
1.387     albertel 4679: 	    &Reply($client, \$qresult, $userinput);
1.234     foxr     4680: 	} else {
                   4681: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4682: 		    "while attempting courseiddump\n", $userinput);
                   4683: 	}
                   4684:     } else {
                   4685: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4686: 		"while attempting courseiddump\n", $userinput);
                   4687:     }
                   4688:     return 1;
                   4689: }
                   4690: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238     foxr     4691: 
1.438     raeburn  4692: sub course_lastaccess_handler {
                   4693:     my ($cmd, $tail, $client) = @_;
                   4694:     my $userinput = "$cmd:$tail";
                   4695:     my ($cdom,$cnum) = split(':',$tail); 
                   4696:     my (%lastaccess,$qresult);
                   4697:     my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
                   4698:     if ($hashref) {
                   4699:         while (my ($key,$value) = each(%$hashref)) {
                   4700:             my ($unesc_key,$lasttime);
                   4701:             $unesc_key = &unescape($key);
                   4702:             if ($cnum) {
                   4703:                 next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
                   4704:             }
                   4705:             if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
                   4706:                 $lastaccess{$1} = $value;
                   4707:             } else {
                   4708:                 my $items = &Apache::lonnet::thaw_unescape($value);
                   4709:                 if (ref($items) eq 'HASH') {
                   4710:                     unless ($lastaccess{$unesc_key}) {
                   4711:                         $lastaccess{$unesc_key} = '';
                   4712:                     }
                   4713:                 } else {
                   4714:                     my @courseitems = split(':',$value);
                   4715:                     $lastaccess{$unesc_key} = pop(@courseitems);
                   4716:                 }
                   4717:             }
                   4718:         }
                   4719:         foreach my $cid (sort(keys(%lastaccess))) {
                   4720:             $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&'; 
                   4721:         }
                   4722:         if (&untie_domain_hash($hashref)) {
                   4723:             if ($qresult) {
                   4724:                 chop($qresult);
                   4725:             }
                   4726:             &Reply($client, \$qresult, $userinput);
                   4727:         } else {
                   4728:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4729:                     "while attempting lastacourseaccess\n", $userinput);
                   4730:         }
                   4731:     } else {
                   4732:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4733:                 "while attempting lastcourseaccess\n", $userinput);
                   4734:     }
                   4735:     return 1;
                   4736: }
                   4737: &register_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
                   4738: 
1.238     foxr     4739: #
1.348     raeburn  4740: # Puts an unencrypted entry in a namespace db file at the domain level 
                   4741: #
                   4742: # Parameters:
                   4743: #    $cmd      - The command that got us here.
                   4744: #    $tail     - Tail of the command (remaining parameters).
                   4745: #    $client   - File descriptor connected to client.
                   4746: # Returns
                   4747: #     0        - Requested to exit, caller should shut down.
                   4748: #     1        - Continue processing.
                   4749: #  Side effects:
                   4750: #     reply is written to $client.
                   4751: #
                   4752: sub put_domain_handler {
                   4753:     my ($cmd,$tail,$client) = @_;
                   4754: 
                   4755:     my $userinput = "$cmd:$tail";
                   4756: 
                   4757:     my ($udom,$namespace,$what) =split(/:/,$tail,3);
                   4758:     chomp($what);
                   4759:     my @pairs=split(/\&/,$what);
                   4760:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
                   4761:                                    "P", $what);
                   4762:     if ($hashref) {
                   4763:         foreach my $pair (@pairs) {
                   4764:             my ($key,$value)=split(/=/,$pair);
                   4765:             $hashref->{$key}=$value;
                   4766:         }
                   4767:         if (&untie_domain_hash($hashref)) {
                   4768:             &Reply($client, "ok\n", $userinput);
                   4769:         } else {
                   4770:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4771:                      "while attempting putdom\n", $userinput);
                   4772:         }
                   4773:     } else {
                   4774:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4775:                   "while attempting putdom\n", $userinput);
                   4776:     }
                   4777: 
                   4778:     return 1;
                   4779: }
                   4780: &register_handler("putdom", \&put_domain_handler, 0, 1, 0);
                   4781: 
1.517     raeburn  4782: # Updates one or more entries in clickers.db file at the domain level
                   4783: #
                   4784: # Parameters:
                   4785: #    $cmd      - The command that got us here.
                   4786: #    $tail     - Tail of the command (remaining parameters).
                   4787: #                In this case a colon separated list containing:
                   4788: #                (a) the domain for which we are updating the entries,
                   4789: #                (b) the action required -- add or del -- and
                   4790: #                (c) a &-separated list of entries to add or delete.
                   4791: #    $client   - File descriptor connected to client.
                   4792: # Returns
                   4793: #     1        - Continue processing.
                   4794: #     0        - Requested to exit, caller should shut down.
                   4795: #  Side effects:
                   4796: #     reply is written to $client.
                   4797: #
                   4798: 
                   4799: 
                   4800: sub update_clickers {
                   4801:     my ($cmd, $tail, $client)  = @_;
                   4802: 
                   4803:     my $userinput = "$cmd:$tail";
                   4804:     my ($udom,$action,$what) =split(/:/,$tail,3);
                   4805:     chomp($what);
                   4806: 
                   4807:     my $hashref = &tie_domain_hash($udom, "clickers", &GDBM_WRCREAT(),
                   4808:                                  "U","$action:$what");
                   4809: 
                   4810:     if (!$hashref) {
                   4811:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4812:                   "while attempting updateclickers\n", $userinput);
                   4813:         return 1;
                   4814:     }
                   4815: 
                   4816:     my @pairs=split(/\&/,$what);
                   4817:     foreach my $pair (@pairs) {
                   4818:         my ($key,$value)=split(/=/,$pair);
                   4819:         if ($action eq 'add') {
                   4820:             if (exists($hashref->{$key})) {
                   4821:                 my @newvals = split(/,/,&unescape($value));
                   4822:                 my @currvals = split(/,/,&unescape($hashref->{$key}));
                   4823:                 my @merged = sort(keys(%{{map { $_ => 1 } (@newvals,@currvals)}}));
                   4824:                 $hashref->{$key}=&escape(join(',',@merged));
                   4825:             } else {
                   4826:                 $hashref->{$key}=$value;
                   4827:             }
                   4828:         } elsif ($action eq 'del') {
                   4829:             if (exists($hashref->{$key})) {
                   4830:                 my %current;
                   4831:                 map { $current{$_} = 1; } split(/,/,&unescape($hashref->{$key}));
                   4832:                 map { delete($current{$_}); } split(/,/,&unescape($value));
                   4833:                 if (keys(%current)) {
                   4834:                     $hashref->{$key}=&escape(join(',',sort(keys(%current))));
                   4835:                 } else {
                   4836:                     delete($hashref->{$key});
                   4837:                 }
                   4838:             }
                   4839:         }
                   4840:     }
                   4841:     if (&untie_user_hash($hashref)) {
                   4842:         &Reply( $client, "ok\n", $userinput);
                   4843:     } else {
                   4844:         &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   4845:                  "while attempting put\n",
                   4846:                  $userinput);
                   4847:     }
                   4848:     return 1;
                   4849: }
                   4850: &register_handler("updateclickers", \&update_clickers, 0, 1, 0);
                   4851: 
                   4852: 
                   4853: # Deletes one or more entries in a namespace db file at the domain level
                   4854: #
                   4855: # Parameters:
                   4856: #    $cmd      - The command that got us here.
                   4857: #    $tail     - Tail of the command (remaining parameters).
                   4858: #                In this case a colon separated list containing:
                   4859: #                (a) the domain for which we are deleting the entries,
                   4860: #                (b) &-separated list of keys to delete.  
                   4861: #    $client   - File descriptor connected to client.
                   4862: # Returns
                   4863: #     1        - Continue processing.
                   4864: #     0        - Requested to exit, caller should shut down.
                   4865: #  Side effects:
                   4866: #     reply is written to $client.
                   4867: #
                   4868: 
                   4869: sub del_domain_handler {
                   4870:     my ($cmd,$tail,$client) = @_;
                   4871: 
                   4872:     my $userinput = "$cmd:$tail";
                   4873: 
                   4874:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   4875:     chomp($what);
                   4876:     my $hashref = &tie_domain_hash($udom,$namespace,&GDBM_WRCREAT(),
                   4877:                                    "D", $what);
                   4878:     if ($hashref) {
                   4879:         my @keys=split(/\&/,$what);
                   4880:         foreach my $key (@keys) {
                   4881:             delete($hashref->{$key});
                   4882:         }
                   4883:         if (&untie_user_hash($hashref)) {
                   4884:             &Reply($client, "ok\n", $userinput);
                   4885:         } else {
                   4886:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4887:                     "while attempting deldom\n", $userinput);
                   4888:         }
                   4889:     } else {
                   4890:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4891:                  "while attempting deldom\n", $userinput);
                   4892:     }
                   4893:     return 1;
                   4894: }
                   4895: &register_handler("deldom", \&del_domain_handler, 0, 1, 0);
                   4896: 
                   4897: 
1.348     raeburn  4898: # Unencrypted get from the namespace database file at the domain level.
                   4899: # This function retrieves a keyed item from a specific named database in the
                   4900: # domain directory.
                   4901: #
                   4902: # Parameters:
                   4903: #   $cmd             - Command request keyword (get).
                   4904: #   $tail            - Tail of the command.  This is a colon separated list
                   4905: #                      consisting of the domain and the 'namespace' 
                   4906: #                      which selects the gdbm file to do the lookup in,
                   4907: #                      & separated list of keys to lookup.  Note that
                   4908: #                      the values are returned as an & separated list too.
                   4909: #   $client          - File descriptor open on the client.
                   4910: # Returns:
                   4911: #   1       - Continue processing.
                   4912: #   0       - Exit.
                   4913: #  Side effects:
                   4914: #     reply is written to $client.
                   4915: #
                   4916: 
                   4917: sub get_domain_handler {
                   4918:     my ($cmd, $tail, $client) = @_;
                   4919: 
1.461     foxr     4920: 
1.536     raeburn  4921:     my $userinput = "$cmd:$tail";
                   4922: 
                   4923:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   4924:     chomp($what);
                   4925:     if ($namespace =~ /^enc/) {
                   4926:         &Failure( $client, "refused\n", $userinput);
                   4927:     } else {
                   4928:         my @queries=split(/\&/,$what);
                   4929:         my $qresult='';
                   4930:         my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
                   4931:         if ($hashref) {
                   4932:             for (my $i=0;$i<=$#queries;$i++) {
                   4933:                 $qresult.="$hashref->{$queries[$i]}&";
                   4934:             }
                   4935:             if (&untie_domain_hash($hashref)) {
                   4936:                 $qresult=~s/\&$//;
                   4937:                 &Reply($client, \$qresult, $userinput);
                   4938:             } else {
                   4939:                 &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4940:                           "while attempting getdom\n",$userinput);
                   4941:             }
                   4942:         } else {
                   4943:             &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4944:                      "while attempting getdom\n",$userinput);
                   4945:         }
                   4946:     }
                   4947: 
                   4948:     return 1;
                   4949: }
                   4950: &register_handler("getdom", \&get_domain_handler, 0, 1, 0);
                   4951: 
                   4952: sub encrypted_get_domain_handler {
                   4953:     my ($cmd, $tail, $client) = @_;
                   4954: 
                   4955:     my $userinput = "$cmd:$tail";
1.348     raeburn  4956: 
                   4957:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   4958:     chomp($what);
                   4959:     my @queries=split(/\&/,$what);
                   4960:     my $qresult='';
                   4961:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
                   4962:     if ($hashref) {
                   4963:         for (my $i=0;$i<=$#queries;$i++) {
                   4964:             $qresult.="$hashref->{$queries[$i]}&";
                   4965:         }
                   4966:         if (&untie_domain_hash($hashref)) {
                   4967:             $qresult=~s/\&$//;
1.536     raeburn  4968:             if ($cipher) {
                   4969:                 my $cmdlength=length($qresult);
                   4970:                 $qresult.="         ";
                   4971:                 my $encqresult='';
                   4972:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   4973:                     $encqresult.= unpack("H16",
                   4974:                                          $cipher->encrypt(substr($qresult,
                   4975:                                                                  $encidx,
                   4976:                                                                  8)));
                   4977:                 }
                   4978:                 &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   4979:             } else {
                   4980:                 &Failure( $client, "error:no_key\n", $userinput);
                   4981:             }
1.348     raeburn  4982:         } else {
                   4983:             &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
1.536     raeburn  4984:                       "while attempting egetdom\n",$userinput);
1.348     raeburn  4985:         }
                   4986:     } else {
                   4987:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
1.536     raeburn  4988:                  "while attempting egetdom\n",$userinput);
1.348     raeburn  4989:     }
                   4990:     return 1;
                   4991: }
1.536     raeburn  4992: &register_handler("egetdom", \&encrypted_get_domain_handler, 1, 1, 0);
1.348     raeburn  4993: 
1.420     raeburn  4994: #
1.238     foxr     4995: #  Puts an id to a domains id database. 
                   4996: #
                   4997: #  Parameters:
                   4998: #   $cmd     - The command that triggered us.
                   4999: #   $tail    - Remainder of the request other than the command. This is a 
                   5000: #              colon separated list containing:
                   5001: #              $domain  - The domain for which we are writing the id.
                   5002: #              $pairs  - The id info to write... this is and & separated list
                   5003: #                        of keyword=value.
                   5004: #   $client  - Socket open on the client.
                   5005: #  Returns:
                   5006: #    1   - Continue processing.
                   5007: #  Side effects:
                   5008: #     reply is written to $client.
                   5009: #
                   5010: sub put_id_handler {
                   5011:     my ($cmd,$tail,$client) = @_;
                   5012: 
                   5013: 
                   5014:     my $userinput = "$cmd:$tail";
                   5015: 
                   5016:     my ($udom,$what)=split(/:/,$tail);
                   5017:     chomp($what);
                   5018:     my @pairs=split(/\&/,$what);
                   5019:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   5020: 				   "P", $what);
                   5021:     if ($hashref) {
                   5022: 	foreach my $pair (@pairs) {
                   5023: 	    my ($key,$value)=split(/=/,$pair);
                   5024: 	    $hashref->{$key}=$value;
                   5025: 	}
1.311     albertel 5026: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     5027: 	    &Reply($client, "ok\n", $userinput);
                   5028: 	} else {
                   5029: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5030: 		     "while attempting idput\n", $userinput);
                   5031: 	}
                   5032:     } else {
                   5033: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5034: 		  "while attempting idput\n", $userinput);
                   5035:     }
                   5036: 
                   5037:     return 1;
                   5038: }
1.263     albertel 5039: &register_handler("idput", \&put_id_handler, 0, 1, 0);
1.238     foxr     5040: 
                   5041: #
                   5042: #  Retrieves a set of id values from the id database.
                   5043: #  Returns an & separated list of results, one for each requested id to the
                   5044: #  client.
                   5045: #
                   5046: # Parameters:
                   5047: #   $cmd       - Command keyword that caused us to be dispatched.
                   5048: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5049: #               domain - the domain whose id table we dump
                   5050: #               ids      Consists of an & separated list of
                   5051: #                        id keywords whose values will be fetched.
                   5052: #                        nonexisting keywords will have an empty value.
                   5053: #   $client    - Socket open on the client.
                   5054: #
                   5055: # Returns:
                   5056: #    1 - indicating processing should continue.
                   5057: # Side effects:
                   5058: #   An & separated list of results is written to $client.
                   5059: #
                   5060: sub get_id_handler {
                   5061:     my ($cmd, $tail, $client) = @_;
                   5062: 
                   5063:     
                   5064:     my $userinput = "$client:$tail";
                   5065:     
                   5066:     my ($udom,$what)=split(/:/,$tail);
                   5067:     chomp($what);
                   5068:     my @queries=split(/\&/,$what);
                   5069:     my $qresult='';
                   5070:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
                   5071:     if ($hashref) {
                   5072: 	for (my $i=0;$i<=$#queries;$i++) {
                   5073: 	    $qresult.="$hashref->{$queries[$i]}&";
                   5074: 	}
1.311     albertel 5075: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     5076: 	    $qresult=~s/\&$//;
1.387     albertel 5077: 	    &Reply($client, \$qresult, $userinput);
1.238     foxr     5078: 	} else {
                   5079: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5080: 		      "while attempting idget\n",$userinput);
                   5081: 	}
                   5082:     } else {
                   5083: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5084: 		 "while attempting idget\n",$userinput);
                   5085:     }
                   5086:     
                   5087:     return 1;
                   5088: }
1.263     albertel 5089: &register_handler("idget", \&get_id_handler, 0, 1, 0);
1.238     foxr     5090: 
1.501     raeburn  5091: #   Deletes one or more ids in a domain's id database.
                   5092: #
                   5093: #   Parameters:
                   5094: #       $cmd                  - Command keyword (iddel).
                   5095: #       $tail                 - Command tail.  In this case a colon
                   5096: #                               separated list containing:
                   5097: #                               The domain for which we are deleting the id(s).
                   5098: #                               &-separated list of id(s) to delete.
                   5099: #       $client               - File open on client socket.
                   5100: # Returns:
                   5101: #     1   - Continue processing
                   5102: #     0   - Exit server.
                   5103: #     
                   5104: #
                   5105: 
                   5106: sub del_id_handler {
                   5107:     my ($cmd,$tail,$client) = @_;
                   5108: 
                   5109:     my $userinput = "$cmd:$tail";
                   5110: 
                   5111:     my ($udom,$what)=split(/:/,$tail);
                   5112:     chomp($what);
                   5113:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   5114:                                    "D", $what);
                   5115:     if ($hashref) {
                   5116:         my @keys=split(/\&/,$what);
                   5117:         foreach my $key (@keys) {
                   5118:             delete($hashref->{$key});
                   5119:         }
                   5120:         if (&untie_user_hash($hashref)) {
                   5121:             &Reply($client, "ok\n", $userinput);
                   5122:         } else {
                   5123:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5124:                     "while attempting iddel\n", $userinput);
                   5125:         }
                   5126:     } else {
                   5127:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5128:                  "while attempting iddel\n", $userinput);
                   5129:     }
                   5130:     return 1;
                   5131: }
                   5132: &register_handler("iddel", \&del_id_handler, 0, 1, 0);
                   5133: 
1.238     foxr     5134: #
1.299     raeburn  5135: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
                   5136: #
                   5137: # Parameters
                   5138: #   $cmd       - Command keyword that caused us to be dispatched.
                   5139: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5140: #               domain - the domain whose dcmail we are recording
                   5141: #               email    Consists of key=value pair 
                   5142: #                        where key is unique msgid
                   5143: #                        and value is message (in XML)
                   5144: #   $client    - Socket open on the client.
                   5145: #
                   5146: # Returns:
                   5147: #    1 - indicating processing should continue.
                   5148: # Side effects
                   5149: #     reply is written to $client.
                   5150: #
                   5151: sub put_dcmail_handler {
                   5152:     my ($cmd,$tail,$client) = @_;
                   5153:     my $userinput = "$cmd:$tail";
1.463     foxr     5154: 
                   5155: 
1.299     raeburn  5156:     my ($udom,$what)=split(/:/,$tail);
                   5157:     chomp($what);
                   5158:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5159:     if ($hashref) {
                   5160:         my ($key,$value)=split(/=/,$what);
                   5161:         $hashref->{$key}=$value;
                   5162:     }
1.311     albertel 5163:     if (&untie_domain_hash($hashref)) {
1.299     raeburn  5164:         &Reply($client, "ok\n", $userinput);
                   5165:     } else {
                   5166:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5167:                  "while attempting dcmailput\n", $userinput);
                   5168:     }
                   5169:     return 1;
                   5170: }
                   5171: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
                   5172: 
                   5173: #
                   5174: # Retrieves broadcast e-mail from nohist_dcmail database
                   5175: # Returns to client an & separated list of key=value pairs,
                   5176: # where key is msgid and value is message information.
                   5177: #
                   5178: # Parameters
                   5179: #   $cmd       - Command keyword that caused us to be dispatched.
                   5180: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5181: #               domain - the domain whose dcmail table we dump
                   5182: #               startfilter - beginning of time window 
                   5183: #               endfilter - end of time window
                   5184: #               sendersfilter - & separated list of username:domain 
                   5185: #                 for senders to search for.
                   5186: #   $client    - Socket open on the client.
                   5187: #
                   5188: # Returns:
                   5189: #    1 - indicating processing should continue.
                   5190: # Side effects
                   5191: #     reply (& separated list of msgid=messageinfo pairs) is 
                   5192: #     written to $client.
                   5193: #
                   5194: sub dump_dcmail_handler {
                   5195:     my ($cmd, $tail, $client) = @_;
                   5196:                                                                                 
                   5197:     my $userinput = "$cmd:$tail";
                   5198:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
                   5199:     chomp($sendersfilter);
                   5200:     my @senders = ();
                   5201:     if (defined($startfilter)) {
                   5202:         $startfilter=&unescape($startfilter);
                   5203:     } else {
                   5204:         $startfilter='.';
                   5205:     }
                   5206:     if (defined($endfilter)) {
                   5207:         $endfilter=&unescape($endfilter);
                   5208:     } else {
                   5209:         $endfilter='.';
                   5210:     }
                   5211:     if (defined($sendersfilter)) {
                   5212:         $sendersfilter=&unescape($sendersfilter);
1.300     albertel 5213: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
1.299     raeburn  5214:     }
                   5215: 
                   5216:     my $qresult='';
                   5217:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5218:     if ($hashref) {
                   5219:         while (my ($key,$value) = each(%$hashref)) {
                   5220:             my $match = 1;
1.303     albertel 5221:             my ($timestamp,$subj,$uname,$udom) = 
                   5222: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
1.299     raeburn  5223:             $subj = &unescape($subj);
                   5224:             unless ($startfilter eq '.' || !defined($startfilter)) {
                   5225:                 if ($timestamp < $startfilter) {
                   5226:                     $match = 0;
                   5227:                 }
                   5228:             }
                   5229:             unless ($endfilter eq '.' || !defined($endfilter)) {
                   5230:                 if ($timestamp > $endfilter) {
                   5231:                     $match = 0;
                   5232:                 }
                   5233:             }
                   5234:             unless (@senders < 1) {
                   5235:                 unless (grep/^$uname:$udom$/,@senders) {
                   5236:                     $match = 0;
                   5237:                 }
                   5238:             }
                   5239:             if ($match == 1) {
                   5240:                 $qresult.=$key.'='.$value.'&';
                   5241:             }
                   5242:         }
1.311     albertel 5243:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5244:             chop($qresult);
1.387     albertel 5245:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5246:         } else {
                   5247:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5248:                     "while attempting dcmaildump\n", $userinput);
                   5249:         }
                   5250:     } else {
                   5251:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5252:                 "while attempting dcmaildump\n", $userinput);
                   5253:     }
                   5254:     return 1;
                   5255: }
                   5256: 
                   5257: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
                   5258: 
                   5259: #
                   5260: # Puts domain roles in nohist_domainroles database
                   5261: #
                   5262: # Parameters
                   5263: #   $cmd       - Command keyword that caused us to be dispatched.
                   5264: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5265: #               domain - the domain whose roles we are recording  
                   5266: #               role -   Consists of key=value pair
                   5267: #                        where key is unique role
                   5268: #                        and value is start/end date information
                   5269: #   $client    - Socket open on the client.
                   5270: #
                   5271: # Returns:
                   5272: #    1 - indicating processing should continue.
                   5273: # Side effects
                   5274: #     reply is written to $client.
                   5275: #
                   5276: 
                   5277: sub put_domainroles_handler {
                   5278:     my ($cmd,$tail,$client) = @_;
                   5279: 
                   5280:     my $userinput = "$cmd:$tail";
                   5281:     my ($udom,$what)=split(/:/,$tail);
                   5282:     chomp($what);
                   5283:     my @pairs=split(/\&/,$what);
                   5284:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5285:     if ($hashref) {
                   5286:         foreach my $pair (@pairs) {
                   5287:             my ($key,$value)=split(/=/,$pair);
                   5288:             $hashref->{$key}=$value;
                   5289:         }
1.311     albertel 5290:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5291:             &Reply($client, "ok\n", $userinput);
                   5292:         } else {
                   5293:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5294:                      "while attempting domroleput\n", $userinput);
                   5295:         }
                   5296:     } else {
                   5297:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5298:                   "while attempting domroleput\n", $userinput);
                   5299:     }
                   5300:                                                                                   
                   5301:     return 1;
                   5302: }
                   5303: 
                   5304: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
                   5305: 
                   5306: #
                   5307: # Retrieves domain roles from nohist_domainroles database
                   5308: # Returns to client an & separated list of key=value pairs,
                   5309: # where key is role and value is start and end date information.
                   5310: #
                   5311: # Parameters
                   5312: #   $cmd       - Command keyword that caused us to be dispatched.
                   5313: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5314: #               domain - the domain whose domain roles table we dump
                   5315: #   $client    - Socket open on the client.
                   5316: #
                   5317: # Returns:
                   5318: #    1 - indicating processing should continue.
                   5319: # Side effects
                   5320: #     reply (& separated list of role=start/end info pairs) is
                   5321: #     written to $client.
                   5322: #
                   5323: sub dump_domainroles_handler {
                   5324:     my ($cmd, $tail, $client) = @_;
                   5325:                                                                                            
                   5326:     my $userinput = "$cmd:$tail";
                   5327:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
                   5328:     chomp($rolesfilter);
                   5329:     my @roles = ();
                   5330:     if (defined($startfilter)) {
                   5331:         $startfilter=&unescape($startfilter);
                   5332:     } else {
                   5333:         $startfilter='.';
                   5334:     }
                   5335:     if (defined($endfilter)) {
                   5336:         $endfilter=&unescape($endfilter);
                   5337:     } else {
                   5338:         $endfilter='.';
                   5339:     }
                   5340:     if (defined($rolesfilter)) {
                   5341:         $rolesfilter=&unescape($rolesfilter);
1.300     albertel 5342: 	@roles = split(/\&/,$rolesfilter);
1.299     raeburn  5343:     }
1.421     raeburn  5344: 
1.299     raeburn  5345:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5346:     if ($hashref) {
                   5347:         my $qresult = '';
                   5348:         while (my ($key,$value) = each(%$hashref)) {
                   5349:             my $match = 1;
1.421     raeburn  5350:             my ($end,$start) = split(/:/,&unescape($value));
1.299     raeburn  5351:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
1.421     raeburn  5352:             unless (@roles < 1) {
                   5353:                 unless (grep/^\Q$trole\E$/,@roles) {
                   5354:                     $match = 0;
                   5355:                     next;
                   5356:                 }
                   5357:             }
1.299     raeburn  5358:             unless ($startfilter eq '.' || !defined($startfilter)) {
1.415     raeburn  5359:                 if ((defined($start)) && ($start >= $startfilter)) {
1.299     raeburn  5360:                     $match = 0;
1.421     raeburn  5361:                     next;
1.299     raeburn  5362:                 }
                   5363:             }
                   5364:             unless ($endfilter eq '.' || !defined($endfilter)) {
1.421     raeburn  5365:                 if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
1.299     raeburn  5366:                     $match = 0;
1.421     raeburn  5367:                     next;
1.299     raeburn  5368:                 }
                   5369:             }
                   5370:             if ($match == 1) {
                   5371:                 $qresult.=$key.'='.$value.'&';
                   5372:             }
                   5373:         }
1.311     albertel 5374:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5375:             chop($qresult);
1.387     albertel 5376:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5377:         } else {
                   5378:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5379:                     "while attempting domrolesdump\n", $userinput);
                   5380:         }
                   5381:     } else {
                   5382:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5383:                 "while attempting domrolesdump\n", $userinput);
                   5384:     }
                   5385:     return 1;
                   5386: }
                   5387: 
                   5388: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
                   5389: 
                   5390: 
1.238     foxr     5391: #  Process the tmpput command I'm not sure what this does.. Seems to
                   5392: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
                   5393: # where Id is the client's ip concatenated with a sequence number.
                   5394: # The file will contain some value that is passed in.  Is this e.g.
                   5395: # a login token?
                   5396: #
                   5397: # Parameters:
                   5398: #    $cmd     - The command that got us dispatched.
                   5399: #    $tail    - The remainder of the request following $cmd:
                   5400: #               In this case this will be the contents of the file.
                   5401: #    $client  - Socket connected to the client.
                   5402: # Returns:
                   5403: #    1 indicating processing can continue.
                   5404: # Side effects:
                   5405: #   A file is created in the local filesystem.
                   5406: #   A reply is sent to the client.
                   5407: sub tmp_put_handler {
                   5408:     my ($cmd, $what, $client) = @_;
                   5409: 
                   5410:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
                   5411: 
1.347     raeburn  5412:     my ($record,$context) = split(/:/,$what);
                   5413:     if ($context ne '') {
                   5414:         chomp($context);
                   5415:         $context = &unescape($context);
                   5416:     }
                   5417:     my ($id,$store);
1.238     foxr     5418:     $tmpsnum++;
1.454     raeburn  5419:     if (($context eq 'resetpw') || ($context eq 'createaccount')) {
1.347     raeburn  5420:         $id = &md5_hex(&md5_hex(time.{}.rand().$$));
                   5421:     } else {
                   5422:         $id = $$.'_'.$clientip.'_'.$tmpsnum;
                   5423:     }
1.238     foxr     5424:     $id=~s/\W/\_/g;
1.347     raeburn  5425:     $record=~s/\n//g;
1.238     foxr     5426:     my $execdir=$perlvar{'lonDaemons'};
                   5427:     if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
1.347     raeburn  5428: 	print $store $record;
1.238     foxr     5429: 	close $store;
1.387     albertel 5430: 	&Reply($client, \$id, $userinput);
1.238     foxr     5431:     } else {
                   5432: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5433: 		  "while attempting tmpput\n", $userinput);
                   5434:     }
                   5435:     return 1;
                   5436:   
                   5437: }
                   5438: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263     albertel 5439: 
1.238     foxr     5440: #   Processes the tmpget command.  This command returns the contents
                   5441: #  of a temporary resource file(?) created via tmpput.
                   5442: #
                   5443: # Paramters:
                   5444: #    $cmd      - Command that got us dispatched.
                   5445: #    $id       - Tail of the command, contain the id of the resource
                   5446: #                we want to fetch.
                   5447: #    $client   - socket open on the client.
                   5448: # Return:
                   5449: #    1         - Inidcating processing can continue.
                   5450: # Side effects:
                   5451: #   A reply is sent to the client.
                   5452: #
                   5453: sub tmp_get_handler {
                   5454:     my ($cmd, $id, $client) = @_;
                   5455: 
                   5456:     my $userinput = "$cmd:$id"; 
                   5457:     
                   5458: 
                   5459:     $id=~s/\W/\_/g;
                   5460:     my $store;
                   5461:     my $execdir=$perlvar{'lonDaemons'};
                   5462:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
                   5463: 	my $reply=<$store>;
1.387     albertel 5464: 	&Reply( $client, \$reply, $userinput);
1.238     foxr     5465: 	close $store;
                   5466:     } else {
                   5467: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5468: 		  "while attempting tmpget\n", $userinput);
                   5469:     }
                   5470: 
                   5471:     return 1;
                   5472: }
                   5473: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263     albertel 5474: 
1.238     foxr     5475: #
                   5476: #  Process the tmpdel command.  This command deletes a temp resource
                   5477: #  created by the tmpput command.
                   5478: #
                   5479: # Parameters:
                   5480: #   $cmd      - Command that got us here.
                   5481: #   $id       - Id of the temporary resource created.
                   5482: #   $client   - socket open on the client process.
                   5483: #
                   5484: # Returns:
                   5485: #   1     - Indicating processing should continue.
                   5486: # Side Effects:
                   5487: #   A file is deleted
                   5488: #   A reply is sent to the client.
                   5489: sub tmp_del_handler {
                   5490:     my ($cmd, $id, $client) = @_;
                   5491:     
                   5492:     my $userinput= "$cmd:$id";
                   5493:     
                   5494:     chomp($id);
                   5495:     $id=~s/\W/\_/g;
                   5496:     my $execdir=$perlvar{'lonDaemons'};
                   5497:     if (unlink("$execdir/tmp/$id.tmp")) {
                   5498: 	&Reply($client, "ok\n", $userinput);
                   5499:     } else {
                   5500: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
                   5501: 		  "while attempting tmpdel\n", $userinput);
                   5502:     }
                   5503:     
                   5504:     return 1;
                   5505: 
                   5506: }
                   5507: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263     albertel 5508: 
1.238     foxr     5509: #
1.246     foxr     5510: #   Processes the setannounce command.  This command
                   5511: #   creates a file named announce.txt in the top directory of
                   5512: #   the documentn root and sets its contents.  The announce.txt file is
                   5513: #   printed in its entirety at the LonCAPA login page.  Note:
                   5514: #   once the announcement.txt fileis created it cannot be deleted.
                   5515: #   However, setting the contents of the file to empty removes the
                   5516: #   announcement from the login page of loncapa so who cares.
                   5517: #
                   5518: # Parameters:
                   5519: #    $cmd          - The command that got us dispatched.
                   5520: #    $announcement - The text of the announcement.
                   5521: #    $client       - Socket open on the client process.
                   5522: # Retunrns:
                   5523: #   1             - Indicating request processing should continue
                   5524: # Side Effects:
                   5525: #   The file {DocRoot}/announcement.txt is created.
                   5526: #   A reply is sent to $client.
                   5527: #
                   5528: sub set_announce_handler {
                   5529:     my ($cmd, $announcement, $client) = @_;
                   5530:   
                   5531:     my $userinput    = "$cmd:$announcement";
                   5532: 
                   5533:     chomp($announcement);
                   5534:     $announcement=&unescape($announcement);
                   5535:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
                   5536: 				'/announcement.txt')) {
                   5537: 	print $store $announcement;
                   5538: 	close $store;
                   5539: 	&Reply($client, "ok\n", $userinput);
                   5540:     } else {
                   5541: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
                   5542:     }
                   5543: 
                   5544:     return 1;
                   5545: }
                   5546: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263     albertel 5547: 
1.246     foxr     5548: #
                   5549: #  Return the version of the daemon.  This can be used to determine
                   5550: #  the compatibility of cross version installations or, alternatively to
                   5551: #  simply know who's out of date and who isn't.  Note that the version
                   5552: #  is returned concatenated with the tail.
                   5553: # Parameters:
                   5554: #   $cmd        - the request that dispatched to us.
                   5555: #   $tail       - Tail of the request (client's version?).
                   5556: #   $client     - Socket open on the client.
                   5557: #Returns:
                   5558: #   1 - continue processing requests.
                   5559: # Side Effects:
                   5560: #   Replies with version to $client.
                   5561: sub get_version_handler {
                   5562:     my ($cmd, $tail, $client) = @_;
                   5563: 
                   5564:     my $userinput  = $cmd.$tail;
                   5565:     
                   5566:     &Reply($client, &version($userinput)."\n", $userinput);
                   5567: 
                   5568: 
                   5569:     return 1;
                   5570: }
                   5571: &register_handler("version", \&get_version_handler, 0, 1, 0);
1.263     albertel 5572: 
1.246     foxr     5573: #  Set the current host and domain.  This is used to support
                   5574: #  multihomed systems.  Each IP of the system, or even separate daemons
                   5575: #  on the same IP can be treated as handling a separate lonCAPA virtual
                   5576: #  machine.  This command selects the virtual lonCAPA.  The client always
                   5577: #  knows the right one since it is lonc and it is selecting the domain/system
                   5578: #  from the hosts.tab file.
                   5579: # Parameters:
                   5580: #    $cmd      - Command that dispatched us.
                   5581: #    $tail     - Tail of the command (domain/host requested).
                   5582: #    $socket   - Socket open on the client.
                   5583: #
                   5584: # Returns:
                   5585: #     1   - Indicates the program should continue to process requests.
                   5586: # Side-effects:
                   5587: #     The default domain/system context is modified for this daemon.
                   5588: #     a reply is sent to the client.
                   5589: #
                   5590: sub set_virtual_host_handler {
                   5591:     my ($cmd, $tail, $socket) = @_;
                   5592:   
                   5593:     my $userinput  ="$cmd:$tail";
                   5594: 
                   5595:     &Reply($client, &sethost($userinput)."\n", $userinput);
                   5596: 
                   5597: 
                   5598:     return 1;
                   5599: }
1.247     albertel 5600: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246     foxr     5601: 
                   5602: #  Process a request to exit:
                   5603: #   - "bye" is sent to the client.
                   5604: #   - The client socket is shutdown and closed.
                   5605: #   - We indicate to the caller that we should exit.
                   5606: # Formal Parameters:
                   5607: #   $cmd                - The command that got us here.
                   5608: #   $tail               - Tail of the command (empty).
                   5609: #   $client             - Socket open on the tail.
                   5610: # Returns:
                   5611: #   0      - Indicating the program should exit!!
                   5612: #
                   5613: sub exit_handler {
                   5614:     my ($cmd, $tail, $client) = @_;
                   5615: 
                   5616:     my $userinput = "$cmd:$tail";
                   5617: 
                   5618:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
                   5619:     &Reply($client, "bye\n", $userinput);
                   5620:     $client->shutdown(2);        # shutdown the socket forcibly.
                   5621:     $client->close();
                   5622: 
                   5623:     return 0;
                   5624: }
1.248     foxr     5625: &register_handler("exit", \&exit_handler, 0,1,1);
                   5626: &register_handler("init", \&exit_handler, 0,1,1);
                   5627: &register_handler("quit", \&exit_handler, 0,1,1);
                   5628: 
                   5629: #  Determine if auto-enrollment is enabled.
                   5630: #  Note that the original had what I believe to be a defect.
                   5631: #  The original returned 0 if the requestor was not a registerd client.
                   5632: #  It should return "refused".
                   5633: # Formal Parameters:
                   5634: #   $cmd       - The command that invoked us.
                   5635: #   $tail      - The tail of the command (Extra command parameters.
                   5636: #   $client    - The socket open on the client that issued the request.
                   5637: # Returns:
                   5638: #    1         - Indicating processing should continue.
                   5639: #
                   5640: sub enrollment_enabled_handler {
                   5641:     my ($cmd, $tail, $client) = @_;
                   5642:     my $userinput = $cmd.":".$tail; # For logging purposes.
                   5643: 
                   5644:     
1.337     albertel 5645:     my ($cdom) = split(/:/, $tail, 2);   # Domain we're asking about.
                   5646: 
1.248     foxr     5647:     my $outcome  = &localenroll::run($cdom);
1.387     albertel 5648:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5649: 
                   5650:     return 1;
                   5651: }
                   5652: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
                   5653: 
1.417     raeburn  5654: #
1.423     raeburn  5655: #   Validate an institutional code used for a LON-CAPA course.          
1.417     raeburn  5656: #
                   5657: # Formal Parameters:
                   5658: #   $cmd          - The command request that got us dispatched.
                   5659: #   $tail         - The tail of the command.  In this case,
                   5660: #                   this is a colon separated set of words that will be split
                   5661: #                   into:
1.424     raeburn  5662: #                        $dom      - The domain for which the check of 
                   5663: #                                    institutional course code will occur.
                   5664: #
                   5665: #                        $instcode - The institutional code for the course
                   5666: #                                    being requested, or validated for rights
                   5667: #                                    to request.
                   5668: #
                   5669: #                        $owner    - The course requestor (who will be the
                   5670: #                                    course owner, in the form username:domain
                   5671: #
1.417     raeburn  5672: #   $client       - Socket open on the client.
                   5673: # Returns:
                   5674: #    1           - Indicating processing should continue.
                   5675: #
                   5676: sub validate_instcode_handler {
                   5677:     my ($cmd, $tail, $client) = @_;
                   5678:     my $userinput = "$cmd:$tail";
1.423     raeburn  5679:     my ($dom,$instcode,$owner) = split(/:/, $tail);
1.422     raeburn  5680:     $instcode = &unescape($instcode);
                   5681:     $owner = &unescape($owner);
1.498     raeburn  5682:     my ($outcome,$description,$credits) = 
1.426     raeburn  5683:         &localenroll::validate_instcode($dom,$instcode,$owner);
1.498     raeburn  5684:     my $result = &escape($outcome).'&'.&escape($description).'&'.
                   5685:                  &escape($credits);
1.426     raeburn  5686:     &Reply($client, \$result, $userinput);
1.417     raeburn  5687: 
                   5688:     return 1;
                   5689: }
                   5690: &register_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
                   5691: 
1.248     foxr     5692: #   Get the official sections for which auto-enrollment is possible.
                   5693: #   Since the admin people won't know about 'unofficial sections' 
                   5694: #   we cannot auto-enroll on them.
                   5695: # Formal Parameters:
                   5696: #    $cmd     - The command request that got us dispatched here.
                   5697: #    $tail    - The remainder of the request.  In our case this
                   5698: #               will be split into:
                   5699: #               $coursecode   - The course name from the admin point of view.
                   5700: #               $cdom         - The course's domain(?).
                   5701: #    $client  - Socket open on the client.
                   5702: # Returns:
                   5703: #    1    - Indiciting processing should continue.
                   5704: #
                   5705: sub get_sections_handler {
                   5706:     my ($cmd, $tail, $client) = @_;
                   5707:     my $userinput = "$cmd:$tail";
                   5708: 
                   5709:     my ($coursecode, $cdom) = split(/:/, $tail);
                   5710:     my @secs = &localenroll::get_sections($coursecode,$cdom);
                   5711:     my $seclist = &escape(join(':',@secs));
                   5712: 
1.387     albertel 5713:     &Reply($client, \$seclist, $userinput);
1.248     foxr     5714:     
                   5715: 
                   5716:     return 1;
                   5717: }
                   5718: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
                   5719: 
                   5720: #   Validate the owner of a new course section.  
                   5721: #
                   5722: # Formal Parameters:
                   5723: #   $cmd      - Command that got us dispatched.
                   5724: #   $tail     - the remainder of the command.  For us this consists of a
                   5725: #               colon separated string containing:
                   5726: #                  $inst    - Course Id from the institutions point of view.
                   5727: #                  $owner   - Proposed owner of the course.
                   5728: #                  $cdom    - Domain of the course (from the institutions
                   5729: #                             point of view?)..
                   5730: #   $client   - Socket open on the client.
                   5731: #
                   5732: # Returns:
                   5733: #   1        - Processing should continue.
                   5734: #
                   5735: sub validate_course_owner_handler {
                   5736:     my ($cmd, $tail, $client)  = @_;
                   5737:     my $userinput = "$cmd:$tail";
1.470     raeburn  5738:     my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
                   5739:     
1.336     raeburn  5740:     $owner = &unescape($owner);
1.470     raeburn  5741:     $coowners = &unescape($coowners);
                   5742:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
1.387     albertel 5743:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5744: 
                   5745: 
                   5746: 
                   5747:     return 1;
                   5748: }
                   5749: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263     albertel 5750: 
1.248     foxr     5751: #
                   5752: #   Validate a course section in the official schedule of classes
                   5753: #   from the institutions point of view (part of autoenrollment).
                   5754: #
                   5755: # Formal Parameters:
                   5756: #   $cmd          - The command request that got us dispatched.
                   5757: #   $tail         - The tail of the command.  In this case,
                   5758: #                   this is a colon separated set of words that will be split
                   5759: #                   into:
                   5760: #                        $inst_course_id - The course/section id from the
                   5761: #                                          institutions point of view.
                   5762: #                        $cdom           - The domain from the institutions
                   5763: #                                          point of view.
                   5764: #   $client       - Socket open on the client.
                   5765: # Returns:
                   5766: #    1           - Indicating processing should continue.
                   5767: #
                   5768: sub validate_course_section_handler {
                   5769:     my ($cmd, $tail, $client) = @_;
                   5770:     my $userinput = "$cmd:$tail";
                   5771:     my ($inst_course_id, $cdom) = split(/:/, $tail);
                   5772: 
                   5773:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
1.387     albertel 5774:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5775: 
                   5776: 
                   5777:     return 1;
                   5778: }
                   5779: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
                   5780: 
                   5781: #
1.340     raeburn  5782: #   Validate course owner's access to enrollment data for specific class section. 
                   5783: #   
                   5784: #
                   5785: # Formal Parameters:
                   5786: #    $cmd     - The command request that got us dispatched.
                   5787: #    $tail    - The tail of the command.   In this case this is a colon separated
1.542     raeburn  5788: #               set of values that will be split into:
1.340     raeburn  5789: #               $inst_class  - Institutional code for the specific class section   
1.542     raeburn  5790: #               $ownerlist   - An escaped comma-separated list of username:domain 
                   5791: #                              of the course owner, and co-owner(s).
1.340     raeburn  5792: #               $cdom        - The domain of the course from the institution's
                   5793: #                              point of view.
                   5794: #    $client  - The socket open on the client.
                   5795: # Returns:
                   5796: #    1 - continue processing.
                   5797: #
                   5798: 
                   5799: sub validate_class_access_handler {
                   5800:     my ($cmd, $tail, $client) = @_;
                   5801:     my $userinput = "$cmd:$tail";
1.383     raeburn  5802:     my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
1.392     raeburn  5803:     my $owners = &unescape($ownerlist);
1.341     albertel 5804:     my $outcome;
                   5805:     eval {
                   5806: 	local($SIG{__DIE__})='DEFAULT';
1.392     raeburn  5807: 	$outcome=&localenroll::check_section($inst_class,$owners,$cdom);
1.341     albertel 5808:     };
1.387     albertel 5809:     &Reply($client,\$outcome, $userinput);
1.340     raeburn  5810: 
                   5811:     return 1;
                   5812: }
                   5813: &register_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
                   5814: 
                   5815: #
1.542     raeburn  5816: #   Validate course owner or co-owners(s) access to enrollment data for all sections
                   5817: #   and crosslistings for a particular course.
                   5818: #
                   5819: #
                   5820: # Formal Parameters:
                   5821: #    $cmd     - The command request that got us dispatched.
                   5822: #    $tail    - The tail of the command.   In this case this is a colon separated
                   5823: #               set of values that will be split into:
                   5824: #               $ownerlist   - An escaped comma-separated list of username:domain
                   5825: #                              of the course owner, and co-owner(s).
                   5826: #               $cdom        - The domain of the course from the institution's
                   5827: #                              point of view.
                   5828: #               $classes     - Frozen hash of institutional course sections and
                   5829: #                              crosslistings.
                   5830: #    $client  - The socket open on the client.
                   5831: # Returns:
                   5832: #    1 - continue processing.
                   5833: #
                   5834: 
                   5835: sub validate_classes_handler {
                   5836:     my ($cmd, $tail, $client) = @_;
                   5837:     my $userinput = "$cmd:$tail";
                   5838:     my ($ownerlist,$cdom,$classes) = split(/:/, $tail);
                   5839:     my $classesref = &Apache::lonnet::thaw_unescape($classes);
                   5840:     my $owners = &unescape($ownerlist);
                   5841:     my $result;
                   5842:     eval {
                   5843:         local($SIG{__DIE__})='DEFAULT';
                   5844:         my %validations;
                   5845:         my $response = &localenroll::check_instclasses($owners,$cdom,$classesref,
                   5846:                                                        \%validations);
                   5847:         if ($response eq 'ok') {
                   5848:             foreach my $key (keys(%validations)) {
                   5849:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   5850:             }
                   5851:             $result =~ s/\&$//;
                   5852:         } else {
                   5853:             $result = 'error';
                   5854:         }
                   5855:     };
                   5856:     if (!$@) {
                   5857:         &Reply($client, \$result, $userinput);
                   5858:     } else {
                   5859:         &Failure($client,"unknown_cmd\n",$userinput);
                   5860:     }
                   5861:     return 1;
                   5862: }
                   5863: &register_handler("autovalidateinstclasses", \&validate_classes_handler, 0, 1, 0);
                   5864: 
                   5865: #
1.340     raeburn  5866: #   Create a password for a new LON-CAPA user added by auto-enrollment.
                   5867: #   Only used for case where authentication method for new user is localauth
1.248     foxr     5868: #
                   5869: # Formal Parameters:
                   5870: #    $cmd     - The command request that got us dispatched.
                   5871: #    $tail    - The tail of the command.   In this case this is a colon separated
                   5872: #               set of words that will be split into:
1.340     raeburn  5873: #               $authparam - An authentication parameter (localauth parameter).
1.248     foxr     5874: #               $cdom      - The domain of the course from the institution's
                   5875: #                            point of view.
                   5876: #    $client  - The socket open on the client.
                   5877: # Returns:
                   5878: #    1 - continue processing.
                   5879: #
                   5880: sub create_auto_enroll_password_handler {
                   5881:     my ($cmd, $tail, $client) = @_;
                   5882:     my $userinput = "$cmd:$tail";
                   5883: 
                   5884:     my ($authparam, $cdom) = split(/:/, $userinput);
                   5885: 
                   5886:     my ($create_passwd,$authchk);
                   5887:     ($authparam,
                   5888:      $create_passwd,
                   5889:      $authchk) = &localenroll::create_password($authparam,$cdom);
                   5890: 
                   5891:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
                   5892: 	   $userinput);
                   5893: 
                   5894: 
                   5895:     return 1;
                   5896: }
                   5897: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
                   5898: 		  0, 1, 0);
                   5899: 
1.522     raeburn  5900: sub auto_export_grades_handler {
                   5901:     my ($cmd, $tail, $client) = @_;
                   5902:     my $userinput = "$cmd:$tail";
                   5903:     my ($cdom,$cnum,$info,$data) = split(/:/,$tail);
                   5904:     my $inforef = &Apache::lonnet::thaw_unescape($info);
                   5905:     my $dataref = &Apache::lonnet::thaw_unescape($data);
                   5906:     my ($outcome,$result);;
                   5907:     eval {
                   5908:         local($SIG{__DIE__})='DEFAULT';
                   5909:         my %rtnhash;
                   5910:         $outcome=&localenroll::export_grades($cdom,$cnum,$inforef,$dataref,\%rtnhash);
                   5911:         if ($outcome eq 'ok') {
                   5912:             foreach my $key (keys(%rtnhash)) {
                   5913:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   5914:             }
                   5915:             $result =~ s/\&$//;
                   5916:         }
                   5917:     };
                   5918:     if (!$@) {
                   5919:         if ($outcome eq 'ok') {
                   5920:             if ($cipher) {
                   5921:                 my $cmdlength=length($result);
                   5922:                 $result.="         ";
                   5923:                 my $encresult='';
                   5924:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   5925:                     $encresult.= unpack("H16",
                   5926:                                         $cipher->encrypt(substr($result,
                   5927:                                                                 $encidx,
                   5928:                                                                 8)));
                   5929:                 }
                   5930:                 &Reply( $client, "enc:$cmdlength:$encresult\n", $userinput);
                   5931:             } else {
                   5932:                 &Failure( $client, "error:no_key\n", $userinput);
                   5933:             }
                   5934:         } else {
                   5935:             &Reply($client, "$outcome\n", $userinput);
                   5936:         }
                   5937:     } else {
                   5938:         &Failure($client,"export_error\n",$userinput);
                   5939:     }
                   5940:     return 1;
                   5941: }
                   5942: &register_handler("autoexportgrades", \&auto_export_grades_handler,
1.536     raeburn  5943:                   1, 1, 0);
1.522     raeburn  5944: 
1.248     foxr     5945: #   Retrieve and remove temporary files created by/during autoenrollment.
                   5946: #
                   5947: # Formal Parameters:
                   5948: #    $cmd      - The command that got us dispatched.
                   5949: #    $tail     - The tail of the command.  In our case this is a colon 
                   5950: #                separated list that will be split into:
1.526     raeburn  5951: #                $filename - The name of the file to retrieve.
1.248     foxr     5952: #                            The filename is given as a path relative to
                   5953: #                            the LonCAPA temp file directory.
                   5954: #    $client   - Socket open on the client.
                   5955: #
                   5956: # Returns:
                   5957: #   1     - Continue processing.
                   5958: sub retrieve_auto_file_handler {
                   5959:     my ($cmd, $tail, $client)    = @_;
                   5960:     my $userinput                = "cmd:$tail";
                   5961: 
                   5962:     my ($filename)   = split(/:/, $tail);
                   5963: 
                   5964:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
1.521     raeburn  5965: 
                   5966:     if ($filename =~m{/\.\./}) {
                   5967:         &Failure($client, "refused\n", $userinput);
1.526     raeburn  5968:     } elsif ($filename !~ /^$LONCAPA::match_domain\_$LONCAPA::match_courseid\_.+_classlist\.xml$/) {
                   5969:         &Failure($client, "refused\n", $userinput);
1.521     raeburn  5970:     } elsif ( (-e $source) && ($filename ne '') ) {
1.248     foxr     5971: 	my $reply = '';
                   5972: 	if (open(my $fh,$source)) {
                   5973: 	    while (<$fh>) {
                   5974: 		chomp($_);
                   5975: 		$_ =~ s/^\s+//g;
                   5976: 		$_ =~ s/\s+$//g;
                   5977: 		$reply .= $_;
                   5978: 	    }
                   5979: 	    close($fh);
                   5980: 	    &Reply($client, &escape($reply)."\n", $userinput);
                   5981: 
                   5982: #   Does this have to be uncommented??!?  (RF).
                   5983: #
                   5984: #                                unlink($source);
                   5985: 	} else {
                   5986: 	    &Failure($client, "error\n", $userinput);
                   5987: 	}
                   5988:     } else {
                   5989: 	&Failure($client, "error\n", $userinput);
                   5990:     }
                   5991:     
                   5992: 
                   5993:     return 1;
                   5994: }
                   5995: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
                   5996: 
1.423     raeburn  5997: sub crsreq_checks_handler {
                   5998:     my ($cmd, $tail, $client) = @_;
                   5999:     my $userinput = "$cmd:$tail";
                   6000:     my $dom = $tail;
                   6001:     my $result;
1.519     raeburn  6002:     my @reqtypes = ('official','unofficial','community','textbook','placement');
1.423     raeburn  6003:     eval {
                   6004:         local($SIG{__DIE__})='DEFAULT';
                   6005:         my %validations;
1.424     raeburn  6006:         my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
                   6007:                                                    \%validations);
1.423     raeburn  6008:         if ($response eq 'ok') { 
                   6009:             foreach my $key (keys(%validations)) {
                   6010:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   6011:             }
                   6012:             $result =~ s/\&$//;
                   6013:         } else {
                   6014:             $result = 'error';
                   6015:         }
                   6016:     };
                   6017:     if (!$@) {
                   6018:         &Reply($client, \$result, $userinput);
                   6019:     } else {
                   6020:         &Failure($client,"unknown_cmd\n",$userinput);
                   6021:     }
                   6022:     return 1;
                   6023: }
                   6024: &register_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
                   6025: 
                   6026: sub validate_crsreq_handler {
                   6027:     my ($cmd, $tail, $client) = @_;
                   6028:     my $userinput = "$cmd:$tail";
1.508     raeburn  6029:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
1.423     raeburn  6030:     $instcode = &unescape($instcode);
                   6031:     $owner = &unescape($owner);
                   6032:     $crstype = &unescape($crstype);
                   6033:     $inststatuslist = &unescape($inststatuslist);
                   6034:     $instcode = &unescape($instcode);
                   6035:     $instseclist = &unescape($instseclist);
1.508     raeburn  6036:     my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
1.423     raeburn  6037:     my $outcome;
                   6038:     eval {
                   6039:         local($SIG{__DIE__})='DEFAULT';
                   6040:         $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
                   6041:                                                  $inststatuslist,$instcode,
1.508     raeburn  6042:                                                  $instseclist,$custominfo);
1.423     raeburn  6043:     };
                   6044:     if (!$@) {
                   6045:         &Reply($client, \$outcome, $userinput);
                   6046:     } else {
                   6047:         &Failure($client,"unknown_cmd\n",$userinput);
                   6048:     }
                   6049:     return 1;
                   6050: }
                   6051: &register_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
                   6052: 
1.506     raeburn  6053: sub crsreq_update_handler {
                   6054:     my ($cmd, $tail, $client) = @_;
                   6055:     my $userinput = "$cmd:$tail";
1.509     raeburn  6056:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
                   6057:         $accessstart,$accessend,$infohashref) =
1.506     raeburn  6058:         split(/:/, $tail);
                   6059:     $crstype = &unescape($crstype);
                   6060:     $action = &unescape($action);
                   6061:     $ownername = &unescape($ownername);
                   6062:     $ownerdomain = &unescape($ownerdomain);
                   6063:     $fullname = &unescape($fullname);
                   6064:     $title = &unescape($title);
                   6065:     $code = &unescape($code);
1.509     raeburn  6066:     $accessstart = &unescape($accessstart);
                   6067:     $accessend = &unescape($accessend);
1.506     raeburn  6068:     my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
                   6069:     my ($result,$outcome);
                   6070:     eval {
                   6071:         local($SIG{__DIE__})='DEFAULT';
                   6072:         my %rtnhash;
                   6073:         $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
                   6074:                                                 $ownername,$ownerdomain,$fullname,
1.509     raeburn  6075:                                                 $title,$code,$accessstart,$accessend,
                   6076:                                                 $incoming,\%rtnhash);
1.506     raeburn  6077:         if ($outcome eq 'ok') {
1.515     raeburn  6078:             my @posskeys = qw(createdweb createdmsg createdcustomized createdactions queuedweb queuedmsg formitems reviewweb validationjs onload javascript);
1.506     raeburn  6079:             foreach my $key (keys(%rtnhash)) {
                   6080:                 if (grep(/^\Q$key\E/,@posskeys)) {
                   6081:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   6082:                 }
                   6083:             }
                   6084:             $result =~ s/\&$//;
                   6085:         }
                   6086:     };
                   6087:     if (!$@) {
                   6088:         if ($outcome eq 'ok') {
                   6089:             &Reply($client, \$result, $userinput);
                   6090:         } else {
                   6091:             &Reply($client, "format_error\n", $userinput);
                   6092:         }
                   6093:     } else {
                   6094:         &Failure($client,"unknown_cmd\n",$userinput);
                   6095:     }
                   6096:     return 1;
                   6097: }
                   6098: &register_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
                   6099: 
1.248     foxr     6100: #
                   6101: #   Read and retrieve institutional code format (for support form).
                   6102: # Formal Parameters:
                   6103: #    $cmd        - Command that dispatched us.
                   6104: #    $tail       - Tail of the command.  In this case it conatins 
                   6105: #                  the course domain and the coursename.
                   6106: #    $client     - Socket open on the client.
                   6107: # Returns:
                   6108: #    1     - Continue processing.
                   6109: #
                   6110: sub get_institutional_code_format_handler {
                   6111:     my ($cmd, $tail, $client)   = @_;
                   6112:     my $userinput               = "$cmd:$tail";
                   6113: 
                   6114:     my $reply;
                   6115:     my($cdom,$course) = split(/:/,$tail);
                   6116:     my @pairs = split/\&/,$course;
                   6117:     my %instcodes = ();
                   6118:     my %codes = ();
                   6119:     my @codetitles = ();
                   6120:     my %cat_titles = ();
                   6121:     my %cat_order = ();
                   6122:     foreach (@pairs) {
                   6123: 	my ($key,$value) = split/=/,$_;
                   6124: 	$instcodes{&unescape($key)} = &unescape($value);
                   6125:     }
                   6126:     my $formatreply = &localenroll::instcode_format($cdom,
                   6127: 						    \%instcodes,
                   6128: 						    \%codes,
                   6129: 						    \@codetitles,
                   6130: 						    \%cat_titles,
                   6131: 						    \%cat_order);
                   6132:     if ($formatreply eq 'ok') {
1.365     albertel 6133: 	my $codes_str = &Apache::lonnet::hash2str(%codes);
                   6134: 	my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
                   6135: 	my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
                   6136: 	my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
1.248     foxr     6137: 	&Reply($client,
                   6138: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
                   6139: 	       .$cat_order_str."\n",
                   6140: 	       $userinput);
                   6141:     } else {
                   6142: 	# this else branch added by RF since if not ok, lonc will
                   6143: 	# hang waiting on reply until timeout.
                   6144: 	#
                   6145: 	&Reply($client, "format_error\n", $userinput);
                   6146:     }
                   6147:     
                   6148:     return 1;
                   6149: }
1.265     albertel 6150: &register_handler("autoinstcodeformat",
                   6151: 		  \&get_institutional_code_format_handler,0,1,0);
1.246     foxr     6152: 
1.345     raeburn  6153: sub get_institutional_defaults_handler {
                   6154:     my ($cmd, $tail, $client)   = @_;
                   6155:     my $userinput               = "$cmd:$tail";
                   6156: 
                   6157:     my $dom = $tail;
                   6158:     my %defaults_hash;
                   6159:     my @code_order;
                   6160:     my $outcome;
                   6161:     eval {
                   6162:         local($SIG{__DIE__})='DEFAULT';
                   6163:         $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
                   6164:                                                    \@code_order);
                   6165:     };
                   6166:     if (!$@) {
                   6167:         if ($outcome eq 'ok') {
                   6168:             my $result='';
                   6169:             while (my ($key,$value) = each(%defaults_hash)) {
                   6170:                 $result.=&escape($key).'='.&escape($value).'&';
                   6171:             }
                   6172:             $result .= 'code_order='.&escape(join('&',@code_order));
1.387     albertel 6173:             &Reply($client,\$result,$userinput);
1.345     raeburn  6174:         } else {
                   6175:             &Reply($client,"error\n", $userinput);
                   6176:         }
                   6177:     } else {
                   6178:         &Failure($client,"unknown_cmd\n",$userinput);
                   6179:     }
                   6180: }
                   6181: &register_handler("autoinstcodedefaults",
                   6182:                   \&get_institutional_defaults_handler,0,1,0);
                   6183: 
1.416     raeburn  6184: sub get_possible_instcodes_handler {
                   6185:     my ($cmd, $tail, $client)   = @_;
                   6186:     my $userinput               = "$cmd:$tail";
                   6187: 
                   6188:     my $reply;
                   6189:     my $cdom = $tail;
1.417     raeburn  6190:     my (@codetitles,%cat_titles,%cat_order,@code_order);
1.416     raeburn  6191:     my $formatreply = &localenroll::possible_instcodes($cdom,
                   6192:                                                        \@codetitles,
                   6193:                                                        \%cat_titles,
1.417     raeburn  6194:                                                        \%cat_order,
                   6195:                                                        \@code_order);
1.416     raeburn  6196:     if ($formatreply eq 'ok') {
                   6197:         my $result = join('&',map {&escape($_);} (@codetitles)).':';
1.417     raeburn  6198:         $result .= join('&',map {&escape($_);} (@code_order)).':';
1.416     raeburn  6199:         foreach my $key (keys(%cat_titles)) {
                   6200:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
                   6201:         }
                   6202:         $result =~ s/\&$//;
                   6203:         $result .= ':';
                   6204:         foreach my $key (keys(%cat_order)) {
                   6205:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
                   6206:         }
                   6207:         $result =~ s/\&$//;
                   6208:         &Reply($client,\$result,$userinput);
                   6209:     } else {
                   6210:         &Reply($client, "format_error\n", $userinput);
                   6211:     }
                   6212:     return 1;
                   6213: }
                   6214: &register_handler("autopossibleinstcodes",
                   6215:                   \&get_possible_instcodes_handler,0,1,0);
                   6216: 
1.381     raeburn  6217: sub get_institutional_user_rules {
                   6218:     my ($cmd, $tail, $client)   = @_;
                   6219:     my $userinput               = "$cmd:$tail";
                   6220:     my $dom = &unescape($tail);
                   6221:     my (%rules_hash,@rules_order);
                   6222:     my $outcome;
                   6223:     eval {
                   6224:         local($SIG{__DIE__})='DEFAULT';
                   6225:         $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
                   6226:     };
                   6227:     if (!$@) {
                   6228:         if ($outcome eq 'ok') {
                   6229:             my $result;
                   6230:             foreach my $key (keys(%rules_hash)) {
                   6231:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6232:             }
                   6233:             $result =~ s/\&$//;
                   6234:             $result .= ':';
                   6235:             if (@rules_order > 0) {
                   6236:                 foreach my $item (@rules_order) {
                   6237:                     $result .= &escape($item).'&';
                   6238:                 }
                   6239:             }
                   6240:             $result =~ s/\&$//;
1.387     albertel 6241:             &Reply($client,\$result,$userinput);
1.381     raeburn  6242:         } else {
                   6243:             &Reply($client,"error\n", $userinput);
                   6244:         }
                   6245:     } else {
                   6246:         &Failure($client,"unknown_cmd\n",$userinput);
                   6247:     }
                   6248: }
                   6249: &register_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
                   6250: 
1.389     raeburn  6251: sub get_institutional_id_rules {
                   6252:     my ($cmd, $tail, $client)   = @_;
                   6253:     my $userinput               = "$cmd:$tail";
                   6254:     my $dom = &unescape($tail);
                   6255:     my (%rules_hash,@rules_order);
                   6256:     my $outcome;
                   6257:     eval {
                   6258:         local($SIG{__DIE__})='DEFAULT';
                   6259:         $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
                   6260:     };
                   6261:     if (!$@) {
                   6262:         if ($outcome eq 'ok') {
                   6263:             my $result;
                   6264:             foreach my $key (keys(%rules_hash)) {
                   6265:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6266:             }
                   6267:             $result =~ s/\&$//;
                   6268:             $result .= ':';
                   6269:             if (@rules_order > 0) {
                   6270:                 foreach my $item (@rules_order) {
                   6271:                     $result .= &escape($item).'&';
                   6272:                 }
                   6273:             }
                   6274:             $result =~ s/\&$//;
                   6275:             &Reply($client,\$result,$userinput);
                   6276:         } else {
                   6277:             &Reply($client,"error\n", $userinput);
                   6278:         }
                   6279:     } else {
                   6280:         &Failure($client,"unknown_cmd\n",$userinput);
                   6281:     }
                   6282: }
                   6283: &register_handler("instidrules",\&get_institutional_id_rules,0,1,0);
                   6284: 
1.397     raeburn  6285: sub get_institutional_selfcreate_rules {
1.396     raeburn  6286:     my ($cmd, $tail, $client)   = @_;
                   6287:     my $userinput               = "$cmd:$tail";
                   6288:     my $dom = &unescape($tail);
                   6289:     my (%rules_hash,@rules_order);
                   6290:     my $outcome;
                   6291:     eval {
                   6292:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6293:         $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
1.396     raeburn  6294:     };
                   6295:     if (!$@) {
                   6296:         if ($outcome eq 'ok') {
                   6297:             my $result;
                   6298:             foreach my $key (keys(%rules_hash)) {
                   6299:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6300:             }
                   6301:             $result =~ s/\&$//;
                   6302:             $result .= ':';
                   6303:             if (@rules_order > 0) {
                   6304:                 foreach my $item (@rules_order) {
                   6305:                     $result .= &escape($item).'&';
                   6306:                 }
                   6307:             }
                   6308:             $result =~ s/\&$//;
                   6309:             &Reply($client,\$result,$userinput);
                   6310:         } else {
                   6311:             &Reply($client,"error\n", $userinput);
                   6312:         }
                   6313:     } else {
                   6314:         &Failure($client,"unknown_cmd\n",$userinput);
                   6315:     }
                   6316: }
1.397     raeburn  6317: &register_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
1.396     raeburn  6318: 
1.381     raeburn  6319: 
                   6320: sub institutional_username_check {
                   6321:     my ($cmd, $tail, $client)   = @_;
                   6322:     my $userinput               = "$cmd:$tail";
                   6323:     my %rulecheck;
                   6324:     my $outcome;
                   6325:     my ($udom,$uname,@rules) = split(/:/,$tail);
                   6326:     $udom = &unescape($udom);
                   6327:     $uname = &unescape($uname);
                   6328:     @rules = map {&unescape($_);} (@rules);
                   6329:     eval {
                   6330:         local($SIG{__DIE__})='DEFAULT';
                   6331:         $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
                   6332:     };
                   6333:     if (!$@) {
                   6334:         if ($outcome eq 'ok') {
                   6335:             my $result='';
                   6336:             foreach my $key (keys(%rulecheck)) {
                   6337:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6338:             }
1.387     albertel 6339:             &Reply($client,\$result,$userinput);
1.381     raeburn  6340:         } else {
                   6341:             &Reply($client,"error\n", $userinput);
                   6342:         }
                   6343:     } else {
                   6344:         &Failure($client,"unknown_cmd\n",$userinput);
                   6345:     }
                   6346: }
                   6347: &register_handler("instrulecheck",\&institutional_username_check,0,1,0);
                   6348: 
1.389     raeburn  6349: sub institutional_id_check {
                   6350:     my ($cmd, $tail, $client)   = @_;
                   6351:     my $userinput               = "$cmd:$tail";
                   6352:     my %rulecheck;
                   6353:     my $outcome;
                   6354:     my ($udom,$id,@rules) = split(/:/,$tail);
                   6355:     $udom = &unescape($udom);
                   6356:     $id = &unescape($id);
                   6357:     @rules = map {&unescape($_);} (@rules);
                   6358:     eval {
                   6359:         local($SIG{__DIE__})='DEFAULT';
                   6360:         $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
                   6361:     };
                   6362:     if (!$@) {
                   6363:         if ($outcome eq 'ok') {
                   6364:             my $result='';
                   6365:             foreach my $key (keys(%rulecheck)) {
                   6366:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6367:             }
                   6368:             &Reply($client,\$result,$userinput);
                   6369:         } else {
                   6370:             &Reply($client,"error\n", $userinput);
                   6371:         }
                   6372:     } else {
                   6373:         &Failure($client,"unknown_cmd\n",$userinput);
                   6374:     }
                   6375: }
                   6376: &register_handler("instidrulecheck",\&institutional_id_check,0,1,0);
1.345     raeburn  6377: 
1.397     raeburn  6378: sub institutional_selfcreate_check {
1.396     raeburn  6379:     my ($cmd, $tail, $client)   = @_;
                   6380:     my $userinput               = "$cmd:$tail";
                   6381:     my %rulecheck;
                   6382:     my $outcome;
                   6383:     my ($udom,$email,@rules) = split(/:/,$tail);
                   6384:     $udom = &unescape($udom);
                   6385:     $email = &unescape($email);
                   6386:     @rules = map {&unescape($_);} (@rules);
                   6387:     eval {
                   6388:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6389:         $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
1.396     raeburn  6390:     };
                   6391:     if (!$@) {
                   6392:         if ($outcome eq 'ok') {
                   6393:             my $result='';
                   6394:             foreach my $key (keys(%rulecheck)) {
                   6395:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6396:             }
                   6397:             &Reply($client,\$result,$userinput);
                   6398:         } else {
                   6399:             &Reply($client,"error\n", $userinput);
                   6400:         }
                   6401:     } else {
                   6402:         &Failure($client,"unknown_cmd\n",$userinput);
                   6403:     }
                   6404: }
1.397     raeburn  6405: &register_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
1.396     raeburn  6406: 
1.317     raeburn  6407: # Get domain specific conditions for import of student photographs to a course
                   6408: #
                   6409: # Retrieves information from photo_permission subroutine in localenroll.
                   6410: # Returns outcome (ok) if no processing errors, and whether course owner is 
                   6411: # required to accept conditions of use (yes/no).
                   6412: #
                   6413: #    
                   6414: sub photo_permission_handler {
                   6415:     my ($cmd, $tail, $client)   = @_;
                   6416:     my $userinput               = "$cmd:$tail";
                   6417:     my $cdom = $tail;
                   6418:     my ($perm_reqd,$conditions);
1.320     albertel 6419:     my $outcome;
                   6420:     eval {
                   6421: 	local($SIG{__DIE__})='DEFAULT';
                   6422: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
                   6423: 						  \$conditions);
                   6424:     };
                   6425:     if (!$@) {
                   6426: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
                   6427: 	       $userinput);
                   6428:     } else {
                   6429: 	&Failure($client,"unknown_cmd\n",$userinput);
                   6430:     }
                   6431:     return 1;
1.317     raeburn  6432: }
                   6433: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
                   6434: 
                   6435: #
                   6436: # Checks if student photo is available for a user in the domain, in the user's
                   6437: # directory (in /userfiles/internal/studentphoto.jpg).
                   6438: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
                   6439: # the student's photo.   
                   6440: 
                   6441: sub photo_check_handler {
                   6442:     my ($cmd, $tail, $client)   = @_;
                   6443:     my $userinput               = "$cmd:$tail";
                   6444:     my ($udom,$uname,$pid) = split(/:/,$tail);
                   6445:     $udom = &unescape($udom);
                   6446:     $uname = &unescape($uname);
                   6447:     $pid = &unescape($pid);
                   6448:     my $path=&propath($udom,$uname).'/userfiles/internal/';
                   6449:     if (!-e $path) {
                   6450:         &mkpath($path);
                   6451:     }
                   6452:     my $response;
                   6453:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
                   6454:     $result .= ':'.$response;
                   6455:     &Reply($client, &escape($result)."\n",$userinput);
1.320     albertel 6456:     return 1;
1.317     raeburn  6457: }
                   6458: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
                   6459: 
                   6460: #
                   6461: # Retrieve information from localenroll about whether to provide a button     
                   6462: # for users who have enbled import of student photos to initiate an 
                   6463: # update of photo files for registered students. Also include 
                   6464: # comment to display alongside button.  
                   6465: 
                   6466: sub photo_choice_handler {
                   6467:     my ($cmd, $tail, $client) = @_;
                   6468:     my $userinput             = "$cmd:$tail";
                   6469:     my $cdom                  = &unescape($tail);
1.320     albertel 6470:     my ($update,$comment);
                   6471:     eval {
                   6472: 	local($SIG{__DIE__})='DEFAULT';
                   6473: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
                   6474:     };
                   6475:     if (!$@) {
                   6476: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
                   6477:     } else {
                   6478: 	&Failure($client,"unknown_cmd\n",$userinput);
                   6479:     }
                   6480:     return 1;
1.317     raeburn  6481: }
                   6482: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
                   6483: 
1.265     albertel 6484: #
                   6485: # Gets a student's photo to exist (in the correct image type) in the user's 
                   6486: # directory.
                   6487: # Formal Parameters:
                   6488: #    $cmd     - The command request that got us dispatched.
                   6489: #    $tail    - A colon separated set of words that will be split into:
                   6490: #               $domain - student's domain
                   6491: #               $uname  - student username
                   6492: #               $type   - image type desired
                   6493: #    $client  - The socket open on the client.
                   6494: # Returns:
                   6495: #    1 - continue processing.
1.317     raeburn  6496: 
1.265     albertel 6497: sub student_photo_handler {
                   6498:     my ($cmd, $tail, $client) = @_;
1.317     raeburn  6499:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
1.265     albertel 6500: 
1.317     raeburn  6501:     my $path=&propath($domain,$uname). '/userfiles/internal/';
                   6502:     my $filename = 'studentphoto.'.$ext;
                   6503:     if ($type eq 'thumbnail') {
                   6504:         $filename = 'studentphoto_tn.'.$ext;
                   6505:     }
                   6506:     if (-e $path.$filename) {
1.265     albertel 6507: 	&Reply($client,"ok\n","$cmd:$tail");
                   6508: 	return 1;
                   6509:     }
                   6510:     &mkpath($path);
1.317     raeburn  6511:     my $file;
                   6512:     if ($type eq 'thumbnail') {
1.320     albertel 6513: 	eval {
                   6514: 	    local($SIG{__DIE__})='DEFAULT';
                   6515: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
                   6516: 	};
1.317     raeburn  6517:     } else {
                   6518:         $file=&localstudentphoto::fetch($domain,$uname);
                   6519:     }
1.265     albertel 6520:     if (!$file) {
                   6521: 	&Failure($client,"unavailable\n","$cmd:$tail");
                   6522: 	return 1;
                   6523:     }
1.317     raeburn  6524:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
                   6525:     if (-e $path.$filename) {
1.265     albertel 6526: 	&Reply($client,"ok\n","$cmd:$tail");
                   6527: 	return 1;
                   6528:     }
                   6529:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
                   6530:     return 1;
                   6531: }
                   6532: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246     foxr     6533: 
1.361     raeburn  6534: sub inst_usertypes_handler {
                   6535:     my ($cmd, $domain, $client) = @_;
                   6536:     my $res;
                   6537:     my $userinput = $cmd.":".$domain; # For logging purposes.
1.370     albertel 6538:     my (%typeshash,@order,$result);
                   6539:     eval {
                   6540: 	local($SIG{__DIE__})='DEFAULT';
                   6541: 	$result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
                   6542:     };
                   6543:     if ($result eq 'ok') {
1.361     raeburn  6544:         if (keys(%typeshash) > 0) {
                   6545:             foreach my $key (keys(%typeshash)) {
                   6546:                 $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
                   6547:             }
                   6548:         }
                   6549:         $res=~s/\&$//;
                   6550:         $res .= ':';
                   6551:         if (@order > 0) {
                   6552:             foreach my $item (@order) {
                   6553:                 $res .= &escape($item).'&';
                   6554:             }
                   6555:         }
                   6556:         $res=~s/\&$//;
                   6557:     }
1.387     albertel 6558:     &Reply($client, \$res, $userinput);
1.361     raeburn  6559:     return 1;
                   6560: }
                   6561: &register_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
                   6562: 
1.264     albertel 6563: # mkpath makes all directories for a file, expects an absolute path with a
                   6564: # file or a trailing / if just a dir is passed
                   6565: # returns 1 on success 0 on failure
                   6566: sub mkpath {
                   6567:     my ($file)=@_;
                   6568:     my @parts=split(/\//,$file,-1);
                   6569:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
                   6570:     for (my $i=3;$i<= ($#parts-1);$i++) {
1.265     albertel 6571: 	$now.='/'.$parts[$i]; 
1.264     albertel 6572: 	if (!-e $now) {
                   6573: 	    if  (!mkdir($now,0770)) { return 0; }
                   6574: 	}
                   6575:     }
                   6576:     return 1;
                   6577: }
                   6578: 
1.207     foxr     6579: #---------------------------------------------------------------
                   6580: #
                   6581: #   Getting, decoding and dispatching requests:
                   6582: #
                   6583: #
                   6584: #   Get a Request:
                   6585: #   Gets a Request message from the client.  The transaction
                   6586: #   is defined as a 'line' of text.  We remove the new line
                   6587: #   from the text line.  
1.226     foxr     6588: #
1.211     albertel 6589: sub get_request {
1.207     foxr     6590:     my $input = <$client>;
                   6591:     chomp($input);
1.226     foxr     6592: 
1.234     foxr     6593:     &Debug("get_request: Request = $input\n");
1.207     foxr     6594: 
                   6595:     &status('Processing '.$clientname.':'.$input);
                   6596: 
                   6597:     return $input;
                   6598: }
1.212     foxr     6599: #---------------------------------------------------------------
                   6600: #
                   6601: #  Process a request.  This sub should shrink as each action
                   6602: #  gets farmed out into a separat sub that is registered 
                   6603: #  with the dispatch hash.  
                   6604: #
                   6605: # Parameters:
                   6606: #    user_input   - The request received from the client (lonc).
1.525     raeburn  6607: #
1.212     foxr     6608: # Returns:
                   6609: #    true to keep processing, false if caller should exit.
                   6610: #
                   6611: sub process_request {
1.525     raeburn  6612:     my ($userinput) = @_; # Easier for now to break style than to
                   6613:                           # fix all the userinput -> user_input.
1.212     foxr     6614:     my $wasenc    = 0;		# True if request was encrypted.
                   6615: # ------------------------------------------------------------ See if encrypted
1.322     albertel 6616:     # for command
                   6617:     # sethost:<server>
                   6618:     # <command>:<args>
                   6619:     #   we just send it to the processor
                   6620:     # for
                   6621:     # sethost:<server>:<command>:<args>
                   6622:     #  we do the implict set host and then do the command
                   6623:     if ($userinput =~ /^sethost:/) {
                   6624: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
                   6625: 	if (defined($userinput)) {
                   6626: 	    &sethost("$cmd:$newid");
                   6627: 	} else {
                   6628: 	    $userinput = "$cmd:$newid";
                   6629: 	}
                   6630:     }
                   6631: 
1.212     foxr     6632:     if ($userinput =~ /^enc/) {
                   6633: 	$userinput = decipher($userinput);
                   6634: 	$wasenc=1;
                   6635: 	if(!$userinput) {	# Cipher not defined.
1.251     foxr     6636: 	    &Failure($client, "error: Encrypted data without negotated key\n");
1.212     foxr     6637: 	    return 0;
                   6638: 	}
                   6639:     }
                   6640:     Debug("process_request: $userinput\n");
                   6641:     
1.213     foxr     6642:     #  
                   6643:     #   The 'correct way' to add a command to lond is now to
                   6644:     #   write a sub to execute it and Add it to the command dispatch
                   6645:     #   hash via a call to register_handler..  The comments to that
                   6646:     #   sub should give you enough to go on to show how to do this
                   6647:     #   along with the examples that are building up as this code
                   6648:     #   is getting refactored.   Until all branches of the
                   6649:     #   if/elseif monster below have been factored out into
                   6650:     #   separate procesor subs, if the dispatch hash is missing
                   6651:     #   the command keyword, we will fall through to the remainder
                   6652:     #   of the if/else chain below in order to keep this thing in 
                   6653:     #   working order throughout the transmogrification.
                   6654: 
                   6655:     my ($command, $tail) = split(/:/, $userinput, 2);
                   6656:     chomp($command);
                   6657:     chomp($tail);
                   6658:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
1.214     foxr     6659:     $command =~ s/(\r)//;	# And this too for parameterless commands.
                   6660:     if(!$tail) {
                   6661: 	$tail ="";		# defined but blank.
                   6662:     }
1.213     foxr     6663: 
                   6664:     &Debug("Command received: $command, encoded = $wasenc");
                   6665: 
                   6666:     if(defined $Dispatcher{$command}) {
                   6667: 
                   6668: 	my $dispatch_info = $Dispatcher{$command};
                   6669: 	my $handler       = $$dispatch_info[0];
                   6670: 	my $need_encode   = $$dispatch_info[1];
                   6671: 	my $client_types  = $$dispatch_info[2];
                   6672: 	Debug("Matched dispatch hash: mustencode: $need_encode "
                   6673: 	      ."ClientType $client_types");
                   6674:       
                   6675: 	#  Validate the request:
                   6676:       
                   6677: 	my $ok = 1;
                   6678: 	my $requesterprivs = 0;
                   6679: 	if(&isClient()) {
                   6680: 	    $requesterprivs |= $CLIENT_OK;
                   6681: 	}
                   6682: 	if(&isManager()) {
                   6683: 	    $requesterprivs |= $MANAGER_OK;
                   6684: 	}
                   6685: 	if($need_encode && (!$wasenc)) {
                   6686: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
                   6687: 	    $ok = 0;
                   6688: 	}
                   6689: 	if(($client_types & $requesterprivs) == 0) {
                   6690: 	    Debug("Client not privileged to do this operation");
                   6691: 	    $ok = 0;
                   6692: 	}
1.525     raeburn  6693:         if ($ok) {
1.535     raeburn  6694:             my $realcommand = $command;
                   6695:             if ($command eq 'querysend') {
                   6696:                 my ($query,$rest)=split(/\:/,$tail,2);
                   6697:                 $query=~s/\n*$//g;
                   6698:                 my @possqueries = 
                   6699:                     qw(userlog courselog fetchenrollment institutionalphotos usersearch instdirsearch getinstuser getmultinstusers);
                   6700:                 if (grep(/^\Q$query\E$/,@possqueries)) {
                   6701:                     $command .= '_'.$query;
                   6702:                 } elsif ($query eq 'prepare activity log') {
                   6703:                     $command .= '_activitylog';
                   6704:                 }
                   6705:             }
1.525     raeburn  6706:             if (ref($trust{$command}) eq 'HASH') {
                   6707:                 my $donechecks;
                   6708:                 if ($trust{$command}{'anywhere'}) {
                   6709:                    $donechecks = 1;
                   6710:                 } elsif ($trust{$command}{'manageronly'}) {
                   6711:                     unless (&isManager()) {
                   6712:                         $ok = 0;
                   6713:                     }
                   6714:                     $donechecks = 1;
                   6715:                 } elsif ($trust{$command}{'institutiononly'}) {
                   6716:                     unless ($clientsameinst) {
                   6717:                         $ok = 0;
                   6718:                     }
                   6719:                     $donechecks = 1;
                   6720:                 } elsif ($clientsameinst) {
                   6721:                     $donechecks = 1;
                   6722:                 }
                   6723:                 unless ($donechecks) {
                   6724:                     foreach my $rule (keys(%{$trust{$command}})) {
                   6725:                         next if ($rule eq 'remote');
                   6726:                         if ($trust{$command}{$rule}) {
                   6727:                             if ($clientprohibited{$rule}) {
                   6728:                                 $ok = 0;
                   6729:                             } else {
                   6730:                                 $ok = 1;
                   6731:                                 $donechecks = 1;
                   6732:                                 last;
                   6733:                             }
                   6734:                         }
                   6735:                     }
                   6736:                 }
                   6737:                 unless ($donechecks) {
                   6738:                     if ($trust{$command}{'remote'}) {
                   6739:                         if ($clientremoteok) {
                   6740:                             $ok = 1;
                   6741:                         } else {
                   6742:                             $ok = 0;
                   6743:                         } 
                   6744:                     }
                   6745:                 }
                   6746:             }
1.535     raeburn  6747:             $command = $realcommand;
1.525     raeburn  6748:         }
1.213     foxr     6749: 
                   6750: 	if($ok) {
                   6751: 	    Debug("Dispatching to handler $command $tail");
                   6752: 	    my $keep_going = &$handler($command, $tail, $client);
                   6753: 	    return $keep_going;
                   6754: 	} else {
                   6755: 	    Debug("Refusing to dispatch because client did not match requirements");
                   6756: 	    Failure($client, "refused\n", $userinput);
                   6757: 	    return 1;
                   6758: 	}
1.525     raeburn  6759:     }
1.213     foxr     6760: 
1.262     foxr     6761:     print $client "unknown_cmd\n";
1.212     foxr     6762: # -------------------------------------------------------------------- complete
                   6763:     Debug("process_request - returning 1");
                   6764:     return 1;
                   6765: }
1.207     foxr     6766: #
                   6767: #   Decipher encoded traffic
                   6768: #  Parameters:
                   6769: #     input      - Encoded data.
                   6770: #  Returns:
                   6771: #     Decoded data or undef if encryption key was not yet negotiated.
                   6772: #  Implicit input:
                   6773: #     cipher  - This global holds the negotiated encryption key.
                   6774: #
1.211     albertel 6775: sub decipher {
1.207     foxr     6776:     my ($input)  = @_;
                   6777:     my $output = '';
1.212     foxr     6778:     
                   6779:     
1.207     foxr     6780:     if($cipher) {
                   6781: 	my($enc, $enclength, $encinput) = split(/:/, $input);
                   6782: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
                   6783: 	    $output .= 
                   6784: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
                   6785: 	}
                   6786: 	return substr($output, 0, $enclength);
                   6787:     } else {
                   6788: 	return undef;
                   6789:     }
                   6790: }
                   6791: 
                   6792: #
                   6793: #   Register a command processor.  This function is invoked to register a sub
                   6794: #   to process a request.  Once registered, the ProcessRequest sub can automatically
                   6795: #   dispatch requests to an appropriate sub, and do the top level validity checking
                   6796: #   as well:
                   6797: #    - Is the keyword recognized.
                   6798: #    - Is the proper client type attempting the request.
                   6799: #    - Is the request encrypted if it has to be.
                   6800: #   Parameters:
                   6801: #    $request_name         - Name of the request being registered.
                   6802: #                           This is the command request that will match
                   6803: #                           against the hash keywords to lookup the information
                   6804: #                           associated with the dispatch information.
                   6805: #    $procedure           - Reference to a sub to call to process the request.
                   6806: #                           All subs get called as follows:
                   6807: #                             Procedure($cmd, $tail, $replyfd, $key)
                   6808: #                             $cmd    - the actual keyword that invoked us.
                   6809: #                             $tail   - the tail of the request that invoked us.
                   6810: #                             $replyfd- File descriptor connected to the client
                   6811: #    $must_encode          - True if the request must be encoded to be good.
                   6812: #    $client_ok            - True if it's ok for a client to request this.
                   6813: #    $manager_ok           - True if it's ok for a manager to request this.
                   6814: # Side effects:
                   6815: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
                   6816: #      - On failure, the program will die as it's a bad internal bug to try to 
                   6817: #        register a duplicate command handler.
                   6818: #
1.211     albertel 6819: sub register_handler {
1.212     foxr     6820:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
1.207     foxr     6821: 
                   6822:     #  Don't allow duplication#
                   6823:    
                   6824:     if (defined $Dispatcher{$request_name}) {
                   6825: 	die "Attempting to define a duplicate request handler for $request_name\n";
                   6826:     }
                   6827:     #   Build the client type mask:
                   6828:     
                   6829:     my $client_type_mask = 0;
                   6830:     if($client_ok) {
                   6831: 	$client_type_mask  |= $CLIENT_OK;
                   6832:     }
                   6833:     if($manager_ok) {
                   6834: 	$client_type_mask  |= $MANAGER_OK;
                   6835:     }
                   6836:    
                   6837:     #  Enter the hash:
                   6838:       
                   6839:     my @entry = ($procedure, $must_encode, $client_type_mask);
                   6840:    
                   6841:     $Dispatcher{$request_name} = \@entry;
                   6842:    
                   6843: }
                   6844: 
                   6845: 
                   6846: #------------------------------------------------------------------
                   6847: 
                   6848: 
                   6849: 
                   6850: 
1.141     foxr     6851: #
1.96      foxr     6852: #  Convert an error return code from lcpasswd to a string value.
                   6853: #
                   6854: sub lcpasswdstrerror {
                   6855:     my $ErrorCode = shift;
1.97      foxr     6856:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     6857: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   6858:     } else {
1.98      foxr     6859: 	return $passwderrors[$ErrorCode];
1.96      foxr     6860:     }
                   6861: }
                   6862: 
1.23      harris41 6863: # grabs exception and records it to log before exiting
                   6864: sub catchexception {
1.27      albertel 6865:     my ($error)=@_;
1.25      www      6866:     $SIG{'QUIT'}='DEFAULT';
                   6867:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 6868:     &status("Catching exception");
1.190     albertel 6869:     &logthis("<font color='red'>CRITICAL: "
1.373     albertel 6870:      ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
1.27      albertel 6871:      ."a crash with this error msg->[$error]</font>");
1.57      www      6872:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 6873:     if ($client) { print $client "error: $error\n"; }
1.59      www      6874:     $server->close();
1.27      albertel 6875:     die($error);
1.23      harris41 6876: }
1.63      www      6877: sub timeout {
1.165     albertel 6878:     &status("Handling Timeout");
1.190     albertel 6879:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63      www      6880:     &catchexception('Timeout');
                   6881: }
1.22      harris41 6882: # -------------------------------- Set signal handlers to record abnormal exits
                   6883: 
1.226     foxr     6884: 
1.22      harris41 6885: $SIG{'QUIT'}=\&catchexception;
                   6886: $SIG{__DIE__}=\&catchexception;
                   6887: 
1.81      matthew  6888: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 6889: &status("Read loncapa.conf and loncapa_apache.conf");
                   6890: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     6891: %perlvar=%{$perlvarref};
1.80      harris41 6892: undef $perlvarref;
1.19      www      6893: 
1.35      harris41 6894: # ----------------------------- Make sure this process is running from user=www
                   6895: my $wwwid=getpwnam('www');
                   6896: if ($wwwid!=$<) {
1.134     albertel 6897:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   6898:    my $subj="LON: $currenthostid User ID mismatch";
1.37      harris41 6899:    system("echo 'User ID mismatch.  lond must be run as user www.' |\
1.35      harris41 6900:  mailto $emailto -s '$subj' > /dev/null");
                   6901:    exit 1;
                   6902: }
                   6903: 
1.19      www      6904: # --------------------------------------------- Check if other instance running
                   6905: 
                   6906: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   6907: 
                   6908: if (-e $pidfile) {
                   6909:    my $lfh=IO::File->new("$pidfile");
                   6910:    my $pide=<$lfh>;
                   6911:    chomp($pide);
1.29      harris41 6912:    if (kill 0 => $pide) { die "already running"; }
1.19      www      6913: }
1.1       albertel 6914: 
                   6915: # ------------------------------------------------------------- Read hosts file
                   6916: 
                   6917: 
                   6918: 
                   6919: # establish SERVER socket, bind and listen.
                   6920: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   6921:                                 Type      => SOCK_STREAM,
                   6922:                                 Proto     => 'tcp',
1.469     foxr     6923:                                 ReuseAddr     => 1,
1.1       albertel 6924:                                 Listen    => 10 )
1.29      harris41 6925:   or die "making socket: $@\n";
1.1       albertel 6926: 
                   6927: # --------------------------------------------------------- Do global variables
                   6928: 
                   6929: # global variables
                   6930: 
1.134     albertel 6931: my %children               = ();       # keys are current child process IDs
1.1       albertel 6932: 
                   6933: sub REAPER {                        # takes care of dead children
                   6934:     $SIG{CHLD} = \&REAPER;
1.165     albertel 6935:     &status("Handling child death");
1.178     foxr     6936:     my $pid;
                   6937:     do {
                   6938: 	$pid = waitpid(-1,&WNOHANG());
                   6939: 	if (defined($children{$pid})) {
                   6940: 	    &logthis("Child $pid died");
                   6941: 	    delete($children{$pid});
1.183     albertel 6942: 	} elsif ($pid > 0) {
1.178     foxr     6943: 	    &logthis("Unknown Child $pid died");
                   6944: 	}
                   6945:     } while ( $pid > 0 );
                   6946:     foreach my $child (keys(%children)) {
                   6947: 	$pid = waitpid($child,&WNOHANG());
                   6948: 	if ($pid > 0) {
                   6949: 	    &logthis("Child $child - $pid looks like we missed it's death");
                   6950: 	    delete($children{$pid});
                   6951: 	}
1.176     albertel 6952:     }
1.165     albertel 6953:     &status("Finished Handling child death");
1.1       albertel 6954: }
                   6955: 
                   6956: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 6957:     &status("Killing children (INT)");
1.1       albertel 6958:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   6959:     kill 'INT' => keys %children;
1.59      www      6960:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 6961:     my $execdir=$perlvar{'lonDaemons'};
                   6962:     unlink("$execdir/logs/lond.pid");
1.190     albertel 6963:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165     albertel 6964:     &status("Done killing children");
1.1       albertel 6965:     exit;                           # clean up with dignity
                   6966: }
                   6967: 
                   6968: sub HUPSMAN {                      # signal handler for SIGHUP
                   6969:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 6970:     &status("Killing children for restart (HUP)");
1.1       albertel 6971:     kill 'INT' => keys %children;
1.59      www      6972:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190     albertel 6973:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134     albertel 6974:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 6975:     unlink("$execdir/logs/lond.pid");
1.165     albertel 6976:     &status("Restarting self (HUP)");
1.1       albertel 6977:     exec("$execdir/lond");         # here we go again
                   6978: }
                   6979: 
1.144     foxr     6980: #
1.148     foxr     6981: #  Reload the Apache daemon's state.
1.150     foxr     6982: #  This is done by invoking /home/httpd/perl/apachereload
                   6983: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     6984: #
                   6985: sub ReloadApache {
1.473     raeburn  6986: # --------------------------- Handle case of another apachereload process (locking)
1.474     raeburn  6987:     if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
                   6988:         my $execdir = $perlvar{'lonDaemons'};
                   6989:         my $script  = $execdir."/apachereload";
                   6990:         system($script);
                   6991:         unlink('/tmp/lock_apachereload'); #  Remove the lock file.
                   6992:     }
1.148     foxr     6993: }
                   6994: 
                   6995: #
1.144     foxr     6996: #   Called in response to a USR2 signal.
                   6997: #   - Reread hosts.tab
                   6998: #   - All children connected to hosts that were removed from hosts.tab
                   6999: #     are killed via SIGINT
                   7000: #   - All children connected to previously existing hosts are sent SIGUSR1
                   7001: #   - Our internal hosts hash is updated to reflect the new contents of
                   7002: #     hosts.tab causing connections from hosts added to hosts.tab to
                   7003: #     now be honored.
                   7004: #
                   7005: sub UpdateHosts {
1.165     albertel 7006:     &status("Reload hosts.tab");
1.147     foxr     7007:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     7008:     #
                   7009:     #  The %children hash has the set of IP's we currently have children
                   7010:     #  on.  These need to be matched against records in the hosts.tab
                   7011:     #  Any ip's no longer in the table get killed off they correspond to
                   7012:     #  either dropped or changed hosts.  Note that the re-read of the table
                   7013:     #  will take care of new and changed hosts as connections come into being.
                   7014: 
1.371     albertel 7015:     &Apache::lonnet::reset_hosts_info();
1.532     raeburn  7016:     my %active;
1.148     foxr     7017: 
1.368     albertel 7018:     foreach my $child (keys(%children)) {
1.148     foxr     7019: 	my $childip = $children{$child};
1.374     albertel 7020: 	if ($childip ne '127.0.0.1'
                   7021: 	    && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
1.149     foxr     7022: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   7023: 		    ." $child for ip $childip </font>");
1.148     foxr     7024: 	    kill('INT', $child);
1.149     foxr     7025: 	} else {
1.532     raeburn  7026:             $active{$child} = $childip;
1.149     foxr     7027: 	    logthis('<font color="green"> keeping child for ip '
                   7028: 		    ." $childip (pid=$child) </font>");
1.148     foxr     7029: 	}
                   7030:     }
1.532     raeburn  7031: 
                   7032:     my %oldconf = %secureconf;
                   7033:     my %connchange;
1.545     raeburn  7034:     if (lonssl::Read_Connect_Config(\%secureconf,\%crlchecked,\%perlvar) eq 'ok') {
                   7035:         logthis('<font color="blue"> Reloaded SSL connection rules and cleared CRL checking history </font>');
1.532     raeburn  7036:     } else {
1.545     raeburn  7037:         logthis('<font color="yellow"> Failed to reload SSL connection rules and clear CRL checking history </font>');
1.532     raeburn  7038:     }
                   7039:     if ((ref($oldconf{'connfrom'}) eq 'HASH') && (ref($secureconf{'connfrom'}) eq 'HASH')) {
                   7040:         foreach my $type ('dom','intdom','other') {
                   7041:             if ((($oldconf{'connfrom'}{$type} eq 'no') && ($secureconf{'connfrom'}{$type} eq 'req')) ||
                   7042:                 (($oldconf{'connfrom'}{$type} eq 'req') && ($secureconf{'connfrom'}{$type} eq 'no'))) {
                   7043:                 $connchange{$type} = 1;
                   7044:             }
                   7045:         }
                   7046:     }
                   7047:     if (keys(%connchange)) {
                   7048:         foreach my $child (keys(%active)) {
                   7049:             my $childip = $active{$child};
                   7050:             if ($childip ne '127.0.0.1') {
                   7051:                 my $childhostname  = gethostbyaddr(Socket::inet_aton($childip),AF_INET);
                   7052:                 if ($childhostname ne '') {
                   7053:                     my $childlonhost = &Apache::lonnet::get_server_homeID($childhostname);
                   7054:                     my ($samedom,$sameinst) = &set_client_info($childlonhost);
                   7055:                     if ($samedom) {
                   7056:                         if ($connchange{'dom'}) {
                   7057:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7058:                                    ." $child for ip $childip </font>");
                   7059:                             kill('INT', $child);
                   7060:                         }
                   7061:                     } elsif ($sameinst) {
                   7062:                         if ($connchange{'intdom'}) {
                   7063:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7064:                                    ." $child for ip $childip </font>");
                   7065:                            kill('INT', $child);
                   7066:                         }
                   7067:                     } else {
                   7068:                         if ($connchange{'other'}) {
                   7069:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7070:                                    ." $child for ip $childip </font>");
                   7071:                             kill('INT', $child);
                   7072:                         }
                   7073:                     }
                   7074:                 }
                   7075:             }
                   7076:         }
                   7077:     }
1.148     foxr     7078:     ReloadApache;
1.165     albertel 7079:     &status("Finished reloading hosts.tab");
1.144     foxr     7080: }
                   7081: 
1.57      www      7082: sub checkchildren {
1.165     albertel 7083:     &status("Checking on the children (sending signals)");
1.57      www      7084:     &initnewstatus();
                   7085:     &logstatus();
                   7086:     &logthis('Going to check on the children');
1.134     albertel 7087:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 7088:     foreach (sort keys %children) {
1.221     albertel 7089: 	#sleep 1;
1.57      www      7090:         unless (kill 'USR1' => $_) {
                   7091: 	    &logthis ('Child '.$_.' is dead');
                   7092:             &logstatus($$.' is dead');
1.221     albertel 7093: 	    delete($children{$_});
1.57      www      7094:         } 
1.61      harris41 7095:     }
1.63      www      7096:     sleep 5;
1.212     foxr     7097:     $SIG{ALRM} = sub { Debug("timeout"); 
                   7098: 		       die "timeout";  };
1.113     albertel 7099:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 7100:     &status("Checking on the children (waiting for reports)");
1.63      www      7101:     foreach (sort keys %children) {
                   7102:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 7103:           eval {
                   7104:             alarm(300);
1.63      www      7105: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 7106: 	    kill 9 => $_;
1.131     albertel 7107: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   7108: 	    #$subj="LON: $currenthostid killed lond process $_";
                   7109: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   7110: 	    #$execdir=$perlvar{'lonDaemons'};
                   7111: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221     albertel 7112: 	    delete($children{$_});
1.113     albertel 7113: 	    alarm(0);
                   7114: 	  }
1.63      www      7115:         }
                   7116:     }
1.113     albertel 7117:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 7118:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 7119:     &status("Finished checking children");
1.221     albertel 7120:     &logthis('Finished Checking children');
1.57      www      7121: }
                   7122: 
1.1       albertel 7123: # --------------------------------------------------------------------- Logging
                   7124: 
                   7125: sub logthis {
                   7126:     my $message=shift;
                   7127:     my $execdir=$perlvar{'lonDaemons'};
                   7128:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   7129:     my $now=time;
                   7130:     my $local=localtime($now);
1.58      www      7131:     $lastlog=$local.': '.$message;
1.1       albertel 7132:     print $fh "$local ($$): $message\n";
                   7133: }
                   7134: 
1.77      foxr     7135: # ------------------------- Conditional log if $DEBUG true.
                   7136: sub Debug {
                   7137:     my $message = shift;
                   7138:     if($DEBUG) {
                   7139: 	&logthis($message);
                   7140:     }
                   7141: }
1.161     foxr     7142: 
                   7143: #
                   7144: #   Sub to do replies to client.. this gives a hook for some
                   7145: #   debug tracing too:
                   7146: #  Parameters:
                   7147: #     fd      - File open on client.
                   7148: #     reply   - Text to send to client.
                   7149: #     request - Original request from client.
                   7150: #
1.490     droeschl 7151: #NOTE $reply must be terminated by exactly *one* \n. If $reply is a reference
                   7152: #this is done automatically ($$reply must not contain any \n in this case). 
                   7153: #If $reply is a string the caller has to ensure this.
1.161     foxr     7154: sub Reply {
1.192     foxr     7155:     my ($fd, $reply, $request) = @_;
1.387     albertel 7156:     if (ref($reply)) {
                   7157: 	print $fd $$reply;
                   7158: 	print $fd "\n";
                   7159: 	if ($DEBUG) { Debug("Request was $request  Reply was $$reply"); }
                   7160:     } else {
                   7161: 	print $fd $reply;
                   7162: 	if ($DEBUG) { Debug("Request was $request  Reply was $reply"); }
                   7163:     }
1.212     foxr     7164:     $Transactions++;
                   7165: }
                   7166: 
                   7167: 
                   7168: #
                   7169: #    Sub to report a failure.
                   7170: #    This function:
                   7171: #     -   Increments the failure statistic counters.
                   7172: #     -   Invokes Reply to send the error message to the client.
                   7173: # Parameters:
                   7174: #    fd       - File descriptor open on the client
                   7175: #    reply    - Reply text to emit.
                   7176: #    request  - The original request message (used by Reply
                   7177: #               to debug if that's enabled.
                   7178: # Implicit outputs:
                   7179: #    $Failures- The number of failures is incremented.
                   7180: #    Reply (invoked here) sends a message to the 
                   7181: #    client:
                   7182: #
                   7183: sub Failure {
                   7184:     my $fd      = shift;
                   7185:     my $reply   = shift;
                   7186:     my $request = shift;
                   7187:    
                   7188:     $Failures++;
                   7189:     Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     7190: }
1.57      www      7191: # ------------------------------------------------------------------ Log status
                   7192: 
                   7193: sub logstatus {
1.178     foxr     7194:     &status("Doing logging");
                   7195:     my $docdir=$perlvar{'lonDocRoot'};
                   7196:     {
                   7197: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200     matthew  7198:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178     foxr     7199:         $fh->close();
                   7200:     }
1.221     albertel 7201:     &status("Finished $$.txt");
                   7202:     {
                   7203: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
                   7204: 	flock(LOG,LOCK_EX);
                   7205: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
                   7206: 	    .$status."\t".$lastlog."\t $keymode\n";
1.275     albertel 7207: 	flock(LOG,LOCK_UN);
1.221     albertel 7208: 	close(LOG);
                   7209:     }
1.178     foxr     7210:     &status("Finished logging");
1.57      www      7211: }
                   7212: 
                   7213: sub initnewstatus {
                   7214:     my $docdir=$perlvar{'lonDocRoot'};
                   7215:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
1.460     foxr     7216:     my $now=time();
1.57      www      7217:     my $local=localtime($now);
                   7218:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      7219:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 7220:     while (my $filename=readdir(DIR)) {
1.64      www      7221:         unlink("$docdir/lon-status/londchld/$filename");
                   7222:     }
                   7223:     closedir(DIR);
1.57      www      7224: }
                   7225: 
                   7226: # -------------------------------------------------------------- Status setting
                   7227: 
                   7228: sub status {
                   7229:     my $what=shift;
                   7230:     my $now=time;
                   7231:     my $local=localtime($now);
1.178     foxr     7232:     $status=$local.': '.$what;
                   7233:     $0='lond: '.$what.' '.$local;
1.57      www      7234: }
1.11      www      7235: 
1.13      www      7236: # -------------------------------------------------------------- Talk to lonsql
                   7237: 
1.234     foxr     7238: sub sql_reply {
1.12      harris41 7239:     my ($cmd)=@_;
1.234     foxr     7240:     my $answer=&sub_sql_reply($cmd);
                   7241:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12      harris41 7242:     return $answer;
                   7243: }
                   7244: 
1.234     foxr     7245: sub sub_sql_reply {
1.12      harris41 7246:     my ($cmd)=@_;
                   7247:     my $unixsock="mysqlsock";
                   7248:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   7249:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   7250:                                       Type    => SOCK_STREAM,
                   7251:                                       Timeout => 10)
                   7252:        or return "con_lost";
1.319     www      7253:     print $sclient "$cmd:$currentdomainid\n";
1.12      harris41 7254:     my $answer=<$sclient>;
                   7255:     chomp($answer);
                   7256:     if (!$answer) { $answer="con_lost"; }
                   7257:     return $answer;
                   7258: }
                   7259: 
1.1       albertel 7260: # --------------------------------------- Is this the home server of an author?
1.11      www      7261: 
1.1       albertel 7262: sub ishome {
                   7263:     my $author=shift;
                   7264:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   7265:     my ($udom,$uname)=split(/\//,$author);
                   7266:     my $proname=propath($udom,$uname);
                   7267:     if (-e $proname) {
                   7268: 	return 'owner';
                   7269:     } else {
                   7270:         return 'not_owner';
                   7271:     }
                   7272: }
                   7273: 
                   7274: # ======================================================= Continue main program
                   7275: # ---------------------------------------------------- Fork once and dissociate
                   7276: 
1.134     albertel 7277: my $fpid=fork;
1.1       albertel 7278: exit if $fpid;
1.29      harris41 7279: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 7280: 
1.29      harris41 7281: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 7282: 
                   7283: # ------------------------------------------------------- Write our PID on disk
                   7284: 
1.134     albertel 7285: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 7286: open (PIDSAVE,">$execdir/logs/lond.pid");
                   7287: print PIDSAVE "$$\n";
                   7288: close(PIDSAVE);
1.190     albertel 7289: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57      www      7290: &status('Starting');
1.1       albertel 7291: 
1.106     foxr     7292: 
1.1       albertel 7293: 
                   7294: # ----------------------------------------------------- Install signal handlers
                   7295: 
1.57      www      7296: 
1.1       albertel 7297: $SIG{CHLD} = \&REAPER;
                   7298: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   7299: $SIG{HUP}  = \&HUPSMAN;
1.57      www      7300: $SIG{USR1} = \&checkchildren;
1.144     foxr     7301: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     7302: 
1.148     foxr     7303: #  Read the host hashes:
1.368     albertel 7304: &Apache::lonnet::load_hosts_tab();
1.447     raeburn  7305: my %iphost = &Apache::lonnet::get_iphost(1);
1.106     foxr     7306: 
1.480     raeburn  7307: $dist=`$perlvar{'lonDaemons'}/distprobe`;
1.286     albertel 7308: 
1.471     raeburn  7309: my $arch = `uname -i`;
1.475     raeburn  7310: chomp($arch);
1.471     raeburn  7311: if ($arch eq 'unknown') {
                   7312:     $arch = `uname -m`;
1.475     raeburn  7313:     chomp($arch);
1.471     raeburn  7314: }
                   7315: 
1.545     raeburn  7316: unless (lonssl::Read_Connect_Config(\%secureconf,\%crlchecked,\%perlvar) eq 'ok') {
1.532     raeburn  7317:     &logthis('<font color="blue">No connectionrules table. Will fallback to loncapa.conf</font>');
                   7318: }
                   7319: 
1.106     foxr     7320: # --------------------------------------------------------------
                   7321: #   Accept connections.  When a connection comes in, it is validated
                   7322: #   and if good, a child process is created to process transactions
                   7323: #   along the connection.
                   7324: 
1.1       albertel 7325: while (1) {
1.165     albertel 7326:     &status('Starting accept');
1.106     foxr     7327:     $client = $server->accept() or next;
1.165     albertel 7328:     &status('Accepted '.$client.' off to spawn');
1.386     albertel 7329:     make_new_child($client);
1.165     albertel 7330:     &status('Finished spawning');
1.1       albertel 7331: }
                   7332: 
1.212     foxr     7333: sub make_new_child {
                   7334:     my $pid;
                   7335: #    my $cipher;     # Now global
                   7336:     my $sigset;
1.178     foxr     7337: 
1.212     foxr     7338:     $client = shift;
                   7339:     &status('Starting new child '.$client);
                   7340:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   7341: 	     ")</font>");    
                   7342:     # block signal for fork
                   7343:     $sigset = POSIX::SigSet->new(SIGINT);
                   7344:     sigprocmask(SIG_BLOCK, $sigset)
                   7345:         or die "Can't block SIGINT for fork: $!\n";
1.178     foxr     7346: 
1.212     foxr     7347:     die "fork: $!" unless defined ($pid = fork);
1.178     foxr     7348: 
1.212     foxr     7349:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   7350: 	                               # connection liveness.
1.178     foxr     7351: 
1.212     foxr     7352:     #
                   7353:     #  Figure out who we're talking to so we can record the peer in 
                   7354:     #  the pid hash.
                   7355:     #
                   7356:     my $caller = getpeername($client);
                   7357:     my ($port,$iaddr);
                   7358:     if (defined($caller) && length($caller) > 0) {
                   7359: 	($port,$iaddr)=unpack_sockaddr_in($caller);
                   7360:     } else {
                   7361: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
                   7362:     }
                   7363:     if (defined($iaddr)) {
                   7364: 	$clientip  = inet_ntoa($iaddr);
                   7365: 	Debug("Connected with $clientip");
                   7366:     } else {
                   7367: 	&logthis("Unable to determine clientip");
                   7368: 	$clientip='Unavailable';
                   7369:     }
                   7370:     
                   7371:     if ($pid) {
                   7372:         # Parent records the child's birth and returns.
                   7373:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7374:             or die "Can't unblock SIGINT for fork: $!\n";
                   7375:         $children{$pid} = $clientip;
                   7376:         &status('Started child '.$pid);
1.462     foxr     7377: 	close($client);
1.212     foxr     7378:         return;
                   7379:     } else {
                   7380:         # Child can *not* return from this subroutine.
                   7381:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                   7382:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   7383:                                 #don't get intercepted
                   7384:         $SIG{USR1}= \&logstatus;
                   7385:         $SIG{ALRM}= \&timeout;
1.468     foxr     7386: 	#
                   7387: 	# Block sigpipe as it gets thrownon socket disconnect and we want to 
                   7388: 	# deal with that as a read faiure instead.
                   7389: 	#
                   7390: 	my $blockset = POSIX::SigSet->new(SIGPIPE);
                   7391: 	sigprocmask(SIG_BLOCK, $blockset);
                   7392: 
1.212     foxr     7393:         $lastlog='Forked ';
                   7394:         $status='Forked';
1.178     foxr     7395: 
1.212     foxr     7396:         # unblock signals
                   7397:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7398:             or die "Can't unblock SIGINT for fork: $!\n";
1.178     foxr     7399: 
1.212     foxr     7400: #        my $tmpsnum=0;            # Now global
                   7401: #---------------------------------------------------- kerberos 5 initialization
                   7402:         &Authen::Krb5::init_context();
1.511     raeburn  7403: 
                   7404:         my $no_ets;
1.514     raeburn  7405:         if ($dist =~ /^(?:centos|rhes|scientific)(\d+)$/) {
1.511     raeburn  7406:             if ($1 >= 7) {
                   7407:                 $no_ets = 1;
                   7408:             }
                   7409:         } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
                   7410:             if (($1 eq '9.3') || ($1 >= 12.2)) {
                   7411:                 $no_ets = 1; 
                   7412:             }
1.514     raeburn  7413:         } elsif ($dist =~ /^sles(\d+)$/) {
                   7414:             if ($1 > 11) {
                   7415:                 $no_ets = 1;
                   7416:             }
1.511     raeburn  7417:         } elsif ($dist =~ /^fedora(\d+)$/) {
                   7418:             if ($1 < 7) {
                   7419:                 $no_ets = 1;
                   7420:             }
                   7421:         }
                   7422:         unless ($no_ets) {
1.286     albertel 7423: 	    &Authen::Krb5::init_ets();
                   7424: 	}
1.209     albertel 7425: 
1.212     foxr     7426: 	&status('Accepted connection');
                   7427: # =============================================================================
                   7428:             # do something with the connection
                   7429: # -----------------------------------------------------------------------------
                   7430: 	# see if we know client and 'check' for spoof IP by ineffective challenge
1.178     foxr     7431: 
1.278     albertel 7432: 	my $outsideip=$clientip;
                   7433: 	if ($clientip eq '127.0.0.1') {
1.368     albertel 7434: 	    $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
1.278     albertel 7435: 	}
1.412     foxr     7436: 	&ReadManagerTable();
1.368     albertel 7437: 	my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
1.278     albertel 7438: 	my $ismanager=($managers{$outsideip}    ne undef);
1.432     raeburn  7439: 	$clientname  = "[unknown]";
1.212     foxr     7440: 	if($clientrec) {	# Establish client type.
                   7441: 	    $ConnectionType = "client";
1.368     albertel 7442: 	    $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
1.212     foxr     7443: 	    if($ismanager) {
                   7444: 		$ConnectionType = "both";
                   7445: 	    }
                   7446: 	} else {
                   7447: 	    $ConnectionType = "manager";
1.278     albertel 7448: 	    $clientname = $managers{$outsideip};
1.212     foxr     7449: 	}
1.532     raeburn  7450: 	my ($clientok,$clientinfoset);
1.178     foxr     7451: 
1.212     foxr     7452: 	if ($clientrec || $ismanager) {
                   7453: 	    &status("Waiting for init from $clientip $clientname");
                   7454: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   7455: 		     $clientip.
                   7456: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   7457: 	    &status("Connecting $clientip  ($clientname))"); 
                   7458: 	    my $remotereq=<$client>;
                   7459: 	    chomp($remotereq);
                   7460: 	    Debug("Got init: $remotereq");
1.337     albertel 7461: 
1.212     foxr     7462: 	    if ($remotereq =~ /^init/) {
                   7463: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   7464: 		#
                   7465: 		#  If the remote is attempting a local init... give that a try:
                   7466: 		#
1.432     raeburn  7467: 		(my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
1.492     droeschl 7468:         # For LON-CAPA 2.9, the  client session will have sent its LON-CAPA
                   7469:         # version when initiating the connection. For LON-CAPA 2.8 and older,
                   7470:         # the version is retrieved from the global %loncaparevs in lonnet.pm.            
1.494     droeschl 7471:         # $clientversion contains path to keyfile if $inittype eq 'local'
                   7472:         # it's overridden below in this case
1.492     droeschl 7473:         $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
1.209     albertel 7474: 
1.212     foxr     7475: 		# If the connection type is ssl, but I didn't get my
                   7476: 		# certificate files yet, then I'll drop  back to 
                   7477: 		# insecure (if allowed).
1.532     raeburn  7478: 
                   7479:                 if ($inittype eq "ssl") {
                   7480:                     my $context;
                   7481:                     if ($clientsamedom) {
                   7482:                         $context = 'dom';
                   7483:                         if ($secureconf{'connfrom'}{'dom'} eq 'no') {
                   7484:                             $inittype = "";
                   7485:                         }
                   7486:                     } elsif ($clientsameinst) {
                   7487:                         $context = 'intdom';
                   7488:                         if ($secureconf{'connfrom'}{'intdom'} eq 'no') {
                   7489:                             $inittype = "";
                   7490:                         }
                   7491:                     } else {
                   7492:                         $context = 'other';
                   7493:                         if ($secureconf{'connfrom'}{'other'} eq 'no') {
                   7494:                             $inittype = "";
                   7495:                         }
                   7496:                     }
                   7497:                     if ($inittype eq '') {
                   7498:                         &logthis("<font color=\"blue\"> Domain config set "
                   7499:                                 ."to no ssl for $clientname (context: $context)"
                   7500:                                 ." -- trying insecure auth</font>");
                   7501:                     }
                   7502:                 }
                   7503: 
1.212     foxr     7504: 		if($inittype eq "ssl") {
                   7505: 		    my ($ca, $cert) = lonssl::CertificateFile;
                   7506: 		    my $kfile       = lonssl::KeyFile;
                   7507: 		    if((!$ca)   || 
                   7508: 		       (!$cert) || 
                   7509: 		       (!$kfile)) {
                   7510: 			$inittype = ""; # This forces insecure attempt.
                   7511: 			&logthis("<font color=\"blue\"> Certificates not "
                   7512: 				 ."installed -- trying insecure auth</font>");
1.224     foxr     7513: 		    } else {	# SSL certificates are in place so
1.212     foxr     7514: 		    }		# Leave the inittype alone.
                   7515: 		}
                   7516: 
                   7517: 		if($inittype eq "local") {
1.432     raeburn  7518:                     $clientversion = $perlvar{'lonVersion'};
1.212     foxr     7519: 		    my $key = LocalConnection($client, $remotereq);
                   7520: 		    if($key) {
                   7521: 			Debug("Got local key $key");
                   7522: 			$clientok     = 1;
                   7523: 			my $cipherkey = pack("H32", $key);
                   7524: 			$cipher       = new IDEA($cipherkey);
                   7525: 			print $client "ok:local\n";
1.442     www      7526: 			&logthis('<font color="green">'
1.212     foxr     7527: 				 . "Successful local authentication </font>");
                   7528: 			$keymode = "local"
1.178     foxr     7529: 		    } else {
1.212     foxr     7530: 			Debug("Failed to get local key");
                   7531: 			$clientok = 0;
                   7532: 			shutdown($client, 3);
                   7533: 			close $client;
1.178     foxr     7534: 		    }
1.212     foxr     7535: 		} elsif ($inittype eq "ssl") {
1.532     raeburn  7536: 		    my $key = SSLConnection($client,$clientname);
1.212     foxr     7537: 		    if ($key) {
                   7538: 			$clientok = 1;
                   7539: 			my $cipherkey = pack("H32", $key);
                   7540: 			$cipher       = new IDEA($cipherkey);
                   7541: 			&logthis('<font color="green">'
                   7542: 				 ."Successfull ssl authentication with $clientname </font>");
                   7543: 			$keymode = "ssl";
                   7544: 	     
1.178     foxr     7545: 		    } else {
1.212     foxr     7546: 			$clientok = 0;
                   7547: 			close $client;
1.178     foxr     7548: 		    }
1.212     foxr     7549: 	   
                   7550: 		} else {
1.532     raeburn  7551:                     $clientinfoset = &set_client_info();
1.212     foxr     7552: 		    my $ok = InsecureConnection($client);
                   7553: 		    if($ok) {
                   7554: 			$clientok = 1;
                   7555: 			&logthis('<font color="green">'
                   7556: 				 ."Successful insecure authentication with $clientname </font>");
                   7557: 			print $client "ok\n";
                   7558: 			$keymode = "insecure";
1.178     foxr     7559: 		    } else {
1.212     foxr     7560: 			&logthis('<font color="yellow">'
                   7561: 				  ."Attempted insecure connection disallowed </font>");
                   7562: 			close $client;
                   7563: 			$clientok = 0;
1.178     foxr     7564: 		    }
                   7565: 		}
1.212     foxr     7566: 	    } else {
                   7567: 		&logthis(
                   7568: 			 "<font color='blue'>WARNING: "
                   7569: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   7570: 		&status('No init '.$clientip);
                   7571: 	    }
                   7572: 	} else {
                   7573: 	    &logthis(
                   7574: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
                   7575: 	    &status('Hung up on '.$clientip);
                   7576: 	}
                   7577:  
                   7578: 	if ($clientok) {
                   7579: # ---------------- New known client connecting, could mean machine online again
1.368     albertel 7580: 	    if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip 
1.367     albertel 7581: 		&& $clientip ne '127.0.0.1') {
1.375     albertel 7582: 		&Apache::lonnet::reconlonc($clientname);
1.212     foxr     7583: 	    }
                   7584: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
                   7585: 	    &status('Will listen to '.$clientname);
                   7586: # ------------------------------------------------------------ Process requests
                   7587: 	    my $keep_going = 1;
                   7588: 	    my $user_input;
1.532     raeburn  7589:             unless ($clientinfoset) {
                   7590:                 $clientinfoset = &set_client_info();
1.525     raeburn  7591:             }
                   7592:             $clientremoteok = 0;
                   7593:             unless ($clientsameinst) {
                   7594:                 $clientremoteok = 1;
                   7595:                 my $defdom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   7596:                 %clientprohibited = &get_prohibited($defdom);
                   7597:                 if ($clientintdom) {
                   7598:                     my $remsessconf = &get_usersession_config($defdom,'remotesession');
                   7599:                     if (ref($remsessconf) eq 'HASH') {
                   7600:                         if (ref($remsessconf->{'remote'}) eq 'HASH') {
                   7601:                             if (ref($remsessconf->{'remote'}->{'excludedomain'}) eq 'ARRAY') {
                   7602:                                 if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'excludedomain'}})) {
                   7603:                                     $clientremoteok = 0;
                   7604:                                 }
                   7605:                             }
                   7606:                             if (ref($remsessconf->{'remote'}->{'includedomain'}) eq 'ARRAY') {
                   7607:                                 if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'includedomain'}})) {
                   7608:                                     $clientremoteok = 1;
                   7609:                                 } else {
                   7610:                                     $clientremoteok = 0;
                   7611:                                 }
                   7612:                             }
                   7613:                         }
                   7614:                     }
                   7615:                 }
                   7616:             }
1.212     foxr     7617: 	    while(($user_input = get_request) && $keep_going) {
                   7618: 		alarm(120);
                   7619: 		Debug("Main: Got $user_input\n");
                   7620: 		$keep_going = &process_request($user_input);
1.178     foxr     7621: 		alarm(0);
1.212     foxr     7622: 		&status('Listening to '.$clientname." ($keymode)");	   
1.161     foxr     7623: 	    }
1.212     foxr     7624: 
1.59      www      7625: # --------------------------------------------- client unknown or fishy, refuse
1.212     foxr     7626: 	}  else {
1.161     foxr     7627: 	    print $client "refused\n";
                   7628: 	    $client->close();
1.190     albertel 7629: 	    &logthis("<font color='blue'>WARNING: "
1.161     foxr     7630: 		     ."Rejected client $clientip, closing connection</font>");
                   7631: 	}
1.525     raeburn  7632:     }
1.161     foxr     7633:     
1.1       albertel 7634: # =============================================================================
1.161     foxr     7635:     
1.190     albertel 7636:     &logthis("<font color='red'>CRITICAL: "
1.161     foxr     7637: 	     ."Disconnect from $clientip ($clientname)</font>");    
                   7638:     
                   7639:     
                   7640:     # this exit is VERY important, otherwise the child will become
                   7641:     # a producer of more and more children, forking yourself into
                   7642:     # process death.
                   7643:     exit;
1.106     foxr     7644:     
1.78      foxr     7645: }
1.532     raeburn  7646: 
                   7647: #
                   7648: #  Used to determine if a particular client is from the same domain
                   7649: #  as the current server, or from the same internet domain.
                   7650: #
                   7651: #  Optional input -- the client to check for domain and internet domain.
                   7652: #  If not specified, defaults to the package variable: $clientname
                   7653: #
                   7654: #  If called in array context will not set package variables, but will
                   7655: #  instead return an array of two values - (a) true if client is in the
                   7656: #  same domain as the server, and (b) true if client is in the same internet
                   7657: #  domain.
                   7658: #
                   7659: #  If called in scalar context, sets package variables for current client:
                   7660: #
                   7661: #  $clienthomedom  - LonCAPA domain of homeID for client.
                   7662: #  $clientsamedom  - LonCAPA domain same for this host and client.
                   7663: #  $clientintdom   - LonCAPA "internet domain" for client.
                   7664: #  $clientsameinst - LonCAPA "internet domain" same for this host & client.
                   7665: #
                   7666: #  returns 1 to indicate package variables have been set for current client.
                   7667: #
                   7668: 
                   7669: sub set_client_info {
                   7670:     my ($lonhost) = @_;
                   7671:     $lonhost ||= $clientname;
                   7672:     my $clienthost = &Apache::lonnet::hostname($lonhost);
                   7673:     my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
                   7674:     my $homedom = &Apache::lonnet::host_domain($clientserverhomeID);
                   7675:     my $samedom = 0;
                   7676:     if ($perlvar{'lonDefDom'} eq $homedom) {
                   7677:         $samedom = 1;
                   7678:     }
                   7679:     my $intdom = &Apache::lonnet::internet_dom($clientserverhomeID);
                   7680:     my $sameinst = 0;
                   7681:     if ($intdom ne '') {
                   7682:         my $internet_names = &Apache::lonnet::get_internet_names($currenthostid);
                   7683:         if (ref($internet_names) eq 'ARRAY') {
                   7684:             if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   7685:                 $sameinst = 1;
                   7686:             }
                   7687:         }
                   7688:     }
                   7689:     if (wantarray) {
                   7690:         return ($samedom,$sameinst);
                   7691:     } else {
                   7692:         $clienthomedom = $homedom;
                   7693:         $clientsamedom = $samedom;
                   7694:         $clientintdom = $intdom;
                   7695:         $clientsameinst = $sameinst;
                   7696:         return 1;
                   7697:     }
                   7698: }
                   7699: 
1.261     foxr     7700: #
                   7701: #   Determine if a user is an author for the indicated domain.
                   7702: #
                   7703: # Parameters:
                   7704: #    domain          - domain to check in .
                   7705: #    user            - Name of user to check.
                   7706: #
                   7707: # Return:
                   7708: #     1             - User is an author for domain.
                   7709: #     0             - User is not an author for domain.
                   7710: sub is_author {
                   7711:     my ($domain, $user) = @_;
                   7712: 
                   7713:     &Debug("is_author: $user @ $domain");
                   7714: 
                   7715:     my $hashref = &tie_user_hash($domain, $user, "roles",
                   7716: 				 &GDBM_READER());
                   7717: 
                   7718:     #  Author role should show up as a key /domain/_au
1.78      foxr     7719: 
1.321     albertel 7720:     my $value;
1.487     foxr     7721:     if ($hashref) {
1.78      foxr     7722: 
1.487     foxr     7723: 	my $key    = "/$domain/_au";
                   7724: 	if (defined($hashref)) {
                   7725: 	    $value = $hashref->{$key};
                   7726: 	    if(!untie_user_hash($hashref)) {
                   7727: 		return 'error: ' .  ($!+0)." untie (GDBM) Failed";
                   7728: 	    }
                   7729: 	}
                   7730: 	
                   7731: 	if(defined($value)) {
                   7732: 	    &Debug("$user @ $domain is an author");
                   7733: 	}
                   7734:     } else {
                   7735: 	return 'error: '.($!+0)." tie (GDBM) Failed";
1.261     foxr     7736:     }
                   7737: 
                   7738:     return defined($value);
                   7739: }
1.78      foxr     7740: #
                   7741: #   Checks to see if the input roleput request was to set
1.482     www      7742: # an author role.  If so, creates construction space 
1.78      foxr     7743: # Parameters:
                   7744: #    request   - The request sent to the rolesput subchunk.
                   7745: #                We're looking for  /domain/_au
                   7746: #    domain    - The domain in which the user is having roles doctored.
                   7747: #    user      - Name of the user for which the role is being put.
                   7748: #    authtype  - The authentication type associated with the user.
                   7749: #
1.289     albertel 7750: sub manage_permissions {
1.192     foxr     7751:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     7752:     # See if the request is of the form /$domain/_au
1.289     albertel 7753:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.484     raeburn  7754:         my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
1.482     www      7755:         unless (-e $path) {        
                   7756:            mkdir($path);
                   7757:         }
                   7758:         unless (-e $path.'/'.$user) {
                   7759:            mkdir($path.'/'.$user);
                   7760:         }
1.78      foxr     7761:     }
                   7762: }
1.222     foxr     7763: 
                   7764: 
                   7765: #
                   7766: #  Return the full path of a user password file, whether it exists or not.
                   7767: # Parameters:
                   7768: #   domain     - Domain in which the password file lives.
                   7769: #   user       - name of the user.
                   7770: # Returns:
                   7771: #    Full passwd path:
                   7772: #
                   7773: sub password_path {
                   7774:     my ($domain, $user) = @_;
1.264     albertel 7775:     return &propath($domain, $user).'/passwd';
1.222     foxr     7776: }
                   7777: 
                   7778: #   Password Filename
                   7779: #   Returns the path to a passwd file given domain and user... only if
                   7780: #  it exists.
                   7781: # Parameters:
                   7782: #   domain    - Domain in which to search.
                   7783: #   user      - username.
                   7784: # Returns:
                   7785: #   - If the password file exists returns its path.
                   7786: #   - If the password file does not exist, returns undefined.
                   7787: #
                   7788: sub password_filename {
                   7789:     my ($domain, $user) = @_;
                   7790: 
                   7791:     Debug ("PasswordFilename called: dom = $domain user = $user");
                   7792: 
                   7793:     my $path  = &password_path($domain, $user);
                   7794:     Debug("PasswordFilename got path: $path");
                   7795:     if(-e $path) {
                   7796: 	return $path;
                   7797:     } else {
                   7798: 	return undef;
                   7799:     }
                   7800: }
                   7801: 
                   7802: #
                   7803: #   Rewrite the contents of the user's passwd file.
                   7804: #  Parameters:
                   7805: #    domain    - domain of the user.
                   7806: #    name      - User's name.
                   7807: #    contents  - New contents of the file.
1.533     raeburn  7808: #    saveold   - (optional). If true save old file in a passwd.bak file.
1.222     foxr     7809: # Returns:
                   7810: #   0    - Failed.
                   7811: #   1    - Success.
                   7812: #
                   7813: sub rewrite_password_file {
1.533     raeburn  7814:     my ($domain, $user, $contents, $saveold) = @_;
1.222     foxr     7815: 
                   7816:     my $file = &password_filename($domain, $user);
                   7817:     if (defined $file) {
1.533     raeburn  7818:         if ($saveold) {
                   7819:             my $bakfile = $file.'.bak';
                   7820:             if (CopyFile($file,$bakfile)) {
                   7821:                 chmod(0400,$bakfile);
                   7822:                 &logthis("Old password saved in passwd.bak for internally authenticated user: $user:$domain");
                   7823:             } else {
                   7824:                 &logthis("Failed to save old password in passwd.bak for internally authenticated user: $user:$domain");
                   7825:             }
                   7826:         }
1.222     foxr     7827: 	my $pf = IO::File->new(">$file");
                   7828: 	if($pf) {
                   7829: 	    print $pf "$contents\n";
                   7830: 	    return 1;
                   7831: 	} else {
                   7832: 	    return 0;
                   7833: 	}
                   7834:     } else {
                   7835: 	return 0;
                   7836:     }
                   7837: 
                   7838: }
                   7839: 
1.78      foxr     7840: #
1.222     foxr     7841: #   get_auth_type - Determines the authorization type of a user in a domain.
1.78      foxr     7842: 
                   7843: #     Returns the authorization type or nouser if there is no such user.
                   7844: #
1.436     raeburn  7845: sub get_auth_type {
1.192     foxr     7846:     my ($domain, $user)  = @_;
1.78      foxr     7847: 
1.222     foxr     7848:     Debug("get_auth_type( $domain, $user ) \n");
1.78      foxr     7849:     my $proname    = &propath($domain, $user); 
                   7850:     my $passwdfile = "$proname/passwd";
                   7851:     if( -e $passwdfile ) {
                   7852: 	my $pf = IO::File->new($passwdfile);
                   7853: 	my $realpassword = <$pf>;
                   7854: 	chomp($realpassword);
1.79      foxr     7855: 	Debug("Password info = $realpassword\n");
1.78      foxr     7856: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     7857: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.259     raeburn  7858: 	return "$authtype:$contentpwd";     
1.224     foxr     7859:     } else {
1.79      foxr     7860: 	Debug("Returning nouser");
1.78      foxr     7861: 	return "nouser";
                   7862:     }
1.1       albertel 7863: }
                   7864: 
1.220     foxr     7865: #
                   7866: #  Validate a user given their domain, name and password.  This utility
                   7867: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
                   7868: #  to validate the login credentials of a user.
                   7869: # Parameters:
                   7870: #    $domain    - The domain being logged into (this is required due to
                   7871: #                 the capability for multihomed systems.
                   7872: #    $user      - The name of the user being validated.
                   7873: #    $password  - The user's propoposed password.
                   7874: #
                   7875: # Returns:
                   7876: #     1        - The domain,user,pasword triplet corresponds to a valid
                   7877: #                user.
                   7878: #     0        - The domain,user,password triplet is not a valid user.
                   7879: #
                   7880: sub validate_user {
1.396     raeburn  7881:     my ($domain, $user, $password, $checkdefauth) = @_;
1.220     foxr     7882: 
                   7883:     # Why negative ~pi you may well ask?  Well this function is about
                   7884:     # authentication, and therefore very important to get right.
                   7885:     # I've initialized the flag that determines whether or not I've 
                   7886:     # validated correctly to a value it's not supposed to get.
                   7887:     # At the end of this function. I'll ensure that it's not still that
                   7888:     # value so we don't just wind up returning some accidental value
                   7889:     # as a result of executing an unforseen code path that
1.249     foxr     7890:     # did not set $validated.  At the end of valid execution paths,
                   7891:     # validated shoule be 1 for success or 0 for failuer.
1.220     foxr     7892: 
                   7893:     my $validated = -3.14159;
                   7894: 
                   7895:     #  How we authenticate is determined by the type of authentication
                   7896:     #  the user has been assigned.  If the authentication type is
                   7897:     #  "nouser", the user does not exist so we will return 0.
                   7898: 
1.222     foxr     7899:     my $contents = &get_auth_type($domain, $user);
1.220     foxr     7900:     my ($howpwd, $contentpwd) = split(/:/, $contents);
                   7901: 
                   7902:     my $null = pack("C",0);	# Used by kerberos auth types.
                   7903: 
1.395     raeburn  7904:     if ($howpwd eq 'nouser') {
1.396     raeburn  7905:         if ($checkdefauth) {
                   7906:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   7907:             if ($domdefaults{'auth_def'} eq 'localauth') {
                   7908:                 $howpwd = $domdefaults{'auth_def'};
                   7909:                 $contentpwd = $domdefaults{'auth_arg_def'};
                   7910:             } elsif ((($domdefaults{'auth_def'} eq 'krb4') || 
                   7911:                       ($domdefaults{'auth_def'} eq 'krb5')) &&
                   7912:                      ($domdefaults{'auth_arg_def'} ne '')) {
                   7913:                 $howpwd = $domdefaults{'auth_def'};
                   7914:                 $contentpwd = $domdefaults{'auth_arg_def'}; 
                   7915:             }
1.395     raeburn  7916:         }
1.533     raeburn  7917:     }
1.220     foxr     7918:     if ($howpwd ne 'nouser') {
                   7919: 	if($howpwd eq "internal") { # Encrypted is in local password file.
1.518     raeburn  7920:             if (length($contentpwd) == 13) {
                   7921:                 $validated = (crypt($password,$contentpwd) eq $contentpwd);
                   7922:                 if ($validated) {
1.533     raeburn  7923:                     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   7924:                     if ($domdefaults{'intauth_switch'}) {
                   7925:                         my $ncpass = &hash_passwd($domain,$password);
                   7926:                         my $saveold;
                   7927:                         if ($domdefaults{'intauth_switch'} == 2) {
                   7928:                             $saveold = 1;
                   7929:                         }
                   7930:                         if (&rewrite_password_file($domain,$user,"$howpwd:$ncpass",$saveold)) {
                   7931:                             &update_passwd_history($user,$domain,$howpwd,'conversion');
                   7932:                             &logthis("Validated password hashed with bcrypt for $user:$domain");
                   7933:                         }
1.518     raeburn  7934:                     }
                   7935:                 }
                   7936:             } else {
1.533     raeburn  7937:                 $validated = &check_internal_passwd($password,$contentpwd,$domain,$user);
1.518     raeburn  7938:             }
1.220     foxr     7939: 	}
                   7940: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
                   7941: 	    $contentpwd = (getpwnam($user))[1];
                   7942: 	    if($contentpwd) {
                   7943: 		if($contentpwd eq 'x') { # Shadow password file...
                   7944: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
                   7945: 		    open PWAUTH,  "|$pwauth_path" or
                   7946: 			die "Cannot invoke authentication";
                   7947: 		    print PWAUTH "$user\n$password\n";
                   7948: 		    close PWAUTH;
                   7949: 		    $validated = ! $?;
                   7950: 
                   7951: 		} else { 	         # Passwords in /etc/passwd. 
                   7952: 		    $validated = (crypt($password,
                   7953: 					$contentpwd) eq $contentpwd);
                   7954: 		}
                   7955: 	    } else {
                   7956: 		$validated = 0;
                   7957: 	    }
1.439     raeburn  7958: 	} elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
                   7959:             my $checkwithkrb5 = 0;
                   7960:             if ($dist =~/^fedora(\d+)$/) {
                   7961:                 if ($1 > 11) {
                   7962:                     $checkwithkrb5 = 1;
                   7963:                 }
                   7964:             } elsif ($dist =~ /^suse([\d.]+)$/) {
                   7965:                 if ($1 > 11.1) {
                   7966:                     $checkwithkrb5 = 1; 
                   7967:                 }
                   7968:             }
                   7969:             if ($checkwithkrb5) {
                   7970:                 $validated = &krb5_authen($password,$null,$user,$contentpwd);
                   7971:             } else {
                   7972:                 $validated = &krb4_authen($password,$null,$user,$contentpwd);
                   7973:             }
1.224     foxr     7974: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.439     raeburn  7975:             $validated = &krb5_authen($password,$null,$user,$contentpwd);
1.224     foxr     7976: 	} elsif ($howpwd eq "localauth") { 
1.220     foxr     7977: 	    #  Authenticate via installation specific authentcation method:
                   7978: 	    $validated = &localauth::localauth($user, 
                   7979: 					       $password, 
1.353     albertel 7980: 					       $contentpwd,
                   7981: 					       $domain);
1.358     albertel 7982: 	    if ($validated < 0) {
1.357     albertel 7983: 		&logthis("localauth for $contentpwd $user:$domain returned a $validated");
                   7984: 		$validated = 0;
                   7985: 	    }
1.224     foxr     7986: 	} else {			# Unrecognized auth is also bad.
1.220     foxr     7987: 	    $validated = 0;
                   7988: 	}
                   7989:     } else {
                   7990: 	$validated = 0;
                   7991:     }
                   7992:     #
                   7993:     #  $validated has the correct stat of the authentication:
                   7994:     #
                   7995: 
                   7996:     unless ($validated != -3.14159) {
1.249     foxr     7997: 	#  I >really really< want to know if this happens.
                   7998: 	#  since it indicates that user authentication is badly
                   7999: 	#  broken in some code path.
                   8000:         #
                   8001: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220     foxr     8002:     }
                   8003:     return $validated;
                   8004: }
                   8005: 
1.518     raeburn  8006: sub check_internal_passwd {
1.533     raeburn  8007:     my ($plainpass,$stored,$domain,$user) = @_;
1.518     raeburn  8008:     my (undef,$method,@rest) = split(/!/,$stored);
1.533     raeburn  8009:     if ($method eq 'bcrypt') {
1.518     raeburn  8010:         my $result = &hash_passwd($domain,$plainpass,@rest);
                   8011:         if ($result ne $stored) {
                   8012:             return 0;
                   8013:         }
1.533     raeburn  8014:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8015:         if ($domdefaults{'intauth_check'}) {
                   8016:             # Upgrade to a larger number of rounds if necessary
                   8017:             my $defaultcost = $domdefaults{'intauth_cost'};
                   8018:             if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   8019:                 $defaultcost = 10;
                   8020:             }
                   8021:             if (int($rest[0])<int($defaultcost)) {
                   8022:                 if ($domdefaults{'intauth_check'} == 1) { 
                   8023:                     my $ncpass = &hash_passwd($domain,$plainpass);
                   8024:                     if (&rewrite_password_file($domain,$user,"internal:$ncpass")) {
                   8025:                         &update_passwd_history($user,$domain,'internal','update cost');
                   8026:                         &logthis("Validated password hashed with bcrypt for $user:$domain");
                   8027:                     }
                   8028:                     return 1;
                   8029:                 } elsif ($domdefaults{'intauth_check'} == 2) {
                   8030:                     return 0;
                   8031:                 }
                   8032:             }
                   8033:         } else {
                   8034:             return 1;
1.518     raeburn  8035:         }
                   8036:     }
                   8037:     return 0;
                   8038: }
                   8039: 
                   8040: sub get_last_authchg {
                   8041:     my ($domain,$user) = @_;
                   8042:     my $lastmod;
                   8043:     my $logname = &propath($domain,$user).'/passwd.log';
                   8044:     if (-e "$logname") {
                   8045:         $lastmod = (stat("$logname"))[9];
                   8046:     }
                   8047:     return $lastmod;
                   8048: }
                   8049: 
1.439     raeburn  8050: sub krb4_authen {
                   8051:     my ($password,$null,$user,$contentpwd) = @_;
                   8052:     my $validated = 0;
                   8053:     if (!($password =~ /$null/) ) {  # Null password not allowed.
                   8054:         eval {
                   8055:             require Authen::Krb4;
                   8056:         };
                   8057:         if (!$@) {
                   8058:             my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
                   8059:                                                        "",
                   8060:                                                        $contentpwd,,
                   8061:                                                        'krbtgt',
                   8062:                                                        $contentpwd,
                   8063:                                                        1,
                   8064:                                                        $password);
                   8065:             if(!$k4error) {
                   8066:                 $validated = 1;
                   8067:             } else {
                   8068:                 $validated = 0;
                   8069:                 &logthis('krb4: '.$user.', '.$contentpwd.', '.
                   8070:                           &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   8071:             }
                   8072:         } else {
                   8073:             $validated = krb5_authen($password,$null,$user,$contentpwd);
                   8074:         }
                   8075:     }
                   8076:     return $validated;
                   8077: }
                   8078: 
                   8079: sub krb5_authen {
                   8080:     my ($password,$null,$user,$contentpwd) = @_;
                   8081:     my $validated = 0;
                   8082:     if(!($password =~ /$null/)) { # Null password not allowed.
                   8083:         my $krbclient = &Authen::Krb5::parse_name($user.'@'
                   8084:                                                   .$contentpwd);
                   8085:         my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
                   8086:         my $krbserver  = &Authen::Krb5::parse_name($krbservice);
                   8087:         my $credentials= &Authen::Krb5::cc_default();
                   8088:         $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
                   8089:                                                             .$contentpwd));
                   8090:         my $krbreturn;
                   8091:         if (exists(&Authen::Krb5::get_init_creds_password)) {
                   8092:             $krbreturn =
                   8093:                 &Authen::Krb5::get_init_creds_password($krbclient,$password,
                   8094:                                                           $krbservice);
                   8095:             $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
                   8096:         } else {
                   8097:             $krbreturn  =
                   8098:                 &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
                   8099:                                                          $password,$credentials);
                   8100:             $validated = ($krbreturn == 1);
                   8101:         }
                   8102:         if (!$validated) {
                   8103:             &logthis('krb5: '.$user.', '.$contentpwd.', '.
                   8104:                      &Authen::Krb5::error());
                   8105:         }
                   8106:     }
                   8107:     return $validated;
                   8108: }
1.220     foxr     8109: 
1.84      albertel 8110: sub addline {
                   8111:     my ($fname,$hostid,$ip,$newline)=@_;
                   8112:     my $contents;
                   8113:     my $found=0;
1.355     albertel 8114:     my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
1.134     albertel 8115:     my $sh;
1.84      albertel 8116:     if ($sh=IO::File->new("$fname.subscription")) {
                   8117: 	while (my $subline=<$sh>) {
                   8118: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   8119: 	}
                   8120: 	$sh->close();
                   8121:     }
                   8122:     $sh=IO::File->new(">$fname.subscription");
                   8123:     if ($contents) { print $sh $contents; }
                   8124:     if ($newline) { print $sh $newline; }
                   8125:     $sh->close();
                   8126:     return $found;
1.86      www      8127: }
                   8128: 
1.234     foxr     8129: sub get_chat {
1.324     raeburn  8130:     my ($cdom,$cname,$udom,$uname,$group)=@_;
1.310     albertel 8131: 
1.87      www      8132:     my @entries=();
1.324     raeburn  8133:     my $namespace = 'nohist_chatroom';
                   8134:     my $namespace_inroom = 'nohist_inchatroom';
1.335     albertel 8135:     if ($group ne '') {
1.324     raeburn  8136:         $namespace .= '_'.$group;
                   8137:         $namespace_inroom .= '_'.$group;
                   8138:     }
                   8139:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8140: 				 &GDBM_READER());
                   8141:     if ($hashref) {
                   8142: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.311     albertel 8143: 	&untie_user_hash($hashref);
1.123     www      8144:     }
1.124     www      8145:     my @participants=();
1.134     albertel 8146:     my $cutoff=time-60;
1.324     raeburn  8147:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
1.310     albertel 8148: 			      &GDBM_WRCREAT());
                   8149:     if ($hashref) {
                   8150:         $hashref->{$uname.':'.$udom}=time;
                   8151:         foreach my $user (sort(keys(%$hashref))) {
                   8152: 	    if ($hashref->{$user}>$cutoff) {
                   8153: 		push(@participants, 'active_participant:'.$user);
1.123     www      8154:             }
                   8155:         }
1.311     albertel 8156:         &untie_user_hash($hashref);
1.86      www      8157:     }
1.124     www      8158:     return (@participants,@entries);
1.86      www      8159: }
                   8160: 
1.234     foxr     8161: sub chat_add {
1.324     raeburn  8162:     my ($cdom,$cname,$newchat,$group)=@_;
1.88      albertel 8163:     my @entries=();
1.142     www      8164:     my $time=time;
1.324     raeburn  8165:     my $namespace = 'nohist_chatroom';
                   8166:     my $logfile = 'chatroom.log';
1.335     albertel 8167:     if ($group ne '') {
1.324     raeburn  8168:         $namespace .= '_'.$group;
                   8169:         $logfile = 'chatroom_'.$group.'.log';
                   8170:     }
                   8171:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8172: 				 &GDBM_WRCREAT());
                   8173:     if ($hashref) {
                   8174: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.88      albertel 8175: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   8176: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   8177: 	my $newid=$time.'_000000';
                   8178: 	if ($thentime==$time) {
                   8179: 	    $idnum=~s/^0+//;
                   8180: 	    $idnum++;
                   8181: 	    $idnum=substr('000000'.$idnum,-6,6);
                   8182: 	    $newid=$time.'_'.$idnum;
                   8183: 	}
1.310     albertel 8184: 	$hashref->{$newid}=$newchat;
1.88      albertel 8185: 	my $expired=$time-3600;
1.310     albertel 8186: 	foreach my $comment (keys(%$hashref)) {
                   8187: 	    my ($thistime) = ($comment=~/(\d+)\_/);
1.88      albertel 8188: 	    if ($thistime<$expired) {
1.310     albertel 8189: 		delete $hashref->{$comment};
1.88      albertel 8190: 	    }
                   8191: 	}
1.310     albertel 8192: 	{
                   8193: 	    my $proname=&propath($cdom,$cname);
1.324     raeburn  8194: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
1.310     albertel 8195: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
                   8196: 	    }
                   8197: 	    close(CHATLOG);
1.142     www      8198: 	}
1.311     albertel 8199: 	&untie_user_hash($hashref);
1.86      www      8200:     }
1.84      albertel 8201: }
                   8202: 
                   8203: sub unsub {
                   8204:     my ($fname,$clientip)=@_;
                   8205:     my $result;
1.188     foxr     8206:     my $unsubs = 0;		# Number of successful unsubscribes:
                   8207: 
                   8208: 
                   8209:     # An old way subscriptions were handled was to have a 
                   8210:     # subscription marker file:
                   8211: 
                   8212:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     8213:     if (unlink("$fname.$clientname")) {
1.188     foxr     8214: 	$unsubs++;		# Successful unsub via marker file.
                   8215:     } 
                   8216: 
                   8217:     # The more modern way to do it is to have a subscription list
                   8218:     # file:
                   8219: 
1.84      albertel 8220:     if (-e "$fname.subscription") {
1.161     foxr     8221: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     8222: 	if ($found) { 
                   8223: 	    $unsubs++;
                   8224: 	}
                   8225:     } 
                   8226: 
                   8227:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   8228:     #  resource we can return ok:
                   8229: 
                   8230:     if($unsubs) {
                   8231: 	$result = "ok\n";
1.84      albertel 8232:     } else {
1.188     foxr     8233: 	$result = "not_subscribed\n";
1.84      albertel 8234:     }
1.188     foxr     8235: 
1.84      albertel 8236:     return $result;
                   8237: }
                   8238: 
1.101     www      8239: sub currentversion {
                   8240:     my $fname=shift;
                   8241:     my $version=-1;
                   8242:     my $ulsdir='';
                   8243:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   8244:        $ulsdir=$1;
                   8245:     }
1.114     albertel 8246:     my ($fnamere1,$fnamere2);
                   8247:     # remove version if already specified
1.101     www      8248:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 8249:     # get the bits that go before and after the version number
                   8250:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   8251: 	$fnamere1=$1;
                   8252: 	$fnamere2='.'.$2;
                   8253:     }
1.101     www      8254:     if (-e $fname) { $version=1; }
                   8255:     if (-e $ulsdir) {
1.134     albertel 8256: 	if(-d $ulsdir) {
                   8257: 	    if (opendir(LSDIR,$ulsdir)) {
                   8258: 		my $ulsfn;
                   8259: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      8260: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 8261: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   8262: 		    unless (-l $thisfile) {
1.160     www      8263: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 8264: 			    if ($1>$version) { $version=$1; }
                   8265: 			}
                   8266: 		    }
                   8267: 		}
                   8268: 		closedir(LSDIR);
                   8269: 		$version++;
                   8270: 	    }
                   8271: 	}
                   8272:     }
                   8273:     return $version;
1.101     www      8274: }
                   8275: 
                   8276: sub thisversion {
                   8277:     my $fname=shift;
                   8278:     my $version=-1;
                   8279:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   8280: 	$version=$1;
                   8281:     }
                   8282:     return $version;
                   8283: }
                   8284: 
1.84      albertel 8285: sub subscribe {
                   8286:     my ($userinput,$clientip)=@_;
                   8287:     my $result;
1.293     albertel 8288:     my ($cmd,$fname)=split(/:/,$userinput,2);
1.84      albertel 8289:     my $ownership=&ishome($fname);
                   8290:     if ($ownership eq 'owner') {
1.101     www      8291: # explitly asking for the current version?
                   8292:         unless (-e $fname) {
                   8293:             my $currentversion=&currentversion($fname);
                   8294: 	    if (&thisversion($fname)==$currentversion) {
                   8295:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   8296: 		    my $root=$1;
                   8297:                     my $extension=$2;
                   8298:                     symlink($root.'.'.$extension,
                   8299:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      8300:                     unless ($extension=~/\.meta$/) {
                   8301:                        symlink($root.'.'.$extension.'.meta',
                   8302:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   8303: 		    }
1.101     www      8304:                 }
                   8305:             }
                   8306:         }
1.84      albertel 8307: 	if (-e $fname) {
                   8308: 	    if (-d $fname) {
                   8309: 		$result="directory\n";
                   8310: 	    } else {
1.161     foxr     8311: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 8312: 		my $now=time;
1.161     foxr     8313: 		my $found=&addline($fname,$clientname,$clientip,
                   8314: 				   "$clientname:$clientip:$now\n");
1.84      albertel 8315: 		if ($found) { $result="$fname\n"; }
                   8316: 		# if they were subscribed to only meta data, delete that
                   8317:                 # subscription, when you subscribe to a file you also get
                   8318:                 # the metadata
                   8319: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   8320: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
1.476     raeburn  8321:                 my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
                   8322:                 $protocol = 'http' if ($protocol ne 'https');
                   8323: 		$fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
1.84      albertel 8324: 		$result="$fname\n";
                   8325: 	    }
                   8326: 	} else {
                   8327: 	    $result="not_found\n";
                   8328: 	}
                   8329:     } else {
                   8330: 	$result="rejected\n";
                   8331:     }
                   8332:     return $result;
                   8333: }
1.287     foxr     8334: #  Change the passwd of a unix user.  The caller must have
                   8335: #  first verified that the user is a loncapa user.
                   8336: #
                   8337: # Parameters:
                   8338: #    user      - Unix user name to change.
                   8339: #    pass      - New password for the user.
                   8340: # Returns:
                   8341: #    ok    - if success
                   8342: #    other - Some meaningfule error message string.
                   8343: # NOTE:
                   8344: #    invokes a setuid script to change the passwd.
                   8345: sub change_unix_password {
                   8346:     my ($user, $pass) = @_;
                   8347: 
                   8348:     &Debug("change_unix_password");
                   8349:     my $execdir=$perlvar{'lonDaemons'};
                   8350:     &Debug("Opening lcpasswd pipeline");
                   8351:     my $pf = IO::File->new("|$execdir/lcpasswd > "
                   8352: 			   ."$perlvar{'lonDaemons'}"
                   8353: 			   ."/logs/lcpasswd.log");
                   8354:     print $pf "$user\n$pass\n$pass\n";
                   8355:     close $pf;
                   8356:     my $err = $?;
                   8357:     return ($err < @passwderrors) ? $passwderrors[$err] : 
                   8358: 	"pwchange_falure - unknown error";
                   8359: 
                   8360:     
                   8361: }
                   8362: 
1.91      albertel 8363: 
                   8364: sub make_passwd_file {
1.518     raeburn  8365:     my ($uname,$udom,$umode,$npass,$passfilename,$action)=@_;
1.390     raeburn  8366:     my $result="ok";
1.91      albertel 8367:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   8368: 	{
                   8369: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8370: 	    if ($pf) {
                   8371: 		print $pf "$umode:$npass\n";
1.518     raeburn  8372:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     8373: 	    } else {
                   8374: 		$result = "pass_file_failed_error";
                   8375: 	    }
1.91      albertel 8376: 	}
                   8377:     } elsif ($umode eq 'internal') {
1.518     raeburn  8378:         my $ncpass = &hash_passwd($udom,$npass);
1.91      albertel 8379: 	{
                   8380: 	    &Debug("Creating internal auth");
                   8381: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8382: 	    if($pf) {
1.518     raeburn  8383: 		print $pf "internal:$ncpass\n";
                   8384:                 &update_passwd_history($uname,$udom,$umode,$action); 
1.261     foxr     8385: 	    } else {
                   8386: 		$result = "pass_file_failed_error";
                   8387: 	    }
1.91      albertel 8388: 	}
                   8389:     } elsif ($umode eq 'localauth') {
                   8390: 	{
                   8391: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8392: 	    if($pf) {
                   8393: 		print $pf "localauth:$npass\n";
1.524     raeburn  8394:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     8395: 	    } else {
                   8396: 		$result = "pass_file_failed_error";
                   8397: 	    }
1.91      albertel 8398: 	}
                   8399:     } elsif ($umode eq 'unix') {
1.502     raeburn  8400: 	&logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
                   8401: 	$result="no_new_unix_accounts";
1.91      albertel 8402:     } elsif ($umode eq 'none') {
                   8403: 	{
1.223     foxr     8404: 	    my $pf = IO::File->new("> $passfilename");
1.261     foxr     8405: 	    if($pf) {
                   8406: 		print $pf "none:\n";
                   8407: 	    } else {
                   8408: 		$result = "pass_file_failed_error";
                   8409: 	    }
1.91      albertel 8410: 	}
1.543     raeburn  8411:     } elsif ($umode eq 'lti') {
                   8412:         my $pf = IO::File->new(">$passfilename");
                   8413:         if($pf) {
                   8414:             print $pf "lti:\n";
                   8415:             &update_passwd_history($uname,$udom,$umode,$action);
                   8416:         } else {
                   8417:             $result = "pass_file_failed_error";
                   8418:         }
1.91      albertel 8419:     } else {
1.390     raeburn  8420: 	$result="auth_mode_error";
1.91      albertel 8421:     }
                   8422:     return $result;
1.121     albertel 8423: }
                   8424: 
1.265     albertel 8425: sub convert_photo {
                   8426:     my ($start,$dest)=@_;
                   8427:     system("convert $start $dest");
                   8428: }
                   8429: 
1.121     albertel 8430: sub sethost {
                   8431:     my ($remotereq) = @_;
                   8432:     my (undef,$hostid)=split(/:/,$remotereq);
1.322     albertel 8433:     # ignore sethost if we are already correct
                   8434:     if ($hostid eq $currenthostid) {
                   8435: 	return 'ok';
                   8436:     }
                   8437: 
1.121     albertel 8438:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
1.368     albertel 8439:     if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'}) 
                   8440: 	eq &Apache::lonnet::get_host_ip($hostid)) {
1.200     matthew  8441: 	$currenthostid  =$hostid;
1.369     albertel 8442: 	$currentdomainid=&Apache::lonnet::host_domain($hostid);
1.443     www      8443: #	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
1.121     albertel 8444:     } else {
                   8445: 	&logthis("Requested host id $hostid not an alias of ".
                   8446: 		 $perlvar{'lonHostID'}." refusing connection");
                   8447: 	return 'unable_to_set';
                   8448:     }
                   8449:     return 'ok';
                   8450: }
                   8451: 
                   8452: sub version {
                   8453:     my ($userinput)=@_;
                   8454:     $remoteVERSION=(split(/:/,$userinput))[1];
                   8455:     return "version:$VERSION";
1.127     albertel 8456: }
1.178     foxr     8457: 
1.447     raeburn  8458: sub get_usersession_config {
                   8459:     my ($dom,$name) = @_;
                   8460:     my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8461:     if (defined($cached)) {
                   8462:         return $usersessionconf;
                   8463:     } else {
                   8464:         my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
1.525     raeburn  8465:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
                   8466:         return $domconfig{'usersessions'};
1.447     raeburn  8467:     }
                   8468:     return;
                   8469: }
1.200     matthew  8470: 
1.534     raeburn  8471: sub get_usersearch_config {
                   8472:     my ($dom,$name) = @_;
                   8473:     my ($usersearchconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8474:     if (defined($cached)) {
                   8475:         return $usersearchconf;
                   8476:     } else {
                   8477:         my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$dom);
                   8478:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'directorysrch'},600);
                   8479:         return $domconfig{'directorysrch'};
                   8480:     }
                   8481:     return;
                   8482: }
                   8483: 
1.525     raeburn  8484: sub get_prohibited {
                   8485:     my ($dom) = @_;
                   8486:     my $name = 'trust';
                   8487:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8488:     unless (defined($cached)) {
                   8489:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$dom);
                   8490:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'trust'},3600);
                   8491:         $trustconfig = $domconfig{'trust'};
                   8492:     }
                   8493:     my %prohibited;
                   8494:     if (ref($trustconfig)) {
                   8495:         foreach my $prefix (keys(%{$trustconfig})) {
                   8496:             if (ref($trustconfig->{$prefix}) eq 'HASH') {
                   8497:                 my $reject;
                   8498:                 if (ref($trustconfig->{$prefix}->{'exc'}) eq 'ARRAY') {
                   8499:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'exc'}})) {
                   8500:                         $reject = 1;
                   8501:                     }
                   8502:                 }
                   8503:                 if (ref($trustconfig->{$prefix}->{'inc'}) eq 'ARRAY') {
                   8504:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'inc'}})) {
                   8505:                         $reject = 0;
                   8506:                     } else {
                   8507:                         $reject = 1;
                   8508:                     }
                   8509:                 }
                   8510:                 if ($reject) {
                   8511:                     $prohibited{$prefix} = 1;
                   8512:                 }
                   8513:             }
                   8514:         }
                   8515:     }
                   8516:     return %prohibited;
                   8517: }
1.450     raeburn  8518: 
1.471     raeburn  8519: sub distro_and_arch {
                   8520:     return $dist.':'.$arch;
                   8521: }
                   8522: 
1.61      harris41 8523: # ----------------------------------- POD (plain old documentation, CPAN style)
                   8524: 
                   8525: =head1 NAME
                   8526: 
                   8527: lond - "LON Daemon" Server (port "LOND" 5663)
                   8528: 
                   8529: =head1 SYNOPSIS
                   8530: 
1.74      harris41 8531: Usage: B<lond>
                   8532: 
                   8533: Should only be run as user=www.  This is a command-line script which
                   8534: is invoked by B<loncron>.  There is no expectation that a typical user
                   8535: will manually start B<lond> from the command-line.  (In other words,
                   8536: DO NOT START B<lond> YOURSELF.)
1.61      harris41 8537: 
                   8538: =head1 DESCRIPTION
                   8539: 
1.74      harris41 8540: There are two characteristics associated with the running of B<lond>,
                   8541: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   8542: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   8543: subscriptions, etc).  These are described in two large
                   8544: sections below.
                   8545: 
                   8546: B<PROCESS MANAGEMENT>
                   8547: 
1.61      harris41 8548: Preforker - server who forks first. Runs as a daemon. HUPs.
                   8549: Uses IDEA encryption
                   8550: 
1.74      harris41 8551: B<lond> forks off children processes that correspond to the other servers
                   8552: in the network.  Management of these processes can be done at the
                   8553: parent process level or the child process level.
                   8554: 
                   8555: B<logs/lond.log> is the location of log messages.
                   8556: 
                   8557: The process management is now explained in terms of linux shell commands,
                   8558: subroutines internal to this code, and signal assignments:
                   8559: 
                   8560: =over 4
                   8561: 
                   8562: =item *
                   8563: 
                   8564: PID is stored in B<logs/lond.pid>
                   8565: 
                   8566: This is the process id number of the parent B<lond> process.
                   8567: 
                   8568: =item *
                   8569: 
                   8570: SIGTERM and SIGINT
                   8571: 
                   8572: Parent signal assignment:
                   8573:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   8574: 
                   8575: Child signal assignment:
                   8576:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   8577: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   8578:  to restart a new child.)
                   8579: 
                   8580: Command-line invocations:
                   8581:  B<kill> B<-s> SIGTERM I<PID>
                   8582:  B<kill> B<-s> SIGINT I<PID>
                   8583: 
                   8584: Subroutine B<HUNTSMAN>:
                   8585:  This is only invoked for the B<lond> parent I<PID>.
                   8586: This kills all the children, and then the parent.
                   8587: The B<lonc.pid> file is cleared.
                   8588: 
                   8589: =item *
                   8590: 
                   8591: SIGHUP
                   8592: 
                   8593: Current bug:
                   8594:  This signal can only be processed the first time
                   8595: on the parent process.  Subsequent SIGHUP signals
                   8596: have no effect.
                   8597: 
                   8598: Parent signal assignment:
                   8599:  $SIG{HUP}  = \&HUPSMAN;
                   8600: 
                   8601: Child signal assignment:
                   8602:  none (nothing happens)
                   8603: 
                   8604: Command-line invocations:
                   8605:  B<kill> B<-s> SIGHUP I<PID>
                   8606: 
                   8607: Subroutine B<HUPSMAN>:
                   8608:  This is only invoked for the B<lond> parent I<PID>,
                   8609: This kills all the children, and then the parent.
                   8610: The B<lond.pid> file is cleared.
                   8611: 
                   8612: =item *
                   8613: 
                   8614: SIGUSR1
                   8615: 
                   8616: Parent signal assignment:
                   8617:  $SIG{USR1} = \&USRMAN;
                   8618: 
                   8619: Child signal assignment:
                   8620:  $SIG{USR1}= \&logstatus;
                   8621: 
                   8622: Command-line invocations:
                   8623:  B<kill> B<-s> SIGUSR1 I<PID>
                   8624: 
                   8625: Subroutine B<USRMAN>:
                   8626:  When invoked for the B<lond> parent I<PID>,
                   8627: SIGUSR1 is sent to all the children, and the status of
                   8628: each connection is logged.
1.144     foxr     8629: 
                   8630: =item *
                   8631: 
                   8632: SIGUSR2
                   8633: 
                   8634: Parent Signal assignment:
                   8635:     $SIG{USR2} = \&UpdateHosts
                   8636: 
                   8637: Child signal assignment:
                   8638:     NONE
                   8639: 
1.74      harris41 8640: 
                   8641: =item *
                   8642: 
                   8643: SIGCHLD
                   8644: 
                   8645: Parent signal assignment:
                   8646:  $SIG{CHLD} = \&REAPER;
                   8647: 
                   8648: Child signal assignment:
                   8649:  none
                   8650: 
                   8651: Command-line invocations:
                   8652:  B<kill> B<-s> SIGCHLD I<PID>
                   8653: 
                   8654: Subroutine B<REAPER>:
                   8655:  This is only invoked for the B<lond> parent I<PID>.
                   8656: Information pertaining to the child is removed.
                   8657: The socket port is cleaned up.
                   8658: 
                   8659: =back
                   8660: 
                   8661: B<SERVER-SIDE ACTIVITIES>
                   8662: 
                   8663: Server-side information can be accepted in an encrypted or non-encrypted
                   8664: method.
                   8665: 
                   8666: =over 4
                   8667: 
                   8668: =item ping
                   8669: 
                   8670: Query a client in the hosts.tab table; "Are you there?"
                   8671: 
                   8672: =item pong
                   8673: 
                   8674: Respond to a ping query.
                   8675: 
                   8676: =item ekey
                   8677: 
                   8678: Read in encrypted key, make cipher.  Respond with a buildkey.
                   8679: 
                   8680: =item load
                   8681: 
                   8682: Respond with CPU load based on a computation upon /proc/loadavg.
                   8683: 
                   8684: =item currentauth
                   8685: 
                   8686: Reply with current authentication information (only over an
                   8687: encrypted channel).
                   8688: 
                   8689: =item auth
                   8690: 
                   8691: Only over an encrypted channel, reply as to whether a user's
                   8692: authentication information can be validated.
                   8693: 
                   8694: =item passwd
                   8695: 
                   8696: Allow for a password to be set.
                   8697: 
                   8698: =item makeuser
                   8699: 
                   8700: Make a user.
                   8701: 
1.517     raeburn  8702: =item changeuserauth
1.74      harris41 8703: 
                   8704: Allow for authentication mechanism and password to be changed.
                   8705: 
                   8706: =item home
1.61      harris41 8707: 
1.74      harris41 8708: Respond to a question "are you the home for a given user?"
                   8709: 
                   8710: =item update
                   8711: 
                   8712: Update contents of a subscribed resource.
                   8713: 
                   8714: =item unsubscribe
                   8715: 
                   8716: The server is unsubscribing from a resource.
                   8717: 
                   8718: =item subscribe
                   8719: 
                   8720: The server is subscribing to a resource.
                   8721: 
                   8722: =item log
                   8723: 
                   8724: Place in B<logs/lond.log>
                   8725: 
                   8726: =item put
                   8727: 
                   8728: stores hash in namespace
                   8729: 
1.496     raeburn  8730: =item rolesput
1.74      harris41 8731: 
                   8732: put a role into a user's environment
                   8733: 
                   8734: =item get
                   8735: 
                   8736: returns hash with keys from array
                   8737: reference filled in from namespace
                   8738: 
                   8739: =item eget
                   8740: 
                   8741: returns hash with keys from array
                   8742: reference filled in from namesp (encrypts the return communication)
                   8743: 
                   8744: =item rolesget
                   8745: 
                   8746: get a role from a user's environment
                   8747: 
                   8748: =item del
                   8749: 
                   8750: deletes keys out of array from namespace
                   8751: 
                   8752: =item keys
                   8753: 
                   8754: returns namespace keys
                   8755: 
                   8756: =item dump
                   8757: 
                   8758: dumps the complete (or key matching regexp) namespace into a hash
                   8759: 
                   8760: =item store
                   8761: 
                   8762: stores hash permanently
                   8763: for this url; hashref needs to be given and should be a \%hashname; the
                   8764: remaining args aren't required and if they aren't passed or are '' they will
                   8765: be derived from the ENV
                   8766: 
                   8767: =item restore
                   8768: 
                   8769: returns a hash for a given url
                   8770: 
                   8771: =item querysend
                   8772: 
                   8773: Tells client about the lonsql process that has been launched in response
                   8774: to a sent query.
                   8775: 
                   8776: =item queryreply
                   8777: 
                   8778: Accept information from lonsql and make appropriate storage in temporary
                   8779: file space.
                   8780: 
                   8781: =item idput
                   8782: 
                   8783: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   8784: for each student, defined perhaps by the institutional Registrar.)
                   8785: 
                   8786: =item idget
                   8787: 
                   8788: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   8789: for each student, defined perhaps by the institutional Registrar.)
                   8790: 
1.517     raeburn  8791: =item iddel
                   8792: 
                   8793: Deletes one or more ids in a domain's id database.
                   8794: 
1.74      harris41 8795: =item tmpput
                   8796: 
                   8797: Accept and store information in temporary space.
                   8798: 
                   8799: =item tmpget
                   8800: 
                   8801: Send along temporarily stored information.
                   8802: 
                   8803: =item ls
                   8804: 
                   8805: List part of a user's directory.
                   8806: 
1.135     foxr     8807: =item pushtable
                   8808: 
                   8809: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   8810: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   8811: must be restored manually in case of a problem with the new table file.
                   8812: pushtable requires that the request be encrypted and validated via
                   8813: ValidateManager.  The form of the command is:
                   8814: enc:pushtable tablename <tablecontents> \n
                   8815: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   8816: cleartext newline.
                   8817: 
1.74      harris41 8818: =item Hanging up (exit or init)
                   8819: 
                   8820: What to do when a client tells the server that they (the client)
                   8821: are leaving the network.
                   8822: 
                   8823: =item unknown command
                   8824: 
                   8825: If B<lond> is sent an unknown command (not in the list above),
                   8826: it replys to the client "unknown_cmd".
1.135     foxr     8827: 
1.74      harris41 8828: 
                   8829: =item UNKNOWN CLIENT
                   8830: 
                   8831: If the anti-spoofing algorithm cannot verify the client,
                   8832: the client is rejected (with a "refused" message sent
                   8833: to the client, and the connection is closed.
                   8834: 
                   8835: =back
1.61      harris41 8836: 
                   8837: =head1 PREREQUISITES
                   8838: 
                   8839: IO::Socket
                   8840: IO::File
                   8841: Apache::File
                   8842: POSIX
                   8843: Crypt::IDEA
                   8844: GDBM_File
                   8845: Authen::Krb4
1.91      albertel 8846: Authen::Krb5
1.61      harris41 8847: 
                   8848: =head1 COREQUISITES
                   8849: 
1.490     droeschl 8850: none
                   8851: 
1.61      harris41 8852: =head1 OSNAMES
                   8853: 
                   8854: linux
                   8855: 
                   8856: =head1 SCRIPT CATEGORIES
                   8857: 
                   8858: Server/Process
                   8859: 
                   8860: =cut
1.409     foxr     8861: 
                   8862: 
                   8863: =pod
                   8864: 
                   8865: =head1 LOG MESSAGES
                   8866: 
                   8867: The messages below can be emitted in the lond log.  This log is located
                   8868: in ~httpd/perl/logs/lond.log  Many log messages have HTML encapsulation
                   8869: to provide coloring if examined from inside a web page. Some do not.
                   8870: Where color is used, the colors are; Red for sometihhng to get excited
                   8871: about and to follow up on. Yellow for something to keep an eye on to
                   8872: be sure it does not get worse, Green,and Blue for informational items.
                   8873: 
                   8874: In the discussions below, sometimes reference is made to ~httpd
                   8875: when describing file locations.  There isn't really an httpd 
                   8876: user, however there is an httpd directory that gets installed in the
                   8877: place that user home directories go.  On linux, this is usually
                   8878: (always?) /home/httpd.
                   8879: 
                   8880: 
                   8881: Some messages are colorless.  These are usually (not always)
                   8882: Green/Blue color level messages.
                   8883: 
                   8884: =over 2
                   8885: 
                   8886: =item (Red)  LocalConnection rejecting non local: <ip> ne 127.0.0.1
                   8887: 
                   8888: A local connection negotiation was attempted by
                   8889: a host whose IP address was not 127.0.0.1.
                   8890: The socket is closed and the child will exit.
                   8891: lond has three ways to establish an encyrption
                   8892: key with a client:
                   8893: 
                   8894: =over 2
                   8895: 
                   8896: =item local 
                   8897: 
                   8898: The key is written and read from a file.
                   8899: This is only valid for connections from localhost.
                   8900: 
                   8901: =item insecure 
                   8902: 
                   8903: The key is generated by the server and
                   8904: transmitted to the client.
                   8905: 
                   8906: =item  ssl (secure)
                   8907: 
                   8908: An ssl connection is negotiated with the client,
                   8909: the key is generated by the server and sent to the 
                   8910: client across this ssl connection before the
                   8911: ssl connectionis terminated and clear text
                   8912: transmission resumes.
                   8913: 
                   8914: =back
                   8915: 
                   8916: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
                   8917: 
                   8918: The client is local but has not sent an initialization
                   8919: string that is the literal "init:local"  The connection
                   8920: is closed and the child exits.
                   8921: 
                   8922: =item Red CRITICAL Can't get key file <error>        
                   8923: 
                   8924: SSL key negotiation is being attempted but the call to
                   8925: lonssl::KeyFile  failed.  This usually means that the
                   8926: configuration file is not correctly defining or protecting
                   8927: the directories/files lonCertificateDirectory or
                   8928: lonnetPrivateKey
                   8929: <error> is a string that describes the reason that
                   8930: the key file could not be located.
                   8931: 
                   8932: =item (Red) CRITICAL  Can't get certificates <error>  
                   8933: 
                   8934: SSL key negotiation failed because we were not able to retrives our certificate
                   8935: or the CA's certificate in the call to lonssl::CertificateFile
                   8936: <error> is the textual reason this failed.  Usual reasons:
                   8937: 
                   8938: =over 2
1.490     droeschl 8939: 
1.409     foxr     8940: =item Apache config file for loncapa  incorrect:
1.490     droeschl 8941: 
1.409     foxr     8942: one of the variables 
                   8943: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
                   8944: undefined or incorrect
                   8945: 
                   8946: =item Permission error:
                   8947: 
                   8948: The directory pointed to by lonCertificateDirectory is not readable by lond
                   8949: 
                   8950: =item Permission error:
                   8951: 
                   8952: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
                   8953: 
                   8954: =item Installation error:                         
                   8955: 
                   8956: Either the certificate authority file or the certificate have not
                   8957: been installed in lonCertificateDirectory.
                   8958: 
                   8959: =item (Red) CRITICAL SSL Socket promotion failed:  <err> 
                   8960: 
                   8961: The promotion of the connection from plaintext to SSL failed
                   8962: <err> is the reason for the failure.  There are two
                   8963: system calls involved in the promotion (one of which failed), 
                   8964: a dup to produce
                   8965: a second fd on the raw socket over which the encrypted data
                   8966: will flow and IO::SOcket::SSL->new_from_fd which creates
                   8967: the SSL connection on the duped fd.
                   8968: 
                   8969: =item (Blue)   WARNING client did not respond to challenge 
                   8970: 
                   8971: This occurs on an insecure (non SSL) connection negotiation request.
                   8972: lond generates some number from the time, the PID and sends it to
                   8973: the client.  The client must respond by echoing this information back.
                   8974: If the client does not do so, that's a violation of the challenge
                   8975: protocols and the connection will be failed.
                   8976: 
                   8977: =item (Red) No manager table. Nobody can manage!!    
                   8978: 
                   8979: lond has the concept of privileged hosts that
                   8980: can perform remote management function such
                   8981: as update the hosts.tab.   The manager hosts
                   8982: are described in the 
                   8983: ~httpd/lonTabs/managers.tab file.
                   8984: this message is logged if this file is missing.
                   8985: 
                   8986: 
                   8987: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
                   8988: 
                   8989: Reports the successful parse and registration
                   8990: of a specific manager. 
                   8991: 
                   8992: =item Green existing host <clustername:dnsname>  
                   8993: 
                   8994: The manager host is already defined in the hosts.tab
                   8995: the information in that table, rather than the info in the
                   8996: manager table will be used to determine the manager's ip.
                   8997: 
                   8998: =item (Red) Unable to craete <filename>                 
                   8999: 
                   9000: lond has been asked to create new versions of an administrative
                   9001: file (by a manager).  When this is done, the new file is created
                   9002: in a temp file and then renamed into place so that there are always
                   9003: usable administrative files, even if the update fails.  This failure
                   9004: message means that the temp file could not be created.
                   9005: The update is abandoned, and the old file is available for use.
                   9006: 
                   9007: =item (Green) CopyFile from <oldname> to <newname> failed
                   9008: 
                   9009: In an update of administrative files, the copy of the existing file to a
                   9010: backup file failed.  The installation of the new file may still succeed,
                   9011: but there will not be a back up file to rever to (this should probably
                   9012: be yellow).
                   9013: 
                   9014: =item (Green) Pushfile: backed up <oldname> to <newname>
                   9015: 
                   9016: See above, the backup of the old administrative file succeeded.
                   9017: 
                   9018: =item (Red)  Pushfile: Unable to install <filename> <reason>
                   9019: 
                   9020: The new administrative file could not be installed.  In this case,
                   9021: the old administrative file is still in use.
                   9022: 
                   9023: =item (Green) Installed new < filename>.                      
                   9024: 
                   9025: The new administrative file was successfullly installed.                                               
                   9026: 
                   9027: =item (Red) Reinitializing lond pid=<pid>                    
                   9028: 
                   9029: The lonc child process <pid> will be sent a USR2 
                   9030: signal.
                   9031: 
                   9032: =item (Red) Reinitializing self                                    
                   9033: 
                   9034: We've been asked to re-read our administrative files,and
                   9035: are doing so.
                   9036: 
                   9037: =item (Yellow) error:Invalid process identifier <ident>  
                   9038: 
                   9039: A reinit command was received, but the target part of the 
                   9040: command was not valid.  It must be either
                   9041: 'lond' or 'lonc' but was <ident>
                   9042: 
                   9043: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
                   9044: 
                   9045: Checking to see if lond has been handed a valid edit
                   9046: command.  It is possible the edit command is not valid
                   9047: in that case there are no log messages to indicate that.
                   9048: 
                   9049: =item Result of password change for  <username> pwchange_success
                   9050: 
                   9051: The password for <username> was
                   9052: successfully changed.
                   9053: 
                   9054: =item Unable to open <user> passwd to change password
                   9055: 
                   9056: Could not rewrite the 
                   9057: internal password file for a user
                   9058: 
                   9059: =item Result of password change for <user> : <result>
1.490     droeschl 9060: 
1.409     foxr     9061: A unix password change for <user> was attempted 
                   9062: and the pipe returned <result>  
                   9063: 
                   9064: =item LWP GET: <message> for <fname> (<remoteurl>)
                   9065: 
                   9066: The lightweight process fetch for a resource failed
                   9067: with <message> the local filename that should
                   9068: have existed/been created was  <fname> the
                   9069: corresponding URI: <remoteurl>  This is emitted in several
                   9070: places.
                   9071: 
                   9072: =item Unable to move <transname> to <destname>     
                   9073: 
                   9074: From fetch_user_file_handler - the user file was replicated but could not
                   9075: be mv'd to its final location.
                   9076: 
                   9077: =item Looking for <domain> <username>              
                   9078: 
                   9079: From user_has_session_handler - This should be a Debug call instead
                   9080: it indicates lond is about to check whether the specified user has a 
                   9081: session active on the specified domain on the local host.
                   9082: 
                   9083: =item Client <ip> (<name>) hanging up: <input>     
                   9084: 
                   9085: lond has been asked to exit by its client.  The <ip> and <name> identify the
                   9086: client systemand <input> is the full exit command sent to the server.
                   9087: 
                   9088: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
1.490     droeschl 9089: 
1.409     foxr     9090: A lond child terminated.  NOte that this termination can also occur when the
                   9091: child receives the QUIT or DIE signals.  <pid> is the process id of the child,
                   9092: <hostname> the host lond is working for, and <message> the reason the child died
                   9093: to the best of our ability to get it (I would guess that any numeric value
                   9094: represents and errno value).  This is immediately followed by
                   9095: 
                   9096: =item  Famous last words: Catching exception - <log> 
                   9097: 
                   9098: Where log is some recent information about the state of the child.
                   9099: 
                   9100: =item Red CRITICAL: TIME OUT <pid>                     
                   9101: 
                   9102: Some timeout occured for server <pid>.  THis is normally a timeout on an LWP
                   9103: doing an HTTP::GET.
                   9104: 
                   9105: =item child <pid> died                              
                   9106: 
                   9107: The reaper caught a SIGCHILD for the lond child process <pid>
                   9108: This should be modified to also display the IP of the dying child
                   9109: $children{$pid}
                   9110: 
                   9111: =item Unknown child 0 died                           
                   9112: A child died but the wait for it returned a pid of zero which really should not
                   9113: ever happen. 
                   9114: 
                   9115: =item Child <which> - <pid> looks like we missed it's death 
                   9116: 
                   9117: When a sigchild is received, the reaper process checks all children to see if they are
                   9118: alive.  If children are dying quite quickly, the lack of signal queuing can mean
                   9119: that a signal hearalds the death of more than one child.  If so this message indicates
                   9120: which other one died. <which> is the ip of a dead child
                   9121: 
                   9122: =item Free socket: <shutdownretval>                
                   9123: 
                   9124: The HUNTSMAN sub was called due to a SIGINT in a child process.  The socket is being shutdown.
                   9125: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
                   9126: to return anything. This is followed by: 
                   9127: 
                   9128: =item Red CRITICAL: Shutting down                       
                   9129: 
                   9130: Just prior to exit.
                   9131: 
                   9132: =item Free socket: <shutdownretval>                 
                   9133: 
                   9134: The HUPSMAN sub was called due to a SIGHUP.  all children get killsed, and lond execs itself.
                   9135: This is followed by:
                   9136: 
                   9137: =item (Red) CRITICAL: Restarting                         
                   9138: 
                   9139: lond is about to exec itself to restart.
                   9140: 
                   9141: =item (Blue) Updating connections                        
                   9142: 
                   9143: (In response to a USR2).  All the children (except the one for localhost)
                   9144: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
                   9145: 
                   9146: =item (Blue) UpdateHosts killing child <pid> for ip <ip>   
                   9147: 
                   9148: Due to USR2 as above.
                   9149: 
                   9150: =item (Green) keeping child for ip <ip> (pid = <pid>)    
                   9151: 
                   9152: In response to USR2 as above, the child indicated is not being restarted because
                   9153: it's assumed that we'll always need a child for the localhost.
                   9154: 
                   9155: 
                   9156: =item Going to check on the children                
                   9157: 
                   9158: Parent is about to check on the health of the child processes.
                   9159: Note that this is in response to a USR1 sent to the parent lond.
                   9160: there may be one or more of the next two messages:
                   9161: 
                   9162: =item <pid> is dead                                 
                   9163: 
                   9164: A child that we have in our child hash as alive has evidently died.
                   9165: 
                   9166: =item  Child <pid> did not respond                   
                   9167: 
                   9168: In the health check the child <pid> did not update/produce a pid_.txt
                   9169: file when sent it's USR1 signal.  That process is killed with a 9 signal, as it's
                   9170: assumed to be hung in some un-fixable way.
                   9171: 
                   9172: =item Finished checking children                   
1.490     droeschl 9173: 
1.409     foxr     9174: Master processs's USR1 processing is cojmplete.
                   9175: 
                   9176: =item (Red) CRITICAL: ------- Starting ------            
                   9177: 
                   9178: (There are more '-'s on either side).  Lond has forked itself off to 
                   9179: form a new session and is about to start actual initialization.
                   9180: 
                   9181: =item (Green) Attempting to start child (<client>)       
                   9182: 
                   9183: Started a new child process for <client>.  Client is IO::Socket object
                   9184: connected to the child.  This was as a result of a TCP/IP connection from a client.
                   9185: 
                   9186: =item Unable to determine who caller was, getpeername returned nothing
1.490     droeschl 9187: 
1.409     foxr     9188: In child process initialization.  either getpeername returned undef or
                   9189: a zero sized object was returned.  Processing continues, but in my opinion,
                   9190: this should be cause for the child to exit.
                   9191: 
                   9192: =item Unable to determine clientip                  
                   9193: 
                   9194: In child process initialization.  The peer address from getpeername was not defined.
                   9195: The client address is stored as "Unavailable" and processing continues.
                   9196: 
                   9197: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
1.490     droeschl 9198: 
1.409     foxr     9199: In child initialization.  A good connectionw as received from <ip>.
                   9200: 
                   9201: =over 2
                   9202: 
                   9203: =item <name> 
                   9204: 
                   9205: is the name of the client from hosts.tab.
                   9206: 
                   9207: =item <type> 
                   9208: 
                   9209: Is the connection type which is either 
                   9210: 
                   9211: =over 2
                   9212: 
                   9213: =item manager 
                   9214: 
                   9215: The connection is from a manager node, not in hosts.tab
                   9216: 
                   9217: =item client  
                   9218: 
                   9219: the connection is from a non-manager in the hosts.tab
                   9220: 
                   9221: =item both
                   9222: 
                   9223: The connection is from a manager in the hosts.tab.
                   9224: 
                   9225: =back
                   9226: 
                   9227: =back
                   9228: 
                   9229: =item (Blue) Certificates not installed -- trying insecure auth
                   9230: 
                   9231: One of the certificate file, key file or
                   9232: certificate authority file could not be found for a client attempting
                   9233: SSL connection intiation.  COnnection will be attemptied in in-secure mode.
                   9234: (this would be a system with an up to date lond that has not gotten a 
                   9235: certificate from us).
                   9236: 
                   9237: =item (Green)  Successful local authentication            
                   9238: 
                   9239: A local connection successfully negotiated the encryption key. 
                   9240: In this case the IDEA key is in a file (that is hopefully well protected).
                   9241: 
                   9242: =item (Green) Successful ssl authentication with <client>  
                   9243: 
                   9244: The client (<client> is the peer's name in hosts.tab), has successfully
                   9245: negotiated an SSL connection with this child process.
                   9246: 
                   9247: =item (Green) Successful insecure authentication with <client>
1.490     droeschl 9248: 
1.409     foxr     9249: 
                   9250: The client has successfully negotiated an  insecure connection withthe child process.
                   9251: 
                   9252: =item (Yellow) Attempted insecure connection disallowed    
                   9253: 
                   9254: The client attempted and failed to successfully negotiate a successful insecure
                   9255: connection.  This can happen either because the variable londAllowInsecure is false
                   9256: or undefined, or becuse the child did not successfully echo back the challenge
                   9257: string.
                   9258: 
                   9259: 
                   9260: =back
                   9261: 
1.441     raeburn  9262: =back
                   9263: 
1.409     foxr     9264: 
                   9265: =cut

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