Annotation of loncom/lond, revision 1.562

1.1       albertel    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60      www         4: #
1.562   ! raeburn     5: # $Id: lond,v 1.561 2020/03/30 11:04:03 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.562   ! raeburn    68: my $VERSION='$Revision: 1.561 $'; #' 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.
1.556     raeburn    83: my $clientremoteok;             # Current domain permits hosting on client
                     84:                                 # (not set if host and client share "internet domain").
                     85:                                 # Values are 0 or 1; 1 if allowed.
                     86: my %clientprohibited;           # Commands from client prohibited for domain's
                     87:                                 # users.
                     88: 
1.134     albertel   89: my $server;
1.200     matthew    90: 
                     91: my $keymode;
1.198     foxr       92: 
1.207     foxr       93: my $cipher;			# Cipher key negotiated with client
                     94: my $tmpsnum = 0;		# Id of tmpputs.
                     95: 
1.178     foxr       96: # 
                     97: #   Connection type is:
                     98: #      client                   - All client actions are allowed
                     99: #      manager                  - only management functions allowed.
                    100: #      both                     - Both management and client actions are allowed
                    101: #
1.161     foxr      102: 
1.178     foxr      103: my $ConnectionType;
1.161     foxr      104: 
1.178     foxr      105: my %managers;			# Ip -> manager names
1.161     foxr      106: 
1.178     foxr      107: my %perlvar;			# Will have the apache conf defined perl vars.
1.134     albertel  108: 
1.532     raeburn   109: my %secureconf;                 # Will have requirements for security 
                    110:                                 # of lond connections
                    111: 
1.545     raeburn   112: my %crlchecked;                 # Will contain clients for which the client's SSL
                    113:                                 # has been checked against the cluster's Certificate
                    114:                                 # Revocation List.
                    115: 
1.480     raeburn   116: my $dist;
                    117: 
1.178     foxr      118: #
1.207     foxr      119: #   The hash below is used for command dispatching, and is therefore keyed on the request keyword.
                    120: #    Each element of the hash contains a reference to an array that contains:
                    121: #          A reference to a sub that executes the request corresponding to the keyword.
                    122: #          A flag that is true if the request must be encoded to be acceptable.
                    123: #          A mask with bits as follows:
                    124: #                      CLIENT_OK    - Set when the function is allowed by ordinary clients
                    125: #                      MANAGER_OK   - Set when the function is allowed to manager clients.
                    126: #
                    127: my $CLIENT_OK  = 1;
                    128: my $MANAGER_OK = 2;
                    129: my %Dispatcher;
                    130: 
                    131: 
                    132: #
1.178     foxr      133: #  The array below are password error strings."
                    134: #
                    135: my $lastpwderror    = 13;		# Largest error number from lcpasswd.
                    136: my @passwderrors = ("ok",
1.287     foxr      137: 		   "pwchange_failure - lcpasswd must be run as user 'www'",
                    138: 		   "pwchange_failure - lcpasswd got incorrect number of arguments",
                    139: 		   "pwchange_failure - lcpasswd did not get the right nubmer of input text lines",
                    140: 		   "pwchange_failure - lcpasswd too many simultaneous pwd changes in progress",
                    141: 		   "pwchange_failure - lcpasswd User does not exist.",
                    142: 		   "pwchange_failure - lcpasswd Incorrect current passwd",
                    143: 		   "pwchange_failure - lcpasswd Unable to su to root.",
                    144: 		   "pwchange_failure - lcpasswd Cannot set new passwd.",
                    145: 		   "pwchange_failure - lcpasswd Username has invalid characters",
                    146: 		   "pwchange_failure - lcpasswd Invalid characters in password",
                    147: 		   "pwchange_failure - lcpasswd User already exists", 
                    148:                    "pwchange_failure - lcpasswd Something went wrong with user addition.",
                    149: 		   "pwchange_failure - lcpasswd Password mismatch",
                    150: 		   "pwchange_failure - lcpasswd Error filename is invalid");
1.97      foxr      151: 
                    152: 
1.412     foxr      153: # This array are the errors from lcinstallfile:
                    154: 
                    155: my @installerrors = ("ok",
                    156: 		     "Initial user id of client not that of www",
                    157: 		     "Usage error, not enough command line arguments",
1.500     bisitz    158: 		     "Source filename does not exist",
                    159: 		     "Destination filename does not exist",
1.412     foxr      160: 		     "Some file operation failed",
                    161: 		     "Invalid table filename."
                    162: 		     );
1.207     foxr      163: 
                    164: #
1.525     raeburn   165: # The %trust hash classifies commands according to type of trust 
                    166: # required for execution of the command.
                    167: #
                    168: # When clients from a different institution request execution of a
                    169: # particular command, the trust settings for that institution set
                    170: # for this domain (or default domain for a multi-domain server) will
                    171: # be checked to see if running the command is allowed.
                    172: #
                    173: # Trust types which depend on the "Trust" domain configuration
                    174: # for the machine's default domain are:
                    175: #
                    176: # content   ("Access to this domain's content by others")
                    177: # shared    ("Access to other domain's content by this domain")
                    178: # enroll    ("Enrollment in this domain's courses by others")
                    179: # coaurem   ("Co-author roles for this domain's users elsewhere")
1.552     raeburn   180: # othcoau   ("Co-author roles in this domain for others")
1.525     raeburn   181: # domroles  ("Domain roles in this domain assignable to others")
                    182: # catalog   ("Course Catalog for this domain displayed elsewhere")
                    183: # reqcrs    ("Requests for creation of courses in this domain by others")
                    184: # msg       ("Users in other domains can send messages to this domain")
                    185: # 
                    186: # Trust type which depends on the User Session Hosting (remote) 
                    187: # domain configuration for machine's default domain is: "remote".
                    188: #
                    189: # Trust types which depend on contents of manager.tab in 
                    190: # /home/httpd/lonTabs is: "manageronly".
                    191: # 
                    192: # Trust type which requires client to share the same LON-CAPA
                    193: # "internet domain" (i.e., same institution as this server) is:
                    194: # "institutiononly".
                    195: #
                    196: 
                    197: my %trust = (
                    198:                auth => {remote => 1},
                    199:                autocreatepassword => {remote => 1},
                    200:                autocrsreqchecks => {remote => 1, reqcrs => 1},
                    201:                autocrsrequpdate => {remote => 1},
                    202:                autocrsreqvalidation => {remote => 1},
                    203:                autogetsections => {remote => 1},
                    204:                autoinstcodedefaults => {remote => 1, catalog => 1},
                    205:                autoinstcodeformat => {remote => 1, catalog => 1},
                    206:                autonewcourse => {remote => 1, reqcrs => 1},
                    207:                autophotocheck => {remote => 1, enroll => 1},
                    208:                autophotochoice => {remote => 1},
                    209:                autophotopermission => {remote => 1, enroll => 1},
                    210:                autopossibleinstcodes => {remote => 1, reqcrs => 1},
                    211:                autoretrieve => {remote => 1, enroll => 1, catalog => 1},
                    212:                autorun => {remote => 1, enroll => 1, reqcrs => 1},
                    213:                autovalidateclass_sec => {catalog => 1},
                    214:                autovalidatecourse => {remote => 1, enroll => 1},
                    215:                autovalidateinstcode => {domroles => 1, remote => 1, enroll => 1},
                    216:                changeuserauth => {remote => 1, domroles => 1},
                    217:                chatretr => {remote => 1, enroll => 1},
                    218:                chatsend => {remote => 1, enroll => 1},
                    219:                courseiddump => {remote => 1, domroles => 1, enroll => 1},
                    220:                courseidput => {remote => 1, domroles => 1, enroll => 1},
                    221:                courseidputhash => {remote => 1, domroles => 1, enroll => 1},
                    222:                courselastaccess => {remote => 1, domroles => 1, enroll => 1},
1.561     raeburn   223:                coursesessions => {institutiononly => 1},
1.525     raeburn   224:                currentauth => {remote => 1, domroles => 1, enroll => 1},
                    225:                currentdump => {remote => 1, enroll => 1},
                    226:                currentversion => {remote=> 1, content => 1},
                    227:                dcmaildump => {remote => 1, domroles => 1},
                    228:                dcmailput => {remote => 1, domroles => 1},
                    229:                del => {remote => 1, domroles => 1, enroll => 1, content => 1},
1.551     raeburn   230:                delbalcookie => {institutiononly => 1},
1.560     raeburn   231:                delusersession => {institutiononly => 1},
1.525     raeburn   232:                deldom => {remote => 1, domroles => 1}, # not currently used
                    233:                devalidatecache => {institutiononly => 1},
                    234:                domroleput => {remote => 1, enroll => 1},
                    235:                domrolesdump => {remote => 1, catalog => 1},
                    236:                du => {remote => 1, enroll => 1},
                    237:                du2 => {remote => 1, enroll => 1},
                    238:                dump => {remote => 1, enroll => 1, domroles => 1},
                    239:                edit => {institutiononly => 1},  #not used currently
                    240:                eget => {remote => 1, domroles => 1, enroll => 1}, #not used currently
1.536     raeburn   241:                egetdom => {remote => 1, domroles => 1, enroll => 1, },
1.553     raeburn   242:                ekey => {anywhere => 1},
1.525     raeburn   243:                exit => {anywhere => 1},
                    244:                fetchuserfile => {remote => 1, enroll => 1},
                    245:                get => {remote => 1, domroles => 1, enroll => 1},
                    246:                getdom => {anywhere => 1},
                    247:                home => {anywhere => 1},
                    248:                iddel => {remote => 1, enroll => 1},
                    249:                idget => {remote => 1, enroll => 1},
                    250:                idput => {remote => 1, domroles => 1, enroll => 1},
                    251:                inc => {remote => 1, enroll => 1},
                    252:                init => {anywhere => 1},
                    253:                inst_usertypes => {remote => 1, domroles => 1, enroll => 1},
                    254:                instemailrules => {remote => 1, domroles => 1},
                    255:                instidrulecheck => {remote => 1, domroles => 1,},
                    256:                instidrules => {remote => 1, domroles => 1,},
                    257:                instrulecheck => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
                    258:                instselfcreatecheck => {institutiononly => 1},
                    259:                instuserrules => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
                    260:                keys => {remote => 1,},
                    261:                load => {anywhere => 1},
                    262:                log => {anywhere => 1},
                    263:                ls => {remote => 1, enroll => 1, content => 1,},
                    264:                ls2 => {remote => 1, enroll => 1, content => 1,},
                    265:                ls3 => {remote => 1, enroll => 1, content => 1,},
                    266:                makeuser => {remote => 1, enroll => 1, domroles => 1,},
                    267:                mkdiruserfile => {remote => 1, enroll => 1,},
                    268:                newput => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1,},
                    269:                passwd => {remote => 1},
                    270:                ping => {anywhere => 1},
                    271:                pong => {anywhere => 1},
                    272:                pushfile => {manageronly => 1},
                    273:                put => {remote => 1, enroll => 1, domroles => 1, msg => 1, content => 1, shared => 1},
                    274:                putdom => {remote => 1, domroles => 1,},
                    275:                putstore => {remote => 1, enroll => 1},
                    276:                queryreply => {anywhere => 1},
                    277:                querysend => {anywhere => 1},
1.535     raeburn   278:                querysend_activitylog => {remote => 1},
                    279:                querysend_allusers => {remote => 1, domroles => 1},
                    280:                querysend_courselog => {remote => 1},
                    281:                querysend_fetchenrollment => {remote => 1},
                    282:                querysend_getinstuser => {remote => 1},
                    283:                querysend_getmultinstusers => {remote => 1},
                    284:                querysend_instdirsearch => {remote => 1, domroles => 1, coaurem => 1},
                    285:                querysend_institutionalphotos => {remote => 1},
                    286:                querysend_portfolio_metadata => {remote => 1, content => 1},
                    287:                querysend_userlog => {remote => 1, domroles => 1},
                    288:                querysend_usersearch => {remote => 1, enroll => 1, coaurem => 1},
1.525     raeburn   289:                quit => {anywhere => 1},
                    290:                readlonnetglobal => {institutiononly => 1},
                    291:                reinit => {manageronly => 1}, #not used currently
                    292:                removeuserfile => {remote => 1, enroll => 1},
                    293:                renameuserfile => {remote => 1,},
                    294:                restore => {remote => 1, enroll => 1, reqcrs => 1,},
                    295:                rolesdel => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
                    296:                rolesput => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
1.527     raeburn   297:                servercerts => {institutiononly => 1},
1.528     raeburn   298:                serverdistarch => {anywhere => 1},
1.525     raeburn   299:                serverhomeID => {anywhere => 1},
                    300:                serverloncaparev => {anywhere => 1},
                    301:                servertimezone => {remote => 1, enroll => 1},
                    302:                setannounce => {remote => 1, domroles => 1},
                    303:                sethost => {anywhere => 1},
                    304:                store => {remote => 1, enroll => 1, reqcrs => 1,},
                    305:                studentphoto => {remote => 1, enroll => 1},
                    306:                sub => {content => 1,},
1.552     raeburn   307:                tmpdel => {institutiononly => 1},
                    308:                tmpget => {institutiononly => 1},
                    309:                tmpput => {remote => 1, othcoau => 1},
1.525     raeburn   310:                tokenauthuserfile => {anywhere => 1},
                    311:                unsub => {content => 1,},
                    312:                update => {shared => 1},
                    313:                updateclickers => {remote => 1},
                    314:                userhassession => {anywhere => 1},
                    315:                userload => {anywhere => 1},
                    316:                version => {anywhere => 1}, #not used
                    317:             );
                    318: 
                    319: #
1.207     foxr      320: #   Statistics that are maintained and dislayed in the status line.
                    321: #
1.212     foxr      322: my $Transactions = 0;		# Number of attempted transactions.
                    323: my $Failures     = 0;		# Number of transcations failed.
1.207     foxr      324: 
                    325: #   ResetStatistics: 
                    326: #      Resets the statistics counters:
                    327: #
                    328: sub ResetStatistics {
                    329:     $Transactions = 0;
                    330:     $Failures     = 0;
                    331: }
                    332: 
1.200     matthew   333: #------------------------------------------------------------------------
                    334: #
                    335: #   LocalConnection
                    336: #     Completes the formation of a locally authenticated connection.
                    337: #     This function will ensure that the 'remote' client is really the
                    338: #     local host.  If not, the connection is closed, and the function fails.
                    339: #     If so, initcmd is parsed for the name of a file containing the
                    340: #     IDEA session key.  The fie is opened, read, deleted and the session
                    341: #     key returned to the caller.
                    342: #
                    343: # Parameters:
                    344: #   $Socket      - Socket open on client.
                    345: #   $initcmd     - The full text of the init command.
                    346: #
                    347: # Returns:
                    348: #     IDEA session key on success.
                    349: #     undef on failure.
                    350: #
                    351: sub LocalConnection {
                    352:     my ($Socket, $initcmd) = @_;
1.373     albertel  353:     Debug("Attempting local connection: $initcmd client: $clientip");
1.277     albertel  354:     if($clientip ne "127.0.0.1") {
1.200     matthew   355: 	&logthis('<font color="red"> LocalConnection rejecting non local: '
1.373     albertel  356: 		 ."$clientip ne 127.0.0.1 </font>");
1.200     matthew   357: 	close $Socket;
                    358: 	return undef;
1.224     foxr      359:     }  else {
1.200     matthew   360: 	chomp($initcmd);	# Get rid of \n in filename.
                    361: 	my ($init, $type, $name) = split(/:/, $initcmd);
                    362: 	Debug(" Init command: $init $type $name ");
                    363: 
                    364: 	# Require that $init = init, and $type = local:  Otherwise
                    365: 	# the caller is insane:
                    366: 
                    367: 	if(($init ne "init") && ($type ne "local")) {
                    368: 	    &logthis('<font color = "red"> LocalConnection: caller is insane! '
                    369: 		     ."init = $init, and type = $type </font>");
                    370: 	    close($Socket);;
                    371: 	    return undef;
                    372: 		
                    373: 	}
                    374: 	#  Now get the key filename:
                    375: 
                    376: 	my $IDEAKey = lonlocal::ReadKeyFile($name);
                    377: 	return $IDEAKey;
                    378:     }
                    379: }
                    380: #------------------------------------------------------------------------------
                    381: #
                    382: #  SSLConnection
                    383: #   Completes the formation of an ssh authenticated connection. The
                    384: #   socket is promoted to an ssl socket.  If this promotion and the associated
                    385: #   certificate exchange are successful, the IDEA key is generated and sent
                    386: #   to the remote peer via the SSL tunnel. The IDEA key is also returned to
                    387: #   the caller after the SSL tunnel is torn down.
                    388: #
                    389: # Parameters:
                    390: #   Name              Type             Purpose
                    391: #   $Socket          IO::Socket::INET  Plaintext socket.
                    392: #
                    393: # Returns:
                    394: #    IDEA key on success.
                    395: #    undef on failure.
                    396: #
                    397: sub SSLConnection {
                    398:     my $Socket   = shift;
                    399: 
                    400:     Debug("SSLConnection: ");
                    401:     my $KeyFile         = lonssl::KeyFile();
                    402:     if(!$KeyFile) {
                    403: 	my $err = lonssl::LastError();
                    404: 	&logthis("<font color=\"red\"> CRITICAL"
                    405: 		 ."Can't get key file $err </font>");
                    406: 	return undef;
                    407:     }
                    408:     my ($CACertificate,
                    409: 	$Certificate) = lonssl::CertificateFile();
                    410: 
                    411: 
                    412:     # If any of the key, certificate or certificate authority 
                    413:     # certificate filenames are not defined, this can't work.
                    414: 
                    415:     if((!$Certificate) || (!$CACertificate)) {
                    416: 	my $err = lonssl::LastError();
                    417: 	&logthis("<font color=\"red\"> CRITICAL"
                    418: 		 ."Can't get certificates: $err </font>");
                    419: 
                    420: 	return undef;
                    421:     }
                    422:     Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
                    423: 
                    424:     # Indicate to our peer that we can procede with
                    425:     # a transition to ssl authentication:
                    426: 
                    427:     print $Socket "ok:ssl\n";
                    428: 
                    429:     Debug("Approving promotion -> ssl");
                    430:     #  And do so:
                    431: 
1.545     raeburn   432:     my $CRLFile;
                    433:     unless ($crlchecked{$clientname}) {
                    434:         $CRLFile = lonssl::CRLFile();
                    435:         $crlchecked{$clientname} = 1;
                    436:     }
                    437: 
1.200     matthew   438:     my $SSLSocket = lonssl::PromoteServerSocket($Socket,
                    439: 						$CACertificate,
                    440: 						$Certificate,
1.544     raeburn   441: 						$KeyFile,
1.545     raeburn   442: 						$clientname,
1.546     raeburn   443:                                                 $CRLFile,
                    444:                                                 $clientversion);
1.200     matthew   445:     if(! ($SSLSocket) ) {	# SSL socket promotion failed.
                    446: 	my $err = lonssl::LastError();
                    447: 	&logthis("<font color=\"red\"> CRITICAL "
                    448: 		 ."SSL Socket promotion failed: $err </font>");
                    449: 	return undef;
                    450:     }
                    451:     Debug("SSL Promotion successful");
                    452: 
                    453:     # 
                    454:     #  The only thing we'll use the socket for is to send the IDEA key
                    455:     #  to the peer:
                    456: 
                    457:     my $Key = lonlocal::CreateCipherKey();
                    458:     print $SSLSocket "$Key\n";
                    459: 
                    460:     lonssl::Close($SSLSocket); 
                    461: 
                    462:     Debug("Key exchange complete: $Key");
                    463: 
                    464:     return $Key;
                    465: }
                    466: #
                    467: #     InsecureConnection: 
                    468: #        If insecure connections are allowd,
                    469: #        exchange a challenge with the client to 'validate' the
                    470: #        client (not really, but that's the protocol):
                    471: #        We produce a challenge string that's sent to the client.
                    472: #        The client must then echo the challenge verbatim to us.
                    473: #
                    474: #  Parameter:
                    475: #      Socket      - Socket open on the client.
                    476: #  Returns:
                    477: #      1           - success.
                    478: #      0           - failure (e.g.mismatch or insecure not allowed).
                    479: #
                    480: sub InsecureConnection {
                    481:     my $Socket  =  shift;
                    482: 
                    483:     #   Don't even start if insecure connections are not allowed.
1.532     raeburn   484:     #   return 0 if Insecure connections not allowed.
                    485:     #
                    486:     if (ref($secureconf{'connfrom'}) eq 'HASH') {
                    487:         if ($clientsamedom) {
                    488:             if ($secureconf{'connfrom'}{'dom'} eq 'req') {
                    489:                 return 0;
                    490:             } 
                    491:         } elsif ($clientsameinst) {
                    492:             if ($secureconf{'connfrom'}{'intdom'} eq 'req') {
                    493:                 return 0;
                    494:             }
                    495:         } else {
                    496:             if ($secureconf{'connfrom'}{'other'} eq 'req') {
                    497:                 return 0;
                    498:             }
                    499:         }
                    500:     } elsif (!$perlvar{londAllowInsecure}) {
1.200     matthew   501: 	return 0;
                    502:     }
                    503: 
                    504:     #   Fabricate a challenge string and send it..
                    505: 
                    506:     my $challenge = "$$".time;	# pid + time.
                    507:     print $Socket "$challenge\n";
                    508:     &status("Waiting for challenge reply");
                    509: 
                    510:     my $answer = <$Socket>;
                    511:     $answer    =~s/\W//g;
                    512:     if($challenge eq $answer) {
                    513: 	return 1;
1.224     foxr      514:     } else {
1.200     matthew   515: 	logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
                    516: 	&status("No challenge reqply");
                    517: 	return 0;
                    518:     }
                    519:     
                    520: 
                    521: }
1.251     foxr      522: #
                    523: #   Safely execute a command (as long as it's not a shel command and doesn
                    524: #   not require/rely on shell escapes.   The function operates by doing a
                    525: #   a pipe based fork and capturing stdout and stderr  from the pipe.
                    526: #
                    527: # Formal Parameters:
                    528: #     $line                    - A line of text to be executed as a command.
                    529: # Returns:
                    530: #     The output from that command.  If the output is multiline the caller
                    531: #     must know how to split up the output.
                    532: #
                    533: #
                    534: sub execute_command {
                    535:     my ($line)    = @_;
                    536:     my @words     = split(/\s/, $line);	# Bust the command up into words.
                    537:     my $output    = "";
                    538: 
                    539:     my $pid = open(CHILD, "-|");
                    540:     
                    541:     if($pid) {			# Parent process
                    542: 	Debug("In parent process for execute_command");
                    543: 	my @data = <CHILD>;	# Read the child's outupt...
                    544: 	close CHILD;
                    545: 	foreach my $output_line (@data) {
                    546: 	    Debug("Adding $output_line");
                    547: 	    $output .= $output_line; # Presumably has a \n on it.
                    548: 	}
                    549: 
                    550:     } else {			# Child process
                    551: 	close (STDERR);
                    552: 	open  (STDERR, ">&STDOUT");# Combine stderr, and stdout...
                    553: 	exec(@words);		# won't return.
                    554:     }
                    555:     return $output;
                    556: }
                    557: 
1.200     matthew   558: 
1.140     foxr      559: #   GetCertificate: Given a transaction that requires a certificate,
                    560: #   this function will extract the certificate from the transaction
                    561: #   request.  Note that at this point, the only concept of a certificate
                    562: #   is the hostname to which we are connected.
                    563: #
                    564: #   Parameter:
                    565: #      request   - The request sent by our client (this parameterization may
                    566: #                  need to change when we really use a certificate granting
                    567: #                  authority.
                    568: #
                    569: sub GetCertificate {
                    570:     my $request = shift;
                    571: 
                    572:     return $clientip;
                    573: }
1.161     foxr      574: 
1.178     foxr      575: #
                    576: #   Return true if client is a manager.
                    577: #
                    578: sub isManager {
                    579:     return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
                    580: }
                    581: #
                    582: #   Return tru if client can do client functions
                    583: #
                    584: sub isClient {
                    585:     return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
                    586: }
1.161     foxr      587: 
                    588: 
1.156     foxr      589: #
                    590: #   ReadManagerTable: Reads in the current manager table. For now this is
                    591: #                     done on each manager authentication because:
                    592: #                     - These authentications are not frequent
                    593: #                     - This allows dynamic changes to the manager table
                    594: #                       without the need to signal to the lond.
                    595: #
                    596: sub ReadManagerTable {
                    597: 
1.412     foxr      598:     &Debug("Reading manager table");
1.156     foxr      599:     #   Clean out the old table first..
                    600: 
1.166     foxr      601:    foreach my $key (keys %managers) {
                    602:       delete $managers{$key};
                    603:    }
                    604: 
                    605:    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
                    606:    if (!open (MANAGERS, $tablename)) {
1.473     raeburn   607:        my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
                    608:        if (&Apache::lonnet::is_LC_dns($hostname)) {
1.472     raeburn   609:            &logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
                    610:        }
                    611:        return;
1.166     foxr      612:    }
                    613:    while(my $host = <MANAGERS>) {
                    614:       chomp($host);
                    615:       if ($host =~ "^#") {                  # Comment line.
                    616:          next;
                    617:       }
1.368     albertel  618:       if (!defined &Apache::lonnet::get_host_ip($host)) { # This is a non cluster member
1.161     foxr      619: 	    #  The entry is of the form:
                    620: 	    #    cluname:hostname
                    621: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
                    622: 	    #            the host key.
                    623: 	    #  hostname- The dns name of the host.
                    624: 	    #
1.166     foxr      625:           my($cluname, $dnsname) = split(/:/, $host);
                    626:           
                    627:           my $ip = gethostbyname($dnsname);
                    628:           if(defined($ip)) {                 # bad names don't deserve entry.
                    629:             my $hostip = inet_ntoa($ip);
                    630:             $managers{$hostip} = $cluname;
                    631:             logthis('<font color="green"> registering manager '.
                    632:                     "$dnsname as $cluname with $hostip </font>\n");
                    633:          }
                    634:       } else {
                    635:          logthis('<font color="green"> existing host'." $host</font>\n");
1.472     raeburn   636:          $managers{&Apache::lonnet::get_host_ip($host)} = $host;  # Use info from cluster tab if cluster memeber
1.166     foxr      637:       }
                    638:    }
1.156     foxr      639: }
1.140     foxr      640: 
                    641: #
                    642: #  ValidManager: Determines if a given certificate represents a valid manager.
                    643: #                in this primitive implementation, the 'certificate' is
                    644: #                just the connecting loncapa client name.  This is checked
                    645: #                against a valid client list in the configuration.
                    646: #
                    647: #                  
                    648: sub ValidManager {
                    649:     my $certificate = shift; 
                    650: 
1.163     foxr      651:     return isManager;
1.140     foxr      652: }
                    653: #
1.143     foxr      654: #  CopyFile:  Called as part of the process of installing a 
                    655: #             new configuration file.  This function copies an existing
                    656: #             file to a backup file.
                    657: # Parameters:
                    658: #     oldfile  - Name of the file to backup.
                    659: #     newfile  - Name of the backup file.
                    660: # Return:
                    661: #     0   - Failure (errno has failure reason).
                    662: #     1   - Success.
                    663: #
                    664: sub CopyFile {
1.192     foxr      665: 
                    666:     my ($oldfile, $newfile) = @_;
1.143     foxr      667: 
1.281     matthew   668:     if (! copy($oldfile,$newfile)) {
                    669:         return 0;
1.143     foxr      670:     }
1.281     matthew   671:     chmod(0660, $newfile);
                    672:     return 1;
1.143     foxr      673: }
1.157     foxr      674: #
                    675: #  Host files are passed out with externally visible host IPs.
                    676: #  If, for example, we are behind a fire-wall or NAT host, our 
                    677: #  internally visible IP may be different than the externally
                    678: #  visible IP.  Therefore, we always adjust the contents of the
                    679: #  host file so that the entry for ME is the IP that we believe
                    680: #  we have.  At present, this is defined as the entry that
                    681: #  DNS has for us.  If by some chance we are not able to get a
                    682: #  DNS translation for us, then we assume that the host.tab file
                    683: #  is correct.  
                    684: #    BUGBUGBUG - in the future, we really should see if we can
                    685: #       easily query the interface(s) instead.
                    686: # Parameter(s):
                    687: #     contents    - The contents of the host.tab to check.
                    688: # Returns:
                    689: #     newcontents - The adjusted contents.
                    690: #
                    691: #
                    692: sub AdjustHostContents {
                    693:     my $contents  = shift;
                    694:     my $adjusted;
                    695:     my $me        = $perlvar{'lonHostID'};
                    696: 
1.354     albertel  697:     foreach my $line (split(/\n/,$contents)) {
1.472     raeburn   698: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/) ||
                    699:              ($line =~ /^\s*\^/))) {
1.157     foxr      700: 	    chomp($line);
                    701: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
                    702: 	    if ($id eq $me) {
1.354     albertel  703: 		my $ip = gethostbyname($name);
                    704: 		my $ipnew = inet_ntoa($ip);
                    705: 		$ip = $ipnew;
1.157     foxr      706: 		#  Reconstruct the host line and append to adjusted:
                    707: 		
1.354     albertel  708: 		my $newline = "$id:$domain:$role:$name:$ip";
                    709: 		if($maxcon ne "") { # Not all hosts have loncnew tuning params
                    710: 		    $newline .= ":$maxcon:$idleto:$mincon";
                    711: 		}
                    712: 		$adjusted .= $newline."\n";
1.157     foxr      713: 		
1.354     albertel  714: 	    } else {		# Not me, pass unmodified.
                    715: 		$adjusted .= $line."\n";
                    716: 	    }
1.157     foxr      717: 	} else {                  # Blank or comment never re-written.
                    718: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
                    719: 	}
1.354     albertel  720:     }
                    721:     return $adjusted;
1.157     foxr      722: }
1.143     foxr      723: #
                    724: #   InstallFile: Called to install an administrative file:
1.412     foxr      725: #       - The file is created int a temp directory called <name>.tmp
                    726: #       - lcinstall file is called to install the file.
                    727: #         since the web app has no direct write access to the table directory
1.143     foxr      728: #
                    729: #  Parameters:
                    730: #       Name of the file
                    731: #       File Contents.
                    732: #  Return:
                    733: #      nonzero - success.
                    734: #      0       - failure and $! has an errno.
1.412     foxr      735: # Assumptions:
                    736: #    File installtion is a relatively infrequent
1.143     foxr      737: #
                    738: sub InstallFile {
1.192     foxr      739: 
                    740:     my ($Filename, $Contents) = @_;
1.412     foxr      741: #     my $TempFile = $Filename.".tmp";
                    742:     my $exedir = $perlvar{'lonDaemons'};
                    743:     my $tmpdir = $exedir.'/tmp/';
                    744:     my $TempFile = $tmpdir."TempTableFile.tmp";
1.143     foxr      745: 
                    746:     #  Open the file for write:
                    747: 
                    748:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
                    749:     if(!(defined $fh)) {
                    750: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
                    751: 	return 0;
                    752:     }
                    753:     #  write the contents of the file:
                    754: 
                    755:     print $fh ($Contents); 
                    756:     $fh->close;			# In case we ever have a filesystem w. locking
                    757: 
1.412     foxr      758:     chmod(0664, $TempFile);	# Everyone can write it.
                    759: 
                    760:     # Use lcinstall file to put the file in the table directory...
                    761: 
                    762:     &Debug("Opening pipe to $exedir/lcinstallfile $TempFile $Filename");
                    763:     my $pf = IO::File->new("| $exedir/lcinstallfile   $TempFile $Filename > $exedir/logs/lcinstallfile.log");
                    764:     close $pf;
                    765:     my $err = $?;
                    766:     &Debug("Status is $err");
                    767:     if ($err != 0) {
                    768: 	my $msg = $err;
                    769: 	if ($err < @installerrors) {
                    770: 	    $msg = $installerrors[$err];
                    771: 	}
                    772: 	&logthis("Install failed for table file $Filename : $msg");
                    773: 	return 0;
                    774:     }
                    775: 
                    776:     # Remove the temp file:
1.143     foxr      777: 
1.412     foxr      778:     unlink($TempFile);
1.143     foxr      779: 
                    780:     return 1;
                    781: }
1.200     matthew   782: 
                    783: 
1.169     foxr      784: #
                    785: #   ConfigFileFromSelector: converts a configuration file selector
1.411     foxr      786: #                 into a configuration file pathname.
1.472     raeburn   787: #                 Supports the following file selectors: 
                    788: #                 hosts, domain, dns_hosts, dns_domain  
1.411     foxr      789: #
1.169     foxr      790: #
                    791: #  Parameters:
                    792: #      selector  - Configuration file selector.
                    793: #  Returns:
                    794: #      Full path to the file or undef if the selector is invalid.
                    795: #
                    796: sub ConfigFileFromSelector {
                    797:     my $selector   = shift;
                    798:     my $tablefile;
                    799: 
1.549     raeburn   800:     if ($selector eq 'loncapaCAcrl') {
                    801:         my $tabledir = $perlvar{'lonCertificateDirectory'};
                    802:         if (-d $tabledir) {
                    803:             $tablefile =  $tabledir.'/'.$selector.'.pem';
                    804:         }
                    805:     } else {
                    806:         my $tabledir = $perlvar{'lonTabDir'}.'/';
                    807:         if (($selector eq "hosts") || ($selector eq "domain") || 
                    808:             ($selector eq "dns_hosts") || ($selector eq "dns_domain")) {
                    809: 	    $tablefile =  $tabledir.$selector.'.tab';
                    810:         }
1.169     foxr      811:     }
                    812:     return $tablefile;
                    813: }
1.143     foxr      814: #
1.141     foxr      815: #   PushFile:  Called to do an administrative push of a file.
                    816: #              - Ensure the file being pushed is one we support.
                    817: #              - Backup the old file to <filename.saved>
                    818: #              - Separate the contents of the new file out from the
                    819: #                rest of the request.
                    820: #              - Write the new file.
                    821: #  Parameter:
                    822: #     Request - The entire user request.  This consists of a : separated
                    823: #               string pushfile:tablename:contents.
                    824: #     NOTE:  The contents may have :'s in it as well making things a bit
                    825: #            more interesting... but not much.
                    826: #  Returns:
                    827: #     String to send to client ("ok" or "refused" if bad file).
                    828: #
                    829: sub PushFile {
1.510     raeburn   830:     my $request = shift;
1.141     foxr      831:     my ($command, $filename, $contents) = split(":", $request, 3);
1.412     foxr      832:     &Debug("PushFile");
1.141     foxr      833:     
1.549     raeburn   834:     #  At this point in time, pushes for only the following tables and
                    835:     #  CRL file are supported:
1.141     foxr      836:     #   hosts.tab  ($filename eq host).
                    837:     #   domain.tab ($filename eq domain).
1.472     raeburn   838:     #   dns_hosts.tab ($filename eq dns_host).
1.554     raeburn   839:     #   dns_domain.tab ($filename eq dns_domain).
                    840:     #   loncapaCAcrl.pem ($filename eq loncapaCAcrl).
1.141     foxr      841:     # Construct the destination filename or reject the request.
                    842:     #
                    843:     # lonManage is supposed to ensure this, however this session could be
                    844:     # part of some elaborate spoof that managed somehow to authenticate.
                    845:     #
                    846: 
1.169     foxr      847: 
                    848:     my $tablefile = ConfigFileFromSelector($filename);
                    849:     if(! (defined $tablefile)) {
1.141     foxr      850: 	return "refused";
                    851:     }
1.412     foxr      852: 
1.157     foxr      853:     #  If the file being pushed is the host file, we adjust the entry for ourself so that the
                    854:     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
                    855:     #  to conceive of conditions where we don't have a DNS entry locally.  This is possible in a 
                    856:     #  network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
                    857:     #  that possibilty.
                    858: 
                    859:     if($filename eq "host") {
                    860: 	$contents = AdjustHostContents($contents);
1.549     raeburn   861:     } elsif (($filename eq 'dns_host') || ($filename eq 'dns_domain') ||
                    862:              ($filename eq 'loncapaCAcrl')) {
1.510     raeburn   863:         if ($contents eq '') {
                    864:             &logthis('<font color="red"> Pushfile: unable to install '
                    865:                     .$tablefile." - no data received from push. </font>");
                    866:             return 'error: push had no data';
                    867:         }
                    868:         if (&Apache::lonnet::get_host_ip($clientname)) {
                    869:             my $clienthost = &Apache::lonnet::hostname($clientname);
                    870:             if ($managers{$clientip} eq $clientname) {
                    871:                 my $clientprotocol = $Apache::lonnet::protocol{$clientname};
                    872:                 $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.549     raeburn   873:                 my $url;
                    874:                 if ($filename eq 'loncapaCAcrl') {
                    875:                     $url = '/adm/dns/loncapaCRL';
                    876:                 } else {
                    877:                     $url = '/adm/'.$filename;
                    878:                     $url =~ s{_}{/};
                    879:                 }
1.510     raeburn   880:                 my $request=new HTTP::Request('GET',"$clientprotocol://$clienthost$url");
1.523     raeburn   881:                 my $response = LONCAPA::LWPReq::makerequest($clientname,$request,'',\%perlvar,60,0);
1.510     raeburn   882:                 if ($response->is_error()) {
                    883:                     &logthis('<font color="red"> Pushfile: unable to install '
                    884:                             .$tablefile." - error attempting to pull data. </font>");
                    885:                     return 'error: pull failed';
                    886:                 } else {
                    887:                     my $result = $response->content;
                    888:                     chomp($result);
                    889:                     unless ($result eq $contents) {
                    890:                         &logthis('<font color="red"> Pushfile: unable to install '
                    891:                                 .$tablefile." - pushed data and pulled data differ. </font>");
                    892:                         my $pushleng = length($contents);
                    893:                         my $pullleng = length($result);
                    894:                         if ($pushleng != $pullleng) {
                    895:                             return "error: $pushleng vs $pullleng bytes";
                    896:                         } else {
                    897:                             return "error: mismatch push and pull";
                    898:                         }
                    899:                     }
                    900:                 }
                    901:             }
                    902:         }
1.157     foxr      903:     }
                    904: 
1.141     foxr      905:     #  Install the new file:
                    906: 
1.412     foxr      907:     &logthis("Installing new $tablefile contents:\n$contents");
1.143     foxr      908:     if(!InstallFile($tablefile, $contents)) {
                    909: 	&logthis('<font color="red"> Pushfile: unable to install '
1.145     foxr      910: 	 .$tablefile." $! </font>");
1.143     foxr      911: 	return "error:$!";
1.224     foxr      912:     } else {
1.143     foxr      913: 	&logthis('<font color="green"> Installed new '.$tablefile
1.473     raeburn   914: 		 ." - transaction by: $clientname ($clientip)</font>");
1.472     raeburn   915:         my $adminmail = $perlvar{'lonAdmEMail'};
                    916:         my $admindom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                    917:         if ($admindom ne '') {
                    918:             my %domconfig =
                    919:                 &Apache::lonnet::get_dom('configuration',['contacts'],$admindom);
                    920:             if (ref($domconfig{'contacts'}) eq 'HASH') {
                    921:                 if ($domconfig{'contacts'}{'adminemail'} ne '') {
                    922:                     $adminmail = $domconfig{'contacts'}{'adminemail'};
                    923:                 }
                    924:             }
                    925:         }
                    926:         if ($adminmail =~ /^[^\@]+\@[^\@]+$/) {
                    927:             my $msg = new Mail::Send;
                    928:             $msg->to($adminmail);
                    929:             $msg->subject('LON-CAPA DNS update on '.$perlvar{'lonHostID'});
                    930:             $msg->add('Content-type','text/plain; charset=UTF-8');
                    931:             if (my $fh = $msg->open()) {
                    932:                 print $fh 'Update to '.$tablefile.' from Cluster Manager '.
1.473     raeburn   933:                           "$clientname ($clientip)\n";
1.472     raeburn   934:                 $fh->close;
                    935:             }
                    936:         }
1.143     foxr      937:     }
                    938: 
1.141     foxr      939:     #  Indicate success:
                    940:  
                    941:     return "ok";
                    942: 
                    943: }
1.145     foxr      944: 
                    945: #
                    946: #  Called to re-init either lonc or lond.
                    947: #
                    948: #  Parameters:
                    949: #    request   - The full request by the client.  This is of the form
                    950: #                reinit:<process>  
                    951: #                where <process> is allowed to be either of 
                    952: #                lonc or lond
                    953: #
                    954: #  Returns:
                    955: #     The string to be sent back to the client either:
                    956: #   ok         - Everything worked just fine.
                    957: #   error:why  - There was a failure and why describes the reason.
                    958: #
                    959: #
                    960: sub ReinitProcess {
                    961:     my $request = shift;
                    962: 
1.146     foxr      963: 
                    964:     # separate the request (reinit) from the process identifier and
                    965:     # validate it producing the name of the .pid file for the process.
                    966:     #
                    967:     #
                    968:     my ($junk, $process) = split(":", $request);
1.147     foxr      969:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
1.146     foxr      970:     if($process eq 'lonc') {
                    971: 	$processpidfile = $processpidfile."lonc.pid";
1.147     foxr      972: 	if (!open(PIDFILE, "< $processpidfile")) {
                    973: 	    return "error:Open failed for $processpidfile";
                    974: 	}
                    975: 	my $loncpid = <PIDFILE>;
                    976: 	close(PIDFILE);
                    977: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
                    978: 		."</font>");
                    979: 	kill("USR2", $loncpid);
1.146     foxr      980:     } elsif ($process eq 'lond') {
1.147     foxr      981: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
                    982: 	&UpdateHosts;			# Lond is us!!
1.146     foxr      983:     } else {
                    984: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
                    985: 		 ."</font>");
                    986: 	return "error:Invalid process identifier $process";
                    987:     }
1.145     foxr      988:     return 'ok';
                    989: }
1.168     foxr      990: #   Validate a line in a configuration file edit script:
                    991: #   Validation includes:
                    992: #     - Ensuring the command is valid.
                    993: #     - Ensuring the command has sufficient parameters
                    994: #   Parameters:
                    995: #     scriptline - A line to validate (\n has been stripped for what it's worth).
1.167     foxr      996: #
1.168     foxr      997: #   Return:
                    998: #      0     - Invalid scriptline.
                    999: #      1     - Valid scriptline
                   1000: #  NOTE:
                   1001: #     Only the command syntax is checked, not the executability of the
                   1002: #     command.
                   1003: #
                   1004: sub isValidEditCommand {
                   1005:     my $scriptline = shift;
                   1006: 
                   1007:     #   Line elements are pipe separated:
                   1008: 
                   1009:     my ($command, $key, $newline)  = split(/\|/, $scriptline);
                   1010:     &logthis('<font color="green"> isValideditCommand checking: '.
                   1011: 	     "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
                   1012:     
                   1013:     if ($command eq "delete") {
                   1014: 	#
                   1015: 	#   key with no newline.
                   1016: 	#
                   1017: 	if( ($key eq "") || ($newline ne "")) {
                   1018: 	    return 0;		# Must have key but no newline.
                   1019: 	} else {
                   1020: 	    return 1;		# Valid syntax.
                   1021: 	}
1.169     foxr     1022:     } elsif ($command eq "replace") {
1.168     foxr     1023: 	#
                   1024: 	#   key and newline:
                   1025: 	#
                   1026: 	if (($key eq "") || ($newline eq "")) {
                   1027: 	    return 0;
                   1028: 	} else {
                   1029: 	    return 1;
                   1030: 	}
1.169     foxr     1031:     } elsif ($command eq "append") {
                   1032: 	if (($key ne "") && ($newline eq "")) {
                   1033: 	    return 1;
                   1034: 	} else {
                   1035: 	    return 0;
                   1036: 	}
1.168     foxr     1037:     } else {
                   1038: 	return 0;		# Invalid command.
                   1039:     }
                   1040:     return 0;			# Should not get here!!!
                   1041: }
1.169     foxr     1042: #
                   1043: #   ApplyEdit - Applies an edit command to a line in a configuration 
                   1044: #               file.  It is the caller's responsiblity to validate the
                   1045: #               edit line.
                   1046: #   Parameters:
                   1047: #      $directive - A single edit directive to apply.  
                   1048: #                   Edit directives are of the form:
                   1049: #                  append|newline      - Appends a new line to the file.
                   1050: #                  replace|key|newline - Replaces the line with key value 'key'
                   1051: #                  delete|key          - Deletes the line with key value 'key'.
                   1052: #      $editor   - A config file editor object that contains the
                   1053: #                  file being edited.
                   1054: #
                   1055: sub ApplyEdit {
1.192     foxr     1056: 
                   1057:     my ($directive, $editor) = @_;
1.169     foxr     1058: 
                   1059:     # Break the directive down into its command and its parameters
                   1060:     # (at most two at this point.  The meaning of the parameters, if in fact
                   1061:     #  they exist depends on the command).
                   1062: 
                   1063:     my ($command, $p1, $p2) = split(/\|/, $directive);
                   1064: 
                   1065:     if($command eq "append") {
                   1066: 	$editor->Append($p1);	          # p1 - key p2 null.
                   1067:     } elsif ($command eq "replace") {
                   1068: 	$editor->ReplaceLine($p1, $p2);   # p1 - key p2 = newline.
                   1069:     } elsif ($command eq "delete") {
                   1070: 	$editor->DeleteLine($p1);         # p1 - key p2 null.
                   1071:     } else {			          # Should not get here!!!
                   1072: 	die "Invalid command given to ApplyEdit $command"
                   1073:     }
                   1074: }
                   1075: #
                   1076: # AdjustOurHost:
                   1077: #           Adjusts a host file stored in a configuration file editor object
                   1078: #           for the true IP address of this host. This is necessary for hosts
                   1079: #           that live behind a firewall.
                   1080: #           Those hosts have a publicly distributed IP of the firewall, but
                   1081: #           internally must use their actual IP.  We assume that a given
                   1082: #           host only has a single IP interface for now.
                   1083: # Formal Parameters:
                   1084: #     editor   - The configuration file editor to adjust.  This
                   1085: #                editor is assumed to contain a hosts.tab file.
                   1086: # Strategy:
                   1087: #    - Figure out our hostname.
                   1088: #    - Lookup the entry for this host.
                   1089: #    - Modify the line to contain our IP
                   1090: #    - Do a replace for this host.
                   1091: sub AdjustOurHost {
                   1092:     my $editor        = shift;
                   1093: 
                   1094:     # figure out who I am.
                   1095: 
                   1096:     my $myHostName    = $perlvar{'lonHostID'}; # LonCAPA hostname.
                   1097: 
                   1098:     #  Get my host file entry.
                   1099: 
                   1100:     my $ConfigLine    = $editor->Find($myHostName);
                   1101:     if(! (defined $ConfigLine)) {
                   1102: 	die "AdjustOurHost - no entry for me in hosts file $myHostName";
                   1103:     }
                   1104:     # figure out my IP:
                   1105:     #   Use the config line to get my hostname.
                   1106:     #   Use gethostbyname to translate that into an IP address.
                   1107:     #
1.338     albertel 1108:     my ($id,$domain,$role,$name,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
1.169     foxr     1109:     #
                   1110:     #  Reassemble the config line from the elements in the list.
                   1111:     #  Note that if the loncnew items were not present before, they will
                   1112:     #  be now even if they would be empty
                   1113:     #
                   1114:     my $newConfigLine = $id;
1.338     albertel 1115:     foreach my $item ($domain, $role, $name, $maxcon, $idleto, $mincon) {
1.169     foxr     1116: 	$newConfigLine .= ":".$item;
                   1117:     }
                   1118:     #  Replace the line:
                   1119: 
                   1120:     $editor->ReplaceLine($id, $newConfigLine);
                   1121:     
                   1122: }
                   1123: #
                   1124: #   ReplaceConfigFile:
                   1125: #              Replaces a configuration file with the contents of a
                   1126: #              configuration file editor object.
                   1127: #              This is done by:
                   1128: #              - Copying the target file to <filename>.old
                   1129: #              - Writing the new file to <filename>.tmp
                   1130: #              - Moving <filename.tmp>  -> <filename>
                   1131: #              This laborious process ensures that the system is never without
                   1132: #              a configuration file that's at least valid (even if the contents
                   1133: #              may be dated).
                   1134: #   Parameters:
                   1135: #        filename   - Name of the file to modify... this is a full path.
                   1136: #        editor     - Editor containing the file.
                   1137: #
                   1138: sub ReplaceConfigFile {
1.192     foxr     1139:     
                   1140:     my ($filename, $editor) = @_;
1.168     foxr     1141: 
1.169     foxr     1142:     CopyFile ($filename, $filename.".old");
                   1143: 
                   1144:     my $contents  = $editor->Get(); # Get the contents of the file.
                   1145: 
                   1146:     InstallFile($filename, $contents);
                   1147: }
1.168     foxr     1148: #   
                   1149: #
                   1150: #   Called to edit a configuration table  file
1.167     foxr     1151: #   Parameters:
                   1152: #      request           - The entire command/request sent by lonc or lonManage
                   1153: #   Return:
                   1154: #      The reply to send to the client.
1.168     foxr     1155: #
1.167     foxr     1156: sub EditFile {
                   1157:     my $request = shift;
                   1158: 
                   1159:     #  Split the command into it's pieces:  edit:filetype:script
                   1160: 
1.339     albertel 1161:     my ($cmd, $filetype, $script) = split(/:/, $request,3);	# : in script
1.167     foxr     1162: 
                   1163:     #  Check the pre-coditions for success:
                   1164: 
1.339     albertel 1165:     if($cmd != "edit") {	# Something is amiss afoot alack.
1.167     foxr     1166: 	return "error:edit request detected, but request != 'edit'\n";
                   1167:     }
                   1168:     if( ($filetype ne "hosts")  &&
                   1169: 	($filetype ne "domain")) {
                   1170: 	return "error:edit requested with invalid file specifier: $filetype \n";
                   1171:     }
                   1172: 
                   1173:     #   Split the edit script and check it's validity.
1.168     foxr     1174: 
                   1175:     my @scriptlines = split(/\n/, $script);  # one line per element.
                   1176:     my $linecount   = scalar(@scriptlines);
                   1177:     for(my $i = 0; $i < $linecount; $i++) {
                   1178: 	chomp($scriptlines[$i]);
                   1179: 	if(!isValidEditCommand($scriptlines[$i])) {
                   1180: 	    return "error:edit with bad script line: '$scriptlines[$i]' \n";
                   1181: 	}
                   1182:     }
1.145     foxr     1183: 
1.167     foxr     1184:     #   Execute the edit operation.
1.169     foxr     1185:     #   - Create a config file editor for the appropriate file and 
                   1186:     #   - execute each command in the script:
                   1187:     #
                   1188:     my $configfile = ConfigFileFromSelector($filetype);
                   1189:     if (!(defined $configfile)) {
                   1190: 	return "refused\n";
                   1191:     }
                   1192:     my $editor = ConfigFileEdit->new($configfile);
1.167     foxr     1193: 
1.169     foxr     1194:     for (my $i = 0; $i < $linecount; $i++) {
                   1195: 	ApplyEdit($scriptlines[$i], $editor);
                   1196:     }
                   1197:     # If the file is the host file, ensure that our host is
                   1198:     # adjusted to have our ip:
                   1199:     #
                   1200:     if($filetype eq "host") {
                   1201: 	AdjustOurHost($editor);
                   1202:     }
                   1203:     #  Finally replace the current file with our file.
                   1204:     #
                   1205:     ReplaceConfigFile($configfile, $editor);
1.167     foxr     1206: 
                   1207:     return "ok\n";
                   1208: }
1.207     foxr     1209: 
1.255     foxr     1210: #   read_profile
                   1211: #
                   1212: #   Returns a set of specific entries from a user's profile file.
                   1213: #   this is a utility function that is used by both get_profile_entry and
                   1214: #   get_profile_entry_encrypted.
                   1215: #
                   1216: # Parameters:
                   1217: #    udom       - Domain in which the user exists.
                   1218: #    uname      - User's account name (loncapa account)
                   1219: #    namespace  - The profile namespace to open.
                   1220: #    what       - A set of & separated queries.
                   1221: # Returns:
                   1222: #    If all ok: - The string that needs to be shipped back to the user.
                   1223: #    If failure - A string that starts with error: followed by the failure
                   1224: #                 reason.. note that this probabyl gets shipped back to the
                   1225: #                 user as well.
                   1226: #
                   1227: sub read_profile {
                   1228:     my ($udom, $uname, $namespace, $what) = @_;
                   1229:     
                   1230:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   1231: 				 &GDBM_READER());
                   1232:     if ($hashref) {
                   1233:         my @queries=split(/\&/,$what);
1.440     raeburn  1234:         if ($namespace eq 'roles') {
                   1235:             @queries = map { &unescape($_); } @queries; 
                   1236:         }
1.255     foxr     1237:         my $qresult='';
                   1238: 	
                   1239: 	for (my $i=0;$i<=$#queries;$i++) {
                   1240: 	    $qresult.="$hashref->{$queries[$i]}&";    # Presumably failure gives empty string.
                   1241: 	}
                   1242: 	$qresult=~s/\&$//;              # Remove trailing & from last lookup.
1.311     albertel 1243: 	if (&untie_user_hash($hashref)) {
1.255     foxr     1244: 	    return $qresult;
                   1245: 	} else {
                   1246: 	    return "error: ".($!+0)." untie (GDBM) Failed";
                   1247: 	}
                   1248:     } else {
                   1249: 	if ($!+0 == 2) {
                   1250: 	    return "error:No such file or GDBM reported bad block error";
                   1251: 	} else {
                   1252: 	    return "error: ".($!+0)." tie (GDBM) Failed";
                   1253: 	}
                   1254:     }
                   1255: 
                   1256: }
1.214     foxr     1257: #--------------------- Request Handlers --------------------------------------------
                   1258: #
1.215     foxr     1259: #   By convention each request handler registers itself prior to the sub 
                   1260: #   declaration:
1.214     foxr     1261: #
                   1262: 
1.216     foxr     1263: #++
                   1264: #
1.214     foxr     1265: #  Handles ping requests.
                   1266: #  Parameters:
                   1267: #      $cmd    - the actual keyword that invoked us.
                   1268: #      $tail   - the tail of the request that invoked us.
                   1269: #      $replyfd- File descriptor connected to the client
                   1270: #  Implicit Inputs:
                   1271: #      $currenthostid - Global variable that carries the name of the host we are
                   1272: #                       known as.
                   1273: #  Returns:
                   1274: #      1       - Ok to continue processing.
                   1275: #      0       - Program should exit.
                   1276: #  Side effects:
                   1277: #      Reply information is sent to the client.
                   1278: sub ping_handler {
                   1279:     my ($cmd, $tail, $client) = @_;
                   1280:     Debug("$cmd $tail $client .. $currenthostid:");
                   1281:    
1.387     albertel 1282:     Reply( $client,\$currenthostid,"$cmd:$tail");
1.214     foxr     1283:    
                   1284:     return 1;
                   1285: }
                   1286: &register_handler("ping", \&ping_handler, 0, 1, 1);       # Ping unencoded, client or manager.
                   1287: 
1.216     foxr     1288: #++
1.215     foxr     1289: #
                   1290: # Handles pong requests.  Pong replies with our current host id, and
                   1291: #                         the results of a ping sent to us via our lonc.
                   1292: #
                   1293: # Parameters:
                   1294: #      $cmd    - the actual keyword that invoked us.
                   1295: #      $tail   - the tail of the request that invoked us.
                   1296: #      $replyfd- File descriptor connected to the client
                   1297: #  Implicit Inputs:
                   1298: #      $currenthostid - Global variable that carries the name of the host we are
                   1299: #                       connected to.
                   1300: #  Returns:
                   1301: #      1       - Ok to continue processing.
                   1302: #      0       - Program should exit.
                   1303: #  Side effects:
                   1304: #      Reply information is sent to the client.
                   1305: sub pong_handler {
                   1306:     my ($cmd, $tail, $replyfd) = @_;
                   1307: 
1.365     albertel 1308:     my $reply=&Apache::lonnet::reply("ping",$clientname);
1.215     foxr     1309:     &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail"); 
                   1310:     return 1;
                   1311: }
                   1312: &register_handler("pong", \&pong_handler, 0, 1, 1);       # Pong unencoded, client or manager
                   1313: 
1.216     foxr     1314: #++
                   1315: #      Called to establish an encrypted session key with the remote client.
                   1316: #      Note that with secure lond, in most cases this function is never
                   1317: #      invoked.  Instead, the secure session key is established either
                   1318: #      via a local file that's locked down tight and only lives for a short
                   1319: #      time, or via an ssl tunnel...and is generated from a bunch-o-random
                   1320: #      bits from /dev/urandom, rather than the predictable pattern used by
                   1321: #      by this sub.  This sub is only used in the old-style insecure
                   1322: #      key negotiation.
                   1323: # Parameters:
                   1324: #      $cmd    - the actual keyword that invoked us.
                   1325: #      $tail   - the tail of the request that invoked us.
                   1326: #      $replyfd- File descriptor connected to the client
                   1327: #  Implicit Inputs:
                   1328: #      $currenthostid - Global variable that carries the name of the host
                   1329: #                       known as.
1.448     raeburn  1330: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.216     foxr     1331: #  Returns:
                   1332: #      1       - Ok to continue processing.
                   1333: #      0       - Program should exit.
                   1334: #  Implicit Outputs:
                   1335: #      Reply information is sent to the client.
                   1336: #      $cipher is set with a reference to a new IDEA encryption object.
                   1337: #
                   1338: sub establish_key_handler {
                   1339:     my ($cmd, $tail, $replyfd) = @_;
                   1340: 
                   1341:     my $buildkey=time.$$.int(rand 100000);
                   1342:     $buildkey=~tr/1-6/A-F/;
                   1343:     $buildkey=int(rand 100000).$buildkey.int(rand 100000);
                   1344:     my $key=$currenthostid.$clientname;
                   1345:     $key=~tr/a-z/A-Z/;
                   1346:     $key=~tr/G-P/0-9/;
                   1347:     $key=~tr/Q-Z/0-9/;
                   1348:     $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
                   1349:     $key=substr($key,0,32);
                   1350:     my $cipherkey=pack("H32",$key);
                   1351:     $cipher=new IDEA $cipherkey;
1.387     albertel 1352:     &Reply($replyfd, \$buildkey, "$cmd:$tail"); 
1.216     foxr     1353:    
                   1354:     return 1;
                   1355: 
                   1356: }
                   1357: &register_handler("ekey", \&establish_key_handler, 0, 1,1);
                   1358: 
1.217     foxr     1359: #     Handler for the load command.  Returns the current system load average
                   1360: #     to the requestor.
                   1361: #
                   1362: # Parameters:
                   1363: #      $cmd    - the actual keyword that invoked us.
                   1364: #      $tail   - the tail of the request that invoked us.
                   1365: #      $replyfd- File descriptor connected to the client
                   1366: #  Implicit Inputs:
                   1367: #      $currenthostid - Global variable that carries the name of the host
                   1368: #                       known as.
1.448     raeburn  1369: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1370: #  Returns:
                   1371: #      1       - Ok to continue processing.
                   1372: #      0       - Program should exit.
                   1373: #  Side effects:
                   1374: #      Reply information is sent to the client.
                   1375: sub load_handler {
                   1376:     my ($cmd, $tail, $replyfd) = @_;
                   1377: 
1.463     foxr     1378: 
                   1379: 
1.217     foxr     1380:    # Get the load average from /proc/loadavg and calculate it as a percentage of
                   1381:    # the allowed load limit as set by the perl global variable lonLoadLim
                   1382: 
                   1383:     my $loadavg;
                   1384:     my $loadfile=IO::File->new('/proc/loadavg');
                   1385:    
                   1386:     $loadavg=<$loadfile>;
                   1387:     $loadavg =~ s/\s.*//g;                      # Extract the first field only.
                   1388:    
                   1389:     my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
                   1390: 
1.387     albertel 1391:     &Reply( $replyfd, \$loadpercent, "$cmd:$tail");
1.217     foxr     1392:    
                   1393:     return 1;
                   1394: }
1.263     albertel 1395: &register_handler("load", \&load_handler, 0, 1, 0);
1.217     foxr     1396: 
                   1397: #
                   1398: #   Process the userload request.  This sub returns to the client the current
                   1399: #  user load average.  It can be invoked either by clients or managers.
                   1400: #
                   1401: # Parameters:
                   1402: #      $cmd    - the actual keyword that invoked us.
                   1403: #      $tail   - the tail of the request that invoked us.
                   1404: #      $replyfd- File descriptor connected to the client
                   1405: #  Implicit Inputs:
                   1406: #      $currenthostid - Global variable that carries the name of the host
                   1407: #                       known as.
1.448     raeburn  1408: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1409: #  Returns:
                   1410: #      1       - Ok to continue processing.
                   1411: #      0       - Program should exit
                   1412: # Implicit inputs:
                   1413: #     whatever the userload() function requires.
                   1414: #  Implicit outputs:
                   1415: #     the reply is written to the client.
                   1416: #
                   1417: sub user_load_handler {
                   1418:     my ($cmd, $tail, $replyfd) = @_;
                   1419: 
1.365     albertel 1420:     my $userloadpercent=&Apache::lonnet::userload();
1.387     albertel 1421:     &Reply($replyfd, \$userloadpercent, "$cmd:$tail");
1.217     foxr     1422:     
                   1423:     return 1;
                   1424: }
1.263     albertel 1425: &register_handler("userload", \&user_load_handler, 0, 1, 0);
1.217     foxr     1426: 
1.218     foxr     1427: #   Process a request for the authorization type of a user:
                   1428: #   (userauth).
                   1429: #
                   1430: # Parameters:
                   1431: #      $cmd    - the actual keyword that invoked us.
                   1432: #      $tail   - the tail of the request that invoked us.
                   1433: #      $replyfd- File descriptor connected to the client
                   1434: #  Returns:
                   1435: #      1       - Ok to continue processing.
                   1436: #      0       - Program should exit
                   1437: # Implicit outputs:
                   1438: #    The user authorization type is written to the client.
                   1439: #
                   1440: sub user_authorization_type {
                   1441:     my ($cmd, $tail, $replyfd) = @_;
                   1442:    
                   1443:     my $userinput = "$cmd:$tail";
                   1444:    
                   1445:     #  Pull the domain and username out of the command tail.
1.222     foxr     1446:     # and call get_auth_type to determine the authentication type.
1.218     foxr     1447:    
                   1448:     my ($udom,$uname)=split(/:/,$tail);
1.222     foxr     1449:     my $result = &get_auth_type($udom, $uname);
1.218     foxr     1450:     if($result eq "nouser") {
                   1451: 	&Failure( $replyfd, "unknown_user\n", $userinput);
                   1452:     } else {
                   1453: 	#
1.222     foxr     1454: 	# We only want to pass the second field from get_auth_type
1.218     foxr     1455: 	# for ^krb.. otherwise we'll be handing out the encrypted
                   1456: 	# password for internals e.g.
                   1457: 	#
                   1458: 	my ($type,$otherinfo) = split(/:/,$result);
                   1459: 	if($type =~ /^krb/) {
                   1460: 	    $type = $result;
1.269     raeburn  1461: 	} else {
                   1462:             $type .= ':';
                   1463:         }
1.387     albertel 1464: 	&Reply( $replyfd, \$type, $userinput);
1.218     foxr     1465:     }
                   1466:   
                   1467:     return 1;
                   1468: }
                   1469: &register_handler("currentauth", \&user_authorization_type, 1, 1, 0);
                   1470: 
                   1471: #   Process a request by a manager to push a hosts or domain table 
                   1472: #   to us.  We pick apart the command and pass it on to the subs
                   1473: #   that already exist to do this.
                   1474: #
                   1475: # Parameters:
                   1476: #      $cmd    - the actual keyword that invoked us.
                   1477: #      $tail   - the tail of the request that invoked us.
                   1478: #      $client - File descriptor connected to the client
                   1479: #  Returns:
                   1480: #      1       - Ok to continue processing.
                   1481: #      0       - Program should exit
                   1482: # Implicit Output:
                   1483: #    a reply is written to the client.
                   1484: sub push_file_handler {
                   1485:     my ($cmd, $tail, $client) = @_;
1.412     foxr     1486:     &Debug("In push file handler");
1.218     foxr     1487:     my $userinput = "$cmd:$tail";
                   1488: 
                   1489:     # At this time we only know that the IP of our partner is a valid manager
                   1490:     # the code below is a hook to do further authentication (e.g. to resolve
                   1491:     # spoofing).
                   1492: 
                   1493:     my $cert = &GetCertificate($userinput);
1.412     foxr     1494:     if(&ValidManager($cert)) {
                   1495: 	&Debug("Valid manager: $client");
1.218     foxr     1496: 
                   1497: 	# Now presumably we have the bona fides of both the peer host and the
                   1498: 	# process making the request.
                   1499:       
                   1500: 	my $reply = &PushFile($userinput);
1.387     albertel 1501: 	&Reply($client, \$reply, $userinput);
1.218     foxr     1502: 
                   1503:     } else {
1.412     foxr     1504: 	&logthis("push_file_handler $client is not valid");
1.218     foxr     1505: 	&Failure( $client, "refused\n", $userinput);
                   1506:     } 
1.219     foxr     1507:     return 1;
1.218     foxr     1508: }
                   1509: &register_handler("pushfile", \&push_file_handler, 1, 0, 1);
                   1510: 
1.399     raeburn  1511: # The du_handler routine should be considered obsolete and is retained
                   1512: # for communication with legacy servers.  Please see the du2_handler.
1.243     banghart 1513: #
1.399     raeburn  1514: #   du  - list the disk usage of a directory recursively. 
1.243     banghart 1515: #    
                   1516: #   note: stolen code from the ls file handler
                   1517: #   under construction by Rick Banghart 
                   1518: #    .
                   1519: # Parameters:
                   1520: #    $cmd        - The command that dispatched us (du).
                   1521: #    $ududir     - The directory path to list... I'm not sure what this
                   1522: #                  is relative as things like ls:. return e.g.
                   1523: #                  no_such_dir.
                   1524: #    $client     - Socket open on the client.
                   1525: # Returns:
                   1526: #     1 - indicating that the daemon should not disconnect.
                   1527: # Side Effects:
                   1528: #   The reply is written to  $client.
                   1529: #
                   1530: sub du_handler {
                   1531:     my ($cmd, $ududir, $client) = @_;
1.339     albertel 1532:     ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
1.251     foxr     1533:     my $userinput = "$cmd:$ududir";
                   1534: 
1.245     albertel 1535:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
                   1536: 	&Failure($client,"refused\n","$cmd:$ududir");
                   1537: 	return 1;
                   1538:     }
1.249     foxr     1539:     #  Since $ududir could have some nasties in it,
                   1540:     #  we will require that ududir is a valid
                   1541:     #  directory.  Just in case someone tries to
                   1542:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1543:     #  etc.
                   1544:     #
                   1545:     if (-d $ududir) {
1.292     albertel 1546: 	my $total_size=0;
                   1547: 	my $code=sub { 
                   1548: 	    if ($_=~/\.\d+\./) { return;} 
                   1549: 	    if ($_=~/\.meta$/) { return;}
1.362     albertel 1550: 	    if (-d $_)         { return;}
1.292     albertel 1551: 	    $total_size+=(stat($_))[7];
                   1552: 	};
1.295     raeburn  1553: 	chdir($ududir);
1.292     albertel 1554: 	find($code,$ududir);
                   1555: 	$total_size=int($total_size/1024);
1.387     albertel 1556: 	&Reply($client,\$total_size,"$cmd:$ududir");
1.249     foxr     1557:     } else {
1.251     foxr     1558: 	&Failure($client, "bad_directory:$ududir\n","$cmd:$ududir"); 
1.249     foxr     1559:     }
1.243     banghart 1560:     return 1;
                   1561: }
                   1562: &register_handler("du", \&du_handler, 0, 1, 0);
1.218     foxr     1563: 
1.399     raeburn  1564: # Please also see the du_handler, which is obsoleted by du2. 
                   1565: # du2_handler differs from du_handler in that required path to directory
                   1566: # provided by &propath() is prepended in the handler instead of on the 
                   1567: # client side.
1.239     foxr     1568: #
1.399     raeburn  1569: #   du2  - list the disk usage of a directory recursively.
                   1570: #
                   1571: # Parameters:
                   1572: #    $cmd        - The command that dispatched us (du).
                   1573: #    $tail       - The tail of the request that invoked us.
                   1574: #                  $tail is a : separated list of the following:
                   1575: #                   - $ududir - directory path to list (before prepending)
                   1576: #                   - $getpropath = 1 if &propath() should prepend
                   1577: #                   - $uname - username to use for &propath or user dir
                   1578: #                   - $udom - domain to use for &propath or user dir
                   1579: #                   All are escaped.
                   1580: #    $client     - Socket open on the client.
                   1581: # Returns:
                   1582: #     1 - indicating that the daemon should not disconnect.
                   1583: # Side Effects:
                   1584: #   The reply is written to $client.
                   1585: #
                   1586: 
                   1587: sub du2_handler {
                   1588:     my ($cmd, $tail, $client) = @_;
                   1589:     my ($ududir,$getpropath,$uname,$udom) = map { &unescape($_) } (split(/:/, $tail));
                   1590:     my $userinput = "$cmd:$tail";
                   1591:     if (($ududir=~/\.\./) || (($ududir!~m|^/home/httpd/|) && (!$getpropath))) {
                   1592:         &Failure($client,"refused\n","$cmd:$tail");
                   1593:         return 1;
                   1594:     }
                   1595:     if ($getpropath) {
                   1596:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1597:             $ududir = &propath($udom,$uname).'/'.$ududir;
                   1598:         } else {
                   1599:             &Failure($client,"refused\n","$cmd:$tail");
                   1600:             return 1;
                   1601:         }
                   1602:     }
                   1603:     #  Since $ududir could have some nasties in it,
                   1604:     #  we will require that ududir is a valid
                   1605:     #  directory.  Just in case someone tries to
                   1606:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1607:     #  etc.
                   1608:     #
                   1609:     if (-d $ududir) {
                   1610:         my $total_size=0;
                   1611:         my $code=sub {
                   1612:             if ($_=~/\.\d+\./) { return;}
                   1613:             if ($_=~/\.meta$/) { return;}
                   1614:             if (-d $_)         { return;}
                   1615:             $total_size+=(stat($_))[7];
                   1616:         };
                   1617:         chdir($ududir);
                   1618:         find($code,$ududir);
                   1619:         $total_size=int($total_size/1024);
                   1620:         &Reply($client,\$total_size,"$cmd:$ududir");
                   1621:     } else {
                   1622:         &Failure($client, "bad_directory:$ududir\n","$cmd:$tail");
                   1623:     }
                   1624:     return 1;
                   1625: }
                   1626: &register_handler("du2", \&du2_handler, 0, 1, 0);
                   1627: 
                   1628: #
                   1629: # The ls_handler routine should be considered obsolete and is retained
                   1630: # for communication with legacy servers.  Please see the ls3_handler.
1.280     matthew  1631: #
1.239     foxr     1632: #   ls  - list the contents of a directory.  For each file in the
                   1633: #    selected directory the filename followed by the full output of
                   1634: #    the stat function is returned.  The returned info for each
                   1635: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1636: #
                   1637: #    If the requested path contains /../ or is:
                   1638: #
                   1639: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1640: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1641: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1642: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
                   1643: #    or is:
                   1644: #
1.538     raeburn  1645: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1646: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1647: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1648: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529     raeburn  1649: #
                   1650: #    the response will be "refused".
                   1651: #
1.239     foxr     1652: # Parameters:
                   1653: #    $cmd        - The command that dispatched us (ls).
                   1654: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1655: #                  is relative as things like ls:. return e.g.
                   1656: #                  no_such_dir.
                   1657: #    $client     - Socket open on the client.
                   1658: # Returns:
                   1659: #     1 - indicating that the daemon should not disconnect.
                   1660: # Side Effects:
                   1661: #   The reply is written to  $client.
                   1662: #
                   1663: sub ls_handler {
1.280     matthew  1664:     # obsoleted by ls2_handler
1.239     foxr     1665:     my ($cmd, $ulsdir, $client) = @_;
                   1666: 
                   1667:     my $userinput = "$cmd:$ulsdir";
                   1668: 
                   1669:     my $obs;
                   1670:     my $rights;
                   1671:     my $ulsout='';
                   1672:     my $ulsfn;
1.529     raeburn  1673:     if ($ulsdir =~m{/\.\./}) {
                   1674:         &Failure($client,"refused\n",$userinput);
                   1675:         return 1;
                   1676:     }
1.239     foxr     1677:     if (-e $ulsdir) {
                   1678: 	if(-d $ulsdir) {
1.539     raeburn  1679:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1680:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529     raeburn  1681:                 &Failure($client,"refused\n",$userinput);
                   1682:                 return 1;
                   1683:             }
1.239     foxr     1684: 	    if (opendir(LSDIR,$ulsdir)) {
                   1685: 		while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1686: 		    undef($obs);
                   1687: 		    undef($rights); 
1.239     foxr     1688: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1689: 		    #We do some obsolete checking here
                   1690: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1691: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1692: 			my @obsolete=<FILE>;
                   1693: 			foreach my $obsolete (@obsolete) {
1.301     www      1694: 			    if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.239     foxr     1695: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
                   1696: 			}
                   1697: 		    }
                   1698: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
                   1699: 		    if($obs eq '1') { $ulsout.="&1"; }
                   1700: 		    else { $ulsout.="&0"; }
                   1701: 		    if($rights eq '1') { $ulsout.="&1:"; }
                   1702: 		    else { $ulsout.="&0:"; }
                   1703: 		}
                   1704: 		closedir(LSDIR);
                   1705: 	    }
                   1706: 	} else {
1.539     raeburn  1707:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1708:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529     raeburn  1709:                 &Failure($client,"refused\n",$userinput);
                   1710:                 return 1;
                   1711:             }
1.239     foxr     1712: 	    my @ulsstats=stat($ulsdir);
                   1713: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1714: 	}
                   1715:     } else {
                   1716: 	$ulsout='no_such_dir';
                   1717:     }
                   1718:     if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1719:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.239     foxr     1720:     
                   1721:     return 1;
                   1722: 
                   1723: }
                   1724: &register_handler("ls", \&ls_handler, 0, 1, 0);
                   1725: 
1.399     raeburn  1726: # The ls2_handler routine should be considered obsolete and is retained
                   1727: # for communication with legacy servers.  Please see the ls3_handler.
                   1728: # Please also see the ls_handler, which was itself obsoleted by ls2.
1.280     matthew  1729: # ls2_handler differs from ls_handler in that it escapes its return 
                   1730: # values before concatenating them together with ':'s.
                   1731: #
                   1732: #   ls2  - list the contents of a directory.  For each file in the
                   1733: #    selected directory the filename followed by the full output of
                   1734: #    the stat function is returned.  The returned info for each
                   1735: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1736: #
                   1737: #    If the requested path contains /../ or is:
                   1738: #
                   1739: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1740: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1741: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1742: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
                   1743: #    or is:
                   1744: #
1.538     raeburn  1745: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1746: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1747: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1748: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529     raeburn  1749: #
                   1750: #    the response will be "refused".
                   1751: #
1.280     matthew  1752: # Parameters:
                   1753: #    $cmd        - The command that dispatched us (ls).
                   1754: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1755: #                  is relative as things like ls:. return e.g.
                   1756: #                  no_such_dir.
                   1757: #    $client     - Socket open on the client.
                   1758: # Returns:
                   1759: #     1 - indicating that the daemon should not disconnect.
                   1760: # Side Effects:
                   1761: #   The reply is written to  $client.
                   1762: #
                   1763: sub ls2_handler {
                   1764:     my ($cmd, $ulsdir, $client) = @_;
                   1765: 
                   1766:     my $userinput = "$cmd:$ulsdir";
                   1767: 
                   1768:     my $obs;
                   1769:     my $rights;
                   1770:     my $ulsout='';
                   1771:     my $ulsfn;
1.529     raeburn  1772:     if ($ulsdir =~m{/\.\./}) {
                   1773:         &Failure($client,"refused\n",$userinput);
                   1774:         return 1;
                   1775:     }
1.280     matthew  1776:     if (-e $ulsdir) {
                   1777:         if(-d $ulsdir) {
1.539     raeburn  1778:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1779:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529     raeburn  1780:                 &Failure($client,"refused\n","$userinput");
                   1781:                 return 1;
                   1782:             }
1.280     matthew  1783:             if (opendir(LSDIR,$ulsdir)) {
                   1784:                 while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1785:                     undef($obs);
                   1786: 		    undef($rights); 
1.280     matthew  1787:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1788:                     #We do some obsolete checking here
                   1789:                     if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1790:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1791:                         my @obsolete=<FILE>;
                   1792:                         foreach my $obsolete (@obsolete) {
1.301     www      1793:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.280     matthew  1794:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1795:                                 $rights = 1;
                   1796:                             }
                   1797:                         }
                   1798:                     }
                   1799:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1800:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1801:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1802:                     $ulsout.= &escape($tmp).':';
                   1803:                 }
                   1804:                 closedir(LSDIR);
                   1805:             }
                   1806:         } else {
1.539     raeburn  1807:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1808:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529     raeburn  1809:                 &Failure($client,"refused\n",$userinput);
                   1810:                 return 1;
                   1811:             }
1.280     matthew  1812:             my @ulsstats=stat($ulsdir);
                   1813:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1814:         }
                   1815:     } else {
                   1816:         $ulsout='no_such_dir';
                   1817:    }
                   1818:    if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1819:    &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.280     matthew  1820:    return 1;
                   1821: }
                   1822: &register_handler("ls2", \&ls2_handler, 0, 1, 0);
1.399     raeburn  1823: #
                   1824: #   ls3  - list the contents of a directory.  For each file in the
                   1825: #    selected directory the filename followed by the full output of
                   1826: #    the stat function is returned.  The returned info for each
                   1827: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1828: #
                   1829: #    If the requested path (after prepending) contains /../ or is:
                   1830: #
                   1831: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1832: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1833: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1834: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
1.539     raeburn  1835: #        (d) /home/httpd/html/priv/<domain> and client is the homeserver
1.529     raeburn  1836: #
1.530     raeburn  1837: #    or is:
1.529     raeburn  1838: #
1.538     raeburn  1839: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1840: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1841: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1842: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
                   1843: #        (d) /home/httpd/html/priv/<domain>/<username>/ and client is the homeserver
1.529     raeburn  1844: #
                   1845: #    the response will be "refused".
                   1846: #
1.399     raeburn  1847: # Parameters:
                   1848: #    $cmd        - The command that dispatched us (ls).
                   1849: #    $tail       - The tail of the request that invoked us.
                   1850: #                  $tail is a : separated list of the following:
                   1851: #                   - $ulsdir - directory path to list (before prepending)
                   1852: #                   - $getpropath = 1 if &propath() should prepend
                   1853: #                   - $getuserdir = 1 if path to user dir in lonUsers should
                   1854: #                                     prepend
                   1855: #                   - $alternate_root - path to prepend
                   1856: #                   - $uname - username to use for &propath or user dir
                   1857: #                   - $udom - domain to use for &propath or user dir
                   1858: #            All of these except $getpropath and &getuserdir are escaped.    
                   1859: #                  no_such_dir.
                   1860: #    $client     - Socket open on the client.
                   1861: # Returns:
                   1862: #     1 - indicating that the daemon should not disconnect.
                   1863: # Side Effects:
                   1864: #   The reply is written to $client.
                   1865: #
                   1866: 
                   1867: sub ls3_handler {
                   1868:     my ($cmd, $tail, $client) = @_;
                   1869:     my $userinput = "$cmd:$tail";
                   1870:     my ($ulsdir,$getpropath,$getuserdir,$alternate_root,$uname,$udom) =
                   1871:         split(/:/,$tail);
                   1872:     if (defined($ulsdir)) {
                   1873:         $ulsdir = &unescape($ulsdir);
                   1874:     }
                   1875:     if (defined($alternate_root)) {
                   1876:         $alternate_root = &unescape($alternate_root);
                   1877:     }
                   1878:     if (defined($uname)) {
                   1879:         $uname = &unescape($uname);
                   1880:     }
                   1881:     if (defined($udom)) {
                   1882:         $udom = &unescape($udom);
                   1883:     }
                   1884: 
                   1885:     my $dir_root = $perlvar{'lonDocRoot'};
1.529     raeburn  1886:     if (($getpropath) || ($getuserdir)) {
1.399     raeburn  1887:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1888:             $dir_root = &propath($udom,$uname);
                   1889:             $dir_root =~ s/\/$//;
                   1890:         } else {
1.529     raeburn  1891:             &Failure($client,"refused\n",$userinput);
1.399     raeburn  1892:             return 1;
                   1893:         }
1.400     raeburn  1894:     } elsif ($alternate_root ne '') {
1.399     raeburn  1895:         $dir_root = $alternate_root;
                   1896:     }
1.408     raeburn  1897:     if (($dir_root ne '') && ($dir_root ne '/')) {
1.400     raeburn  1898:         if ($ulsdir =~ /^\//) {
                   1899:             $ulsdir = $dir_root.$ulsdir;
                   1900:         } else {
                   1901:             $ulsdir = $dir_root.'/'.$ulsdir;
                   1902:         }
1.399     raeburn  1903:     }
1.529     raeburn  1904:     if ($ulsdir =~m{/\.\./}) {
                   1905:         &Failure($client,"refused\n",$userinput);
                   1906:         return 1;
                   1907:     }
                   1908:     my $islocal;
                   1909:     my @machine_ids = &Apache::lonnet::current_machine_ids();
                   1910:     if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   1911:         $islocal = 1;
                   1912:     }
1.399     raeburn  1913:     my $obs;
                   1914:     my $rights;
                   1915:     my $ulsout='';
                   1916:     my $ulsfn;
1.547     raeburn  1917: 
                   1918:     my ($crscheck,$toplevel,$currdom,$currnum,$skip);
                   1919:     unless ($islocal) {
                   1920:         my ($major,$minor) = split(/\./,$clientversion);
                   1921:         if (($major < 2) || ($major == 2 && $minor < 12)) {
                   1922:             $crscheck = 1;
                   1923:         }
                   1924:     }
1.399     raeburn  1925:     if (-e $ulsdir) {
                   1926:         if(-d $ulsdir) {
1.529     raeburn  1927:             unless (($getpropath) || ($getuserdir) ||
1.539     raeburn  1928:                     ($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1929:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles}) ||
                   1930:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain}) && ($islocal))) {
1.529     raeburn  1931:                 &Failure($client,"refused\n",$userinput);
                   1932:                 return 1;
                   1933:             }
1.547     raeburn  1934:             if (($crscheck) &&
                   1935:                 ($ulsdir =~ m{^/home/httpd/html/res/($LONCAPA::match_domain)(/?$|/$LONCAPA::match_courseid)})) {
                   1936:                 ($currdom,my $posscnum) = ($1,$2);
                   1937:                 if (($posscnum eq '') || ($posscnum eq '/')) {
                   1938:                     $toplevel = 1;
                   1939:                 } else {
                   1940:                     $posscnum =~ s{^/+}{};
                   1941:                     if (&LONCAPA::Lond::is_course($currdom,$posscnum)) {
                   1942:                         $skip = 1;
                   1943:                     }
                   1944:                 }
                   1945:             }
                   1946:             if ((!$skip) && (opendir(LSDIR,$ulsdir))) {
1.399     raeburn  1947:                 while ($ulsfn=readdir(LSDIR)) {
1.547     raeburn  1948:                     if (($crscheck) && ($toplevel) && ($currdom ne '') &&
                   1949:                         ($ulsfn =~ /^$LONCAPA::match_courseid$/) && (-d "$ulsdir/$ulsfn")) {
                   1950:                         if (&LONCAPA::Lond::is_course($currdom,$ulsfn)) {
                   1951:                             next;
                   1952:                         }
                   1953:                     }
1.399     raeburn  1954:                     undef($obs);
                   1955:                     undef($rights);
                   1956:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1957:                     #We do some obsolete checking here
                   1958:                     if(-e $ulsdir.'/'.$ulsfn.".meta") {
                   1959:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1960:                         my @obsolete=<FILE>;
                   1961:                         foreach my $obsolete (@obsolete) {
                   1962:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
                   1963:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1964:                                 $rights = 1;
                   1965:                             }
                   1966:                         }
                   1967:                     }
                   1968:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1969:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1970:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1971:                     $ulsout.= &escape($tmp).':';
                   1972:                 }
                   1973:                 closedir(LSDIR);
                   1974:             }
                   1975:         } else {
1.529     raeburn  1976:             unless (($getpropath) || ($getuserdir) ||
1.539     raeburn  1977:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1978:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/}) ||
                   1979:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain/$LONCAPA::match_name/}) && ($islocal))) {
1.529     raeburn  1980:                 &Failure($client,"refused\n",$userinput);
                   1981:                 return 1;
                   1982:             }
1.399     raeburn  1983:             my @ulsstats=stat($ulsdir);
                   1984:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1985:         }
                   1986:     } else {
                   1987:         $ulsout='no_such_dir';
1.400     raeburn  1988:     }
                   1989:     if ($ulsout eq '') { $ulsout='empty'; }
                   1990:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
                   1991:     return 1;
1.399     raeburn  1992: }
                   1993: &register_handler("ls3", \&ls3_handler, 0, 1, 0);
1.280     matthew  1994: 
1.477     raeburn  1995: sub read_lonnet_global {
                   1996:     my ($cmd,$tail,$client) = @_;
                   1997:     my $userinput = "$cmd:$tail";
                   1998:     my $requested = &Apache::lonnet::thaw_unescape($tail);
                   1999:     my $result;
1.480     raeburn  2000:     my %packagevars = (
                   2001:                         spareid => \%Apache::lonnet::spareid,
                   2002:                         perlvar => \%Apache::lonnet::perlvar,
                   2003:                       );
                   2004:     my %limit_to = (
                   2005:                     perlvar => {
1.531     raeburn  2006:                                  lonOtherAuthen  => 1,
                   2007:                                  lonBalancer     => 1,
                   2008:                                  lonVersion      => 1,
                   2009:                                  lonAdmEMail     => 1,
                   2010:                                  lonSupportEMail => 1,  
                   2011:                                  lonSysEMail     => 1,
                   2012:                                  lonHostID       => 1,
                   2013:                                  lonRole         => 1,
                   2014:                                  lonDefDomain    => 1,
                   2015:                                  lonLoadLim      => 1,
                   2016:                                  lonUserLoadLim  => 1,
1.480     raeburn  2017:                                }
                   2018:                   );
1.477     raeburn  2019:     if (ref($requested) eq 'HASH') {
                   2020:         foreach my $what (keys(%{$requested})) {
                   2021:             my $response;
1.480     raeburn  2022:             my $items = {};
                   2023:             if (exists($packagevars{$what})) {
                   2024:                 if (ref($limit_to{$what}) eq 'HASH') {
                   2025:                     foreach my $varname (keys(%{$packagevars{$what}})) {
                   2026:                         if ($limit_to{$what}{$varname}) {
                   2027:                             $items->{$varname} = $packagevars{$what}{$varname};
                   2028:                         }
                   2029:                     }
                   2030:                 } else {
                   2031:                     $items = $packagevars{$what};
1.477     raeburn  2032:                 }
1.480     raeburn  2033:                 if ($what eq 'perlvar') {
                   2034:                     if (!exists($packagevars{$what}{'lonBalancer'})) {
1.559     raeburn  2035:                         if ($dist =~ /^(centos|rhes|fedora|scientific|oracle)/) {
1.480     raeburn  2036:                             my $othervarref=LONCAPA::Configuration::read_conf('httpd.conf');
                   2037:                             if (ref($othervarref) eq 'HASH') {
                   2038:                                 $items->{'lonBalancer'} = $othervarref->{'lonBalancer'};
                   2039:                             }
                   2040:                         }
                   2041:                     }
1.477     raeburn  2042:                 }
1.480     raeburn  2043:                 $response = &Apache::lonnet::freeze_escape($items);
1.477     raeburn  2044:             }
1.478     raeburn  2045:             $result .= &escape($what).'='.$response.'&';
1.477     raeburn  2046:         }
                   2047:     }
                   2048:     $result =~ s/\&$//;
                   2049:     &Reply($client,\$result,$userinput);
                   2050:     return 1;
                   2051: }
                   2052: &register_handler("readlonnetglobal", \&read_lonnet_global, 0, 1, 0);
                   2053: 
1.479     raeburn  2054: sub server_devalidatecache_handler {
                   2055:     my ($cmd,$tail,$client) = @_;
                   2056:     my $userinput = "$cmd:$tail";
1.503     raeburn  2057:     my $items = &unescape($tail);
                   2058:     my @cached = split(/\&/,$items);
                   2059:     foreach my $key (@cached) {
                   2060:         if ($key =~ /:/) {
                   2061:             my ($name,$id) = map { &unescape($_); } split(/:/,$key);
                   2062:             &Apache::lonnet::devalidate_cache_new($name,$id);
                   2063:         }
                   2064:     }
1.479     raeburn  2065:     my $result = 'ok';
                   2066:     &Reply($client,\$result,$userinput);
                   2067:     return 1;
                   2068: }
1.481     raeburn  2069: &register_handler("devalidatecache", \&server_devalidatecache_handler, 0, 1, 0);
1.479     raeburn  2070: 
1.410     raeburn  2071: sub server_timezone_handler {
                   2072:     my ($cmd,$tail,$client) = @_;
                   2073:     my $userinput = "$cmd:$tail";
                   2074:     my $timezone;
                   2075:     my $clockfile = '/etc/sysconfig/clock'; # Fedora/CentOS/SuSE
                   2076:     my $tzfile = '/etc/timezone'; # Debian/Ubuntu
                   2077:     if (-e $clockfile) {
                   2078:         if (open(my $fh,"<$clockfile")) {
                   2079:             while (<$fh>) {
                   2080:                 next if (/^[\#\s]/);
                   2081:                 if (/^(?:TIME)?ZONE\s*=\s*['"]?\s*([\w\/]+)/) {
                   2082:                     $timezone = $1;
                   2083:                     last;
                   2084:                 }
                   2085:             }
                   2086:             close($fh);
                   2087:         }
                   2088:     } elsif (-e $tzfile) {
                   2089:         if (open(my $fh,"<$tzfile")) {
                   2090:             $timezone = <$fh>;
                   2091:             close($fh);
                   2092:             chomp($timezone);
                   2093:             if ($timezone =~ m{^Etc/(\w+)$}) {
                   2094:                 $timezone = $1;
                   2095:             }
                   2096:         }
                   2097:     }
                   2098:     &Reply($client,\$timezone,$userinput); # This supports debug logging.
                   2099:     return 1;
                   2100: }
                   2101: &register_handler("servertimezone", \&server_timezone_handler, 0, 1, 0);
                   2102: 
1.413     raeburn  2103: sub server_loncaparev_handler {
                   2104:     my ($cmd,$tail,$client) = @_;
                   2105:     my $userinput = "$cmd:$tail";
                   2106:     &Reply($client,\$perlvar{'lonVersion'},$userinput);
                   2107:     return 1;
                   2108: }
                   2109: &register_handler("serverloncaparev", \&server_loncaparev_handler, 0, 1, 0);
                   2110: 
1.448     raeburn  2111: sub server_homeID_handler {
                   2112:     my ($cmd,$tail,$client) = @_;
                   2113:     my $userinput = "$cmd:$tail";
                   2114:     &Reply($client,\$perlvar{'lonHostID'},$userinput);
                   2115:     return 1;
                   2116: }
                   2117: &register_handler("serverhomeID", \&server_homeID_handler, 0, 1, 0);
                   2118: 
1.471     raeburn  2119: sub server_distarch_handler {
                   2120:     my ($cmd,$tail,$client) = @_;
                   2121:     my $userinput = "$cmd:$tail";
                   2122:     my $reply = &distro_and_arch();
                   2123:     &Reply($client,\$reply,$userinput);
                   2124:     return 1;
                   2125: }
                   2126: &register_handler("serverdistarch", \&server_distarch_handler, 0, 1, 0);
                   2127: 
1.523     raeburn  2128: sub server_certs_handler {
                   2129:     my ($cmd,$tail,$client) = @_;
                   2130:     my $userinput = "$cmd:$tail";
1.548     raeburn  2131:     my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
                   2132:     my $result = &LONCAPA::Lond::server_certs(\%perlvar,$perlvar{'lonHostID'},$hostname);
1.523     raeburn  2133:     &Reply($client,\$result,$userinput);
                   2134:     return;
                   2135: }
                   2136: &register_handler("servercerts", \&server_certs_handler, 0, 1, 0);
                   2137: 
1.218     foxr     2138: #   Process a reinit request.  Reinit requests that either
                   2139: #   lonc or lond be reinitialized so that an updated 
                   2140: #   host.tab or domain.tab can be processed.
                   2141: #
                   2142: # Parameters:
                   2143: #      $cmd    - the actual keyword that invoked us.
                   2144: #      $tail   - the tail of the request that invoked us.
                   2145: #      $client - File descriptor connected to the client
                   2146: #  Returns:
                   2147: #      1       - Ok to continue processing.
                   2148: #      0       - Program should exit
                   2149: #  Implicit output:
                   2150: #     a reply is sent to the client.
                   2151: #
                   2152: sub reinit_process_handler {
                   2153:     my ($cmd, $tail, $client) = @_;
                   2154:    
                   2155:     my $userinput = "$cmd:$tail";
                   2156:    
                   2157:     my $cert = &GetCertificate($userinput);
                   2158:     if(&ValidManager($cert)) {
                   2159: 	chomp($userinput);
                   2160: 	my $reply = &ReinitProcess($userinput);
1.387     albertel 2161: 	&Reply( $client,  \$reply, $userinput);
1.218     foxr     2162:     } else {
                   2163: 	&Failure( $client, "refused\n", $userinput);
                   2164:     }
                   2165:     return 1;
                   2166: }
                   2167: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
                   2168: 
                   2169: #  Process the editing script for a table edit operation.
                   2170: #  the editing operation must be encrypted and requested by
                   2171: #  a manager host.
                   2172: #
                   2173: # Parameters:
                   2174: #      $cmd    - the actual keyword that invoked us.
                   2175: #      $tail   - the tail of the request that invoked us.
                   2176: #      $client - File descriptor connected to the client
                   2177: #  Returns:
                   2178: #      1       - Ok to continue processing.
                   2179: #      0       - Program should exit
                   2180: #  Implicit output:
                   2181: #     a reply is sent to the client.
                   2182: #
                   2183: sub edit_table_handler {
                   2184:     my ($command, $tail, $client) = @_;
                   2185:    
                   2186:     my $userinput = "$command:$tail";
                   2187: 
                   2188:     my $cert = &GetCertificate($userinput);
                   2189:     if(&ValidManager($cert)) {
                   2190: 	my($filetype, $script) = split(/:/, $tail);
                   2191: 	if (($filetype eq "hosts") || 
                   2192: 	    ($filetype eq "domain")) {
                   2193: 	    if($script ne "") {
                   2194: 		&Reply($client,              # BUGBUG - EditFile
                   2195: 		      &EditFile($userinput), #   could fail.
                   2196: 		      $userinput);
                   2197: 	    } else {
                   2198: 		&Failure($client,"refused\n",$userinput);
                   2199: 	    }
                   2200: 	} else {
                   2201: 	    &Failure($client,"refused\n",$userinput);
                   2202: 	}
                   2203:     } else {
                   2204: 	&Failure($client,"refused\n",$userinput);
                   2205:     }
                   2206:     return 1;
                   2207: }
1.263     albertel 2208: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
1.218     foxr     2209: 
1.220     foxr     2210: #
                   2211: #   Authenticate a user against the LonCAPA authentication
                   2212: #   database.  Note that there are several authentication
                   2213: #   possibilities:
                   2214: #   - unix     - The user can be authenticated against the unix
                   2215: #                password file.
                   2216: #   - internal - The user can be authenticated against a purely 
                   2217: #                internal per user password file.
                   2218: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
                   2219: #                ticket granting authority.
                   2220: #   - user     - The person tailoring LonCAPA can supply a user authentication
                   2221: #                mechanism that is per system.
                   2222: #
                   2223: # Parameters:
                   2224: #    $cmd      - The command that got us here.
                   2225: #    $tail     - Tail of the command (remaining parameters).
                   2226: #    $client   - File descriptor connected to client.
                   2227: # Returns
                   2228: #     0        - Requested to exit, caller should shut down.
                   2229: #     1        - Continue processing.
                   2230: # Implicit inputs:
                   2231: #    The authentication systems describe above have their own forms of implicit
                   2232: #    input into the authentication process that are described above.
                   2233: #
                   2234: sub authenticate_handler {
                   2235:     my ($cmd, $tail, $client) = @_;
                   2236: 
                   2237:     
                   2238:     #  Regenerate the full input line 
                   2239:     
                   2240:     my $userinput  = $cmd.":".$tail;
                   2241:     
                   2242:     #  udom    - User's domain.
                   2243:     #  uname   - Username.
                   2244:     #  upass   - User's password.
1.396     raeburn  2245:     #  checkdefauth - Pass to validate_user() to try authentication
                   2246:     #                 with default auth type(s) if no user account.
1.447     raeburn  2247:     #  clientcancheckhost - Passed by clients with functionality in lonauth.pm
                   2248:     #                       to check if session can be hosted.
1.220     foxr     2249:     
1.447     raeburn  2250:     my ($udom, $uname, $upass, $checkdefauth, $clientcancheckhost)=split(/:/,$tail);
1.399     raeburn  2251:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass,  checkdefauth = $checkdefauth");
1.220     foxr     2252:     chomp($upass);
                   2253:     $upass=&unescape($upass);
                   2254: 
1.396     raeburn  2255:     my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
1.220     foxr     2256:     if($pwdcorrect) {
1.447     raeburn  2257:         my $canhost = 1;
                   2258:         unless ($clientcancheckhost) {
1.448     raeburn  2259:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   2260:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.452     raeburn  2261:             my @intdoms;
                   2262:             my $internet_names = &Apache::lonnet::get_internet_names($clientname);
                   2263:             if (ref($internet_names) eq 'ARRAY') {
                   2264:                 @intdoms = @{$internet_names};
                   2265:             }
1.448     raeburn  2266:             unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
1.447     raeburn  2267:                 my ($remote,$hosted);
                   2268:                 my $remotesession = &get_usersession_config($udom,'remotesession');
                   2269:                 if (ref($remotesession) eq 'HASH') {
1.525     raeburn  2270:                     $remote = $remotesession->{'remote'};
1.447     raeburn  2271:                 }
1.448     raeburn  2272:                 my $hostedsession = &get_usersession_config($clienthomedom,'hostedsession');
1.447     raeburn  2273:                 if (ref($hostedsession) eq 'HASH') {
                   2274:                     $hosted = $hostedsession->{'hosted'};
                   2275:                 }
1.448     raeburn  2276:                 $canhost = &Apache::lonnet::can_host_session($udom,$clientname,
1.492     droeschl 2277:                                                              $clientversion,
1.447     raeburn  2278:                                                              $remote,$hosted);
                   2279:             }
                   2280:         }
                   2281:         if ($canhost) {               
                   2282:             &Reply( $client, "authorized\n", $userinput);
                   2283:         } else {
                   2284:             &Reply( $client, "not_allowed_to_host\n", $userinput);
                   2285:         }
1.220     foxr     2286: 	#
                   2287: 	#  Bad credentials: Failed to authorize
                   2288: 	#
                   2289:     } else {
                   2290: 	&Failure( $client, "non_authorized\n", $userinput);
                   2291:     }
                   2292: 
                   2293:     return 1;
                   2294: }
1.263     albertel 2295: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
1.214     foxr     2296: 
1.222     foxr     2297: #
                   2298: #   Change a user's password.  Note that this function is complicated by
                   2299: #   the fact that a user may be authenticated in more than one way:
                   2300: #   At present, we are not able to change the password for all types of
                   2301: #   authentication methods.  Only for:
                   2302: #      unix    - unix password or shadow passoword style authentication.
                   2303: #      local   - Locally written authentication mechanism.
                   2304: #   For now, kerb4 and kerb5 password changes are not supported and result
                   2305: #   in an error.
                   2306: # FUTURE WORK:
                   2307: #    Support kerberos passwd changes?
                   2308: # Parameters:
                   2309: #    $cmd      - The command that got us here.
                   2310: #    $tail     - Tail of the command (remaining parameters).
                   2311: #    $client   - File descriptor connected to client.
                   2312: # Returns
                   2313: #     0        - Requested to exit, caller should shut down.
                   2314: #     1        - Continue processing.
                   2315: # Implicit inputs:
                   2316: #    The authentication systems describe above have their own forms of implicit
                   2317: #    input into the authentication process that are described above.
                   2318: sub change_password_handler {
                   2319:     my ($cmd, $tail, $client) = @_;
                   2320: 
                   2321:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
                   2322: 
                   2323:     #
                   2324:     #  udom  - user's domain.
                   2325:     #  uname - Username.
                   2326:     #  upass - Current password.
                   2327:     #  npass - New password.
1.346     raeburn  2328:     #  context - Context in which this was called 
                   2329:     #            (preferences or reset_by_email).
1.428     raeburn  2330:     #  lonhost - HostID of server where request originated 
1.222     foxr     2331:    
1.428     raeburn  2332:     my ($udom,$uname,$upass,$npass,$context,$lonhost)=split(/:/,$tail);
1.222     foxr     2333: 
                   2334:     $upass=&unescape($upass);
                   2335:     $npass=&unescape($npass);
                   2336:     &Debug("Trying to change password for $uname");
                   2337: 
                   2338:     # First require that the user can be authenticated with their
1.346     raeburn  2339:     # old password unless context was 'reset_by_email':
                   2340:     
1.428     raeburn  2341:     my ($validated,$failure);
1.346     raeburn  2342:     if ($context eq 'reset_by_email') {
1.428     raeburn  2343:         if ($lonhost eq '') {
                   2344:             $failure = 'invalid_client';
                   2345:         } else {
                   2346:             $validated = 1;
                   2347:         }
1.346     raeburn  2348:     } else {
                   2349:         $validated = &validate_user($udom, $uname, $upass);
                   2350:     }
1.222     foxr     2351:     if($validated) {
                   2352: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
                   2353: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
1.558     raeburn  2354:         my $notunique;
1.222     foxr     2355: 	if ($howpwd eq 'internal') {
                   2356: 	    &Debug("internal auth");
1.518     raeburn  2357:             my $ncpass = &hash_passwd($udom,$npass);
1.558     raeburn  2358:             my (undef,$method,@rest) = split(/!/,$contentpwd);
                   2359:             if ($method eq 'bcrypt') {
                   2360:                 my %passwdconf = &Apache::lonnet::get_passwdconf($udom);
                   2361:                 if (($passwdconf{'numsaved'}) && ($passwdconf{'numsaved'} =~ /^\d+$/)) {
                   2362:                     my @oldpasswds;
                   2363:                     my $userpath = &propath($udom,$uname);
                   2364:                     my $fullpath = $userpath.'/oldpasswds';
                   2365:                     if (-d $userpath) {
                   2366:                         my @oldfiles;
                   2367:                         if (-e $fullpath) {
                   2368:                             if (opendir(my $dir,$fullpath)) {
                   2369:                                 (@oldfiles) = grep(/^\d+$/,readdir($dir));
                   2370:                                 closedir($dir);
                   2371:                             }
                   2372:                             if (@oldfiles) {
                   2373:                                 @oldfiles = sort { $b <=> $a } (@oldfiles);
                   2374:                                 my $numremoved = 0;
                   2375:                                 for (my $i=0; $i<@oldfiles; $i++) {
                   2376:                                     if ($i>=$passwdconf{'numsaved'}) {
                   2377:                                         if (-f "$fullpath/$oldfiles[$i]") {
                   2378:                                             if (unlink("$fullpath/$oldfiles[$i]")) {
                   2379:                                                 $numremoved ++;
                   2380:                                             }
                   2381:                                         }
                   2382:                                     } elsif (open(my $fh,'<',"$fullpath/$oldfiles[$i]")) {
                   2383:                                         while (my $line = <$fh>) {
                   2384:                                             push(@oldpasswds,$line);
                   2385:                                         }
                   2386:                                         close($fh);
                   2387:                                     }
                   2388:                                 }
                   2389:                                 if ($numremoved) {
                   2390:                                     &logthis("unlinked $numremoved old password files for $uname:$udom");
                   2391:                                 }
                   2392:                             }
                   2393:                         }
                   2394:                         push(@oldpasswds,$contentpwd);
                   2395:                         foreach my $item (@oldpasswds) {
                   2396:                             my (undef,$method,@rest) = split(/!/,$item);
                   2397:                             if ($method eq 'bcrypt') {
                   2398:                                 my $result = &hash_passwd($udom,$npass,@rest);
                   2399:                                 if ($result eq $item) {
                   2400:                                     $notunique = 1;
                   2401:                                     last;
                   2402:                                 }
                   2403:                             }
                   2404:                         }
                   2405:                         unless ($notunique) {
                   2406:                             unless (-e $fullpath) {
                   2407:                                 if (&mkpath("$fullpath/")) {
                   2408:                                     chmod(0700,$fullpath);
                   2409:                                 }
                   2410:                             }
                   2411:                             if (-d $fullpath) {
                   2412:                                 my $now = time;
                   2413:                                 if (open(my $fh,'>',"$fullpath/$now")) {
                   2414:                                     print $fh $contentpwd;
                   2415:                                     close($fh);
                   2416:                                     chmod(0400,"$fullpath/$now");
                   2417:                                 }
                   2418:                             }
                   2419:                         }
                   2420:                     }
                   2421:                 }
                   2422:             }
                   2423:             if ($notunique) {
                   2424:                 my $msg="Result of password change for $uname:$udom - password matches one used before";
                   2425:                 if ($lonhost) {
                   2426:                     $msg .= " - request originated from: $lonhost";
                   2427:                 }
                   2428:                 &logthis($msg);
                   2429:                 &Reply($client, "prioruse\n", $userinput);
                   2430: 	    } elsif (&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
1.428     raeburn  2431: 		my $msg="Result of password change for $uname: pwchange_success";
                   2432:                 if ($lonhost) {
                   2433:                     $msg .= " - request originated from: $lonhost";
                   2434:                 }
                   2435:                 &logthis($msg);
1.518     raeburn  2436:                 &update_passwd_history($uname,$udom,$howpwd,$context);
1.222     foxr     2437: 		&Reply($client, "ok\n", $userinput);
                   2438: 	    } else {
                   2439: 		&logthis("Unable to open $uname passwd "               
                   2440: 			 ."to change password");
                   2441: 		&Failure( $client, "non_authorized\n",$userinput);
                   2442: 	    }
1.346     raeburn  2443: 	} elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
1.287     foxr     2444: 	    my $result = &change_unix_password($uname, $npass);
1.518     raeburn  2445:             if ($result eq 'ok') {
                   2446:                 &update_passwd_history($uname,$udom,$howpwd,$context);
1.561     raeburn  2447:             }
1.222     foxr     2448: 	    &logthis("Result of password change for $uname: ".
1.287     foxr     2449: 		     $result);
1.387     albertel 2450: 	    &Reply($client, \$result, $userinput);
1.222     foxr     2451: 	} else {
                   2452: 	    # this just means that the current password mode is not
                   2453: 	    # one we know how to change (e.g the kerberos auth modes or
                   2454: 	    # locally written auth handler).
                   2455: 	    #
                   2456: 	    &Failure( $client, "auth_mode_error\n", $userinput);
                   2457: 	}  
1.224     foxr     2458:     } else {
1.428     raeburn  2459: 	if ($failure eq '') {
                   2460: 	    $failure = 'non_authorized';
                   2461: 	}
                   2462: 	&Failure( $client, "$failure\n", $userinput);
1.222     foxr     2463:     }
                   2464: 
                   2465:     return 1;
                   2466: }
1.263     albertel 2467: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
1.222     foxr     2468: 
1.518     raeburn  2469: sub hash_passwd {
                   2470:     my ($domain,$plainpass,@rest) = @_;
                   2471:     my ($salt,$cost);
                   2472:     if (@rest) {
                   2473:         $cost = $rest[0];
                   2474:         # salt is first 22 characters, base-64 encoded by bcrypt
                   2475:         my $plainsalt = substr($rest[1],0,22);
                   2476:         $salt = Crypt::Eksblowfish::Bcrypt::de_base64($plainsalt);
                   2477:     } else {
1.533     raeburn  2478:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2479:         my $defaultcost = $domdefaults{'intauth_cost'};
1.518     raeburn  2480:         if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   2481:             $cost = 10;
                   2482:         } else {
                   2483:             $cost = $defaultcost;
                   2484:         }
                   2485:         # Generate random 16-octet base64 salt
                   2486:         $salt = "";
                   2487:         $salt .= pack("C", int rand(256)) for 1..16;
                   2488:     }
                   2489:     my $hash = &Crypt::Eksblowfish::Bcrypt::bcrypt_hash({
                   2490:         key_nul => 1,
                   2491:         cost    => $cost,
                   2492:         salt    => $salt,
                   2493:     }, Digest::SHA::sha512(Encode::encode('UTF-8',$plainpass)));
                   2494: 
                   2495:     my $result = join("!", "", "bcrypt", sprintf("%02d",$cost),
                   2496:                 &Crypt::Eksblowfish::Bcrypt::en_base64($salt).
                   2497:                 &Crypt::Eksblowfish::Bcrypt::en_base64($hash));
                   2498:     return $result;
                   2499: }
                   2500: 
1.225     foxr     2501: #
                   2502: #   Create a new user.  User in this case means a lon-capa user.
                   2503: #   The user must either already exist in some authentication realm
                   2504: #   like kerberos or the /etc/passwd.  If not, a user completely local to
                   2505: #   this loncapa system is created.
                   2506: #
                   2507: # Parameters:
                   2508: #    $cmd      - The command that got us here.
                   2509: #    $tail     - Tail of the command (remaining parameters).
                   2510: #    $client   - File descriptor connected to client.
                   2511: # Returns
                   2512: #     0        - Requested to exit, caller should shut down.
                   2513: #     1        - Continue processing.
                   2514: # Implicit inputs:
                   2515: #    The authentication systems describe above have their own forms of implicit
                   2516: #    input into the authentication process that are described above.
                   2517: sub add_user_handler {
                   2518: 
                   2519:     my ($cmd, $tail, $client) = @_;
                   2520: 
                   2521: 
                   2522:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2523:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
                   2524: 
                   2525:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
                   2526: 
                   2527: 
                   2528:     if($udom eq $currentdomainid) { # Reject new users for other domains...
                   2529: 	
                   2530: 	my $oldumask=umask(0077);
                   2531: 	chomp($npass);
                   2532: 	$npass=&unescape($npass);
                   2533: 	my $passfilename  = &password_path($udom, $uname);
                   2534: 	&Debug("Password file created will be:".$passfilename);
                   2535: 	if (-e $passfilename) {
                   2536: 	    &Failure( $client, "already_exists\n", $userinput);
                   2537: 	} else {
                   2538: 	    my $fperror='';
1.264     albertel 2539: 	    if (!&mkpath($passfilename)) {
                   2540: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
                   2541: 		    ."makeuser";
1.225     foxr     2542: 	    }
                   2543: 	    unless ($fperror) {
1.518     raeburn  2544: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2545:                                              $passfilename,'makeuser');
1.390     raeburn  2546: 		&Reply($client,\$result, $userinput);     #BUGBUG - could be fail
1.225     foxr     2547: 	    } else {
1.387     albertel 2548: 		&Failure($client, \$fperror, $userinput);
1.225     foxr     2549: 	    }
                   2550: 	}
                   2551: 	umask($oldumask);
                   2552:     }  else {
                   2553: 	&Failure($client, "not_right_domain\n",
                   2554: 		$userinput);	# Even if we are multihomed.
                   2555:     
                   2556:     }
                   2557:     return 1;
                   2558: 
                   2559: }
                   2560: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
                   2561: 
                   2562: #
                   2563: #   Change the authentication method of a user.  Note that this may
                   2564: #   also implicitly change the user's password if, for example, the user is
                   2565: #   joining an existing authentication realm.  Known authentication realms at
                   2566: #   this time are:
                   2567: #    internal   - Purely internal password file (only loncapa knows this user)
                   2568: #    local      - Institutionally written authentication module.
                   2569: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
                   2570: #    kerb4      - kerberos version 4
                   2571: #    kerb5      - kerberos version 5
                   2572: #
                   2573: # Parameters:
                   2574: #    $cmd      - The command that got us here.
                   2575: #    $tail     - Tail of the command (remaining parameters).
                   2576: #    $client   - File descriptor connected to client.
                   2577: # Returns
                   2578: #     0        - Requested to exit, caller should shut down.
                   2579: #     1        - Continue processing.
                   2580: # Implicit inputs:
                   2581: #    The authentication systems describe above have their own forms of implicit
                   2582: #    input into the authentication process that are described above.
1.287     foxr     2583: # NOTE:
                   2584: #   This is also used to change the authentication credential values (e.g. passwd).
                   2585: #   
1.225     foxr     2586: #
                   2587: sub change_authentication_handler {
                   2588: 
                   2589:     my ($cmd, $tail, $client) = @_;
                   2590:    
                   2591:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
                   2592: 
                   2593:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2594:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
                   2595:     if ($udom ne $currentdomainid) {
                   2596: 	&Failure( $client, "not_right_domain\n", $client);
                   2597:     } else {
                   2598: 	
                   2599: 	chomp($npass);
                   2600: 	
                   2601: 	$npass=&unescape($npass);
1.261     foxr     2602: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
1.225     foxr     2603: 	my $passfilename = &password_path($udom, $uname);
                   2604: 	if ($passfilename) {	# Not allowed to create a new user!!
1.287     foxr     2605: 	    # If just changing the unix passwd. need to arrange to run
1.502     raeburn  2606: 	    # passwd since otherwise make_passwd_file will fail as 
                   2607: 	    # creation of unix authenticated users is no longer supported
                   2608:             # except from the command line, when running make_domain_coordinator.pl
1.287     foxr     2609: 
                   2610: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
                   2611: 		my $result = &change_unix_password($uname, $npass);
                   2612: 		&logthis("Result of password change for $uname: ".$result);
                   2613: 		if ($result eq "ok") {
1.518     raeburn  2614:                     &update_passwd_history($uname,$udom,$umode,'changeuserauth'); 
1.390     raeburn  2615: 		    &Reply($client, \$result);
1.288     albertel 2616: 		} else {
1.387     albertel 2617: 		    &Failure($client, \$result);
1.287     foxr     2618: 		}
1.288     albertel 2619: 	    } else {
1.518     raeburn  2620: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2621:                                              $passfilename,'changeuserauth');
1.287     foxr     2622: 		#
                   2623: 		#  If the current auth mode is internal, and the old auth mode was
                   2624: 		#  unix, or krb*,  and the user is an author for this domain,
                   2625: 		#  re-run manage_permissions for that role in order to be able
                   2626: 		#  to take ownership of the construction space back to www:www
                   2627: 		#
1.502     raeburn  2628: 
                   2629: 
1.387     albertel 2630: 		&Reply($client, \$result, $userinput);
1.261     foxr     2631: 	    }
                   2632: 	       
                   2633: 
1.225     foxr     2634: 	} else {	       
1.251     foxr     2635: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
1.225     foxr     2636: 	}
                   2637:     }
                   2638:     return 1;
                   2639: }
                   2640: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
                   2641: 
1.518     raeburn  2642: sub update_passwd_history {
                   2643:     my ($uname,$udom,$umode,$context) = @_;
                   2644:     my $proname=&propath($udom,$uname);
                   2645:     my $now = time;
                   2646:     if (open(my $fh,">>$proname/passwd.log")) {
                   2647:         print $fh "$now:$umode:$context\n";
                   2648:         close($fh);
                   2649:     }
                   2650:     return;
                   2651: }
                   2652: 
1.225     foxr     2653: #
                   2654: #   Determines if this is the home server for a user.  The home server
                   2655: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
                   2656: #   to do is determine if this file exists.
                   2657: #
                   2658: # Parameters:
                   2659: #    $cmd      - The command that got us here.
                   2660: #    $tail     - Tail of the command (remaining parameters).
                   2661: #    $client   - File descriptor connected to client.
                   2662: # Returns
                   2663: #     0        - Requested to exit, caller should shut down.
                   2664: #     1        - Continue processing.
                   2665: # Implicit inputs:
                   2666: #    The authentication systems describe above have their own forms of implicit
                   2667: #    input into the authentication process that are described above.
                   2668: #
                   2669: sub is_home_handler {
                   2670:     my ($cmd, $tail, $client) = @_;
                   2671:    
                   2672:     my $userinput  = "$cmd:$tail";
                   2673:    
                   2674:     my ($udom,$uname)=split(/:/,$tail);
                   2675:     chomp($uname);
                   2676:     my $passfile = &password_filename($udom, $uname);
                   2677:     if($passfile) {
                   2678: 	&Reply( $client, "found\n", $userinput);
                   2679:     } else {
                   2680: 	&Failure($client, "not_found\n", $userinput);
                   2681:     }
                   2682:     return 1;
                   2683: }
                   2684: &register_handler("home", \&is_home_handler, 0,1,0);
                   2685: 
                   2686: #
1.434     www      2687: #   Process an update request for a resource.
                   2688: #   A resource has been modified that we hold a subscription to.
1.225     foxr     2689: #   If the resource is not local, then we must update, or at least invalidate our
                   2690: #   cached copy of the resource. 
                   2691: # Parameters:
                   2692: #    $cmd      - The command that got us here.
                   2693: #    $tail     - Tail of the command (remaining parameters).
                   2694: #    $client   - File descriptor connected to client.
                   2695: # Returns
                   2696: #     0        - Requested to exit, caller should shut down.
                   2697: #     1        - Continue processing.
                   2698: # Implicit inputs:
                   2699: #    The authentication systems describe above have their own forms of implicit
                   2700: #    input into the authentication process that are described above.
                   2701: #
                   2702: sub update_resource_handler {
                   2703: 
                   2704:     my ($cmd, $tail, $client) = @_;
                   2705:    
                   2706:     my $userinput = "$cmd:$tail";
                   2707:    
                   2708:     my $fname= $tail;		# This allows interactive testing
                   2709: 
                   2710: 
                   2711:     my $ownership=ishome($fname);
                   2712:     if ($ownership eq 'not_owner') {
                   2713: 	if (-e $fname) {
1.434     www      2714:             # Delete preview file, if exists
                   2715:             unlink("$fname.tmp");
                   2716:             # Get usage stats
1.225     foxr     2717: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
                   2718: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
                   2719: 	    my $now=time;
                   2720: 	    my $since=$now-$atime;
1.434     www      2721:             # If the file has not been used within lonExpire seconds,
                   2722:             # unsubscribe from it and delete local copy
1.225     foxr     2723: 	    if ($since>$perlvar{'lonExpire'}) {
1.365     albertel 2724: 		my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
1.308     albertel 2725: 		&devalidate_meta_cache($fname);
1.225     foxr     2726: 		unlink("$fname");
1.334     albertel 2727: 		unlink("$fname.meta");
1.225     foxr     2728: 	    } else {
1.434     www      2729:             # Yes, this is in active use. Get a fresh copy. Since it might be in
                   2730:             # very active use and huge (like a movie), copy it to "in.transfer" filename first.
1.225     foxr     2731: 		my $transname="$fname.in.transfer";
1.365     albertel 2732: 		my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
1.225     foxr     2733: 		my $response;
1.537     raeburn  2734: # FIXME: cannot replicate files that take more than two minutes to transfer -- needs checking now 1200s timeout used
                   2735: # for LWP request.
                   2736: 		my $request=new HTTP::Request('GET',"$remoteurl");
                   2737:                 $response=&LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,0,1);
1.225     foxr     2738: 		if ($response->is_error()) {
1.541     raeburn  2739:                     my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
                   2740:                     &devalidate_meta_cache($fname);
                   2741:                     if (-e $transname) {
                   2742:                         unlink($transname);
                   2743:                     }
                   2744:                     unlink($fname);
1.225     foxr     2745: 		    my $message=$response->status_line;
                   2746: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2747: 		} else {
                   2748: 		    if ($remoteurl!~/\.meta$/) {
1.537     raeburn  2749: 			my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2750:                         my $mresponse = &LONCAPA::LWPReq::makerequest($clientname,$mrequest,$fname.'.meta',\%perlvar,120,0,1);
                   2751: 			if ($mresponse->is_error()) {
                   2752: 			    unlink($fname.'.meta');
1.225     foxr     2753: 			}
                   2754: 		    }
1.434     www      2755:                     # we successfully transfered, copy file over to real name
1.225     foxr     2756: 		    rename($transname,$fname);
1.308     albertel 2757: 		    &devalidate_meta_cache($fname);
1.225     foxr     2758: 		}
                   2759: 	    }
                   2760: 	    &Reply( $client, "ok\n", $userinput);
                   2761: 	} else {
                   2762: 	    &Failure($client, "not_found\n", $userinput);
                   2763: 	}
                   2764:     } else {
                   2765: 	&Failure($client, "rejected\n", $userinput);
                   2766:     }
                   2767:     return 1;
                   2768: }
                   2769: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
                   2770: 
1.308     albertel 2771: sub devalidate_meta_cache {
                   2772:     my ($url) = @_;
                   2773:     use Cache::Memcached;
                   2774:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.365     albertel 2775:     $url = &Apache::lonnet::declutter($url);
1.308     albertel 2776:     $url =~ s-\.meta$--;
                   2777:     my $id = &escape('meta:'.$url);
                   2778:     $memcache->delete($id);
                   2779: }
                   2780: 
1.225     foxr     2781: #
1.226     foxr     2782: #   Fetch a user file from a remote server to the user's home directory
                   2783: #   userfiles subdir.
1.225     foxr     2784: # Parameters:
                   2785: #    $cmd      - The command that got us here.
                   2786: #    $tail     - Tail of the command (remaining parameters).
                   2787: #    $client   - File descriptor connected to client.
                   2788: # Returns
                   2789: #     0        - Requested to exit, caller should shut down.
                   2790: #     1        - Continue processing.
                   2791: #
                   2792: sub fetch_user_file_handler {
                   2793: 
                   2794:     my ($cmd, $tail, $client) = @_;
                   2795: 
                   2796:     my $userinput = "$cmd:$tail";
                   2797:     my $fname           = $tail;
1.232     foxr     2798:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1.225     foxr     2799:     my $udir=&propath($udom,$uname).'/userfiles';
                   2800:     unless (-e $udir) {
                   2801: 	mkdir($udir,0770); 
                   2802:     }
1.232     foxr     2803:     Debug("fetch user file for $fname");
1.225     foxr     2804:     if (-e $udir) {
                   2805: 	$ufile=~s/^[\.\~]+//;
1.232     foxr     2806: 
                   2807: 	# IF necessary, create the path right down to the file.
                   2808: 	# Note that any regular files in the way of this path are
                   2809: 	# wiped out to deal with some earlier folly of mine.
                   2810: 
1.267     raeburn  2811: 	if (!&mkpath($udir.'/'.$ufile)) {
1.264     albertel 2812: 	    &Failure($client, "unable_to_create\n", $userinput);	    
1.232     foxr     2813: 	}
                   2814: 
1.225     foxr     2815: 	my $destname=$udir.'/'.$ufile;
                   2816: 	my $transname=$udir.'/'.$ufile.'.in.transit';
1.476     raeburn  2817:         my $clientprotocol=$Apache::lonnet::protocol{$clientname};
                   2818:         $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.486     raeburn  2819: 	my $clienthost = &Apache::lonnet::hostname($clientname);
                   2820: 	my $remoteurl=$clientprotocol.'://'.$clienthost.'/userfiles/'.$fname;
1.225     foxr     2821: 	my $response;
1.232     foxr     2822: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
1.537     raeburn  2823: 	my $request=new HTTP::Request('GET',"$remoteurl");
                   2824:         my $verifycert = 1;
                   2825:         my @machine_ids = &Apache::lonnet::current_machine_ids();
                   2826:         if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   2827:             $verifycert = 0;
                   2828:         }
                   2829:         $response = &LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,$verifycert);
1.225     foxr     2830: 	if ($response->is_error()) {
                   2831: 	    unlink($transname);
                   2832: 	    my $message=$response->status_line;
                   2833: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2834: 	    &Failure($client, "failed\n", $userinput);
                   2835: 	} else {
1.232     foxr     2836: 	    Debug("Renaming $transname to $destname");
1.225     foxr     2837: 	    if (!rename($transname,$destname)) {
                   2838: 		&logthis("Unable to move $transname to $destname");
                   2839: 		unlink($transname);
                   2840: 		&Failure($client, "failed\n", $userinput);
                   2841: 	    } else {
1.495     raeburn  2842:                 if ($fname =~ /^default.+\.(page|sequence)$/) {
                   2843:                     my ($major,$minor) = split(/\./,$clientversion);
                   2844:                     if (($major < 2) || ($major == 2 && $minor < 11)) {
                   2845:                         my $now = time;
                   2846:                         &Apache::lonnet::do_cache_new('crschange',$udom.'_'.$uname,$now,600);
                   2847:                         my $key = &escape('internal.contentchange');
                   2848:                         my $what = "$key=$now";
                   2849:                         my $hashref = &tie_user_hash($udom,$uname,'environment',
                   2850:                                                      &GDBM_WRCREAT(),"P",$what);
                   2851:                         if ($hashref) {
                   2852:                             $hashref->{$key}=$now;
                   2853:                             if (!&untie_user_hash($hashref)) {
                   2854:                                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   2855:                                          "when updating internal.contentchange");
                   2856:                             }
                   2857:                         }
                   2858:                     }
                   2859:                 }
1.225     foxr     2860: 		&Reply($client, "ok\n", $userinput);
                   2861: 	    }
                   2862: 	}   
                   2863:     } else {
                   2864: 	&Failure($client, "not_home\n", $userinput);
                   2865:     }
                   2866:     return 1;
                   2867: }
                   2868: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
                   2869: 
1.226     foxr     2870: #
                   2871: #   Remove a file from a user's home directory userfiles subdirectory.
                   2872: # Parameters:
                   2873: #    cmd   - the Lond request keyword that got us here.
                   2874: #    tail  - the part of the command past the keyword.
                   2875: #    client- File descriptor connected with the client.
                   2876: #
                   2877: # Returns:
                   2878: #    1    - Continue processing.
                   2879: sub remove_user_file_handler {
                   2880:     my ($cmd, $tail, $client) = @_;
                   2881: 
                   2882:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2883: 
                   2884:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2885:     if ($ufile =~m|/\.\./|) {
                   2886: 	# any files paths with /../ in them refuse 
                   2887: 	# to deal with
                   2888: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2889:     } else {
                   2890: 	my $udir = &propath($udom,$uname);
                   2891: 	if (-e $udir) {
                   2892: 	    my $file=$udir.'/userfiles/'.$ufile;
                   2893: 	    if (-e $file) {
1.253     foxr     2894: 		#
                   2895: 		#   If the file is a regular file unlink is fine...
1.520     raeburn  2896: 		#   However it's possible the client wants a dir 
                   2897: 		#   removed, in which case rmdir is more appropriate.
                   2898: 		#   Note: rmdir will only remove an empty directory.
1.253     foxr     2899: 		#
1.240     banghart 2900: 	        if (-f $file){
1.241     albertel 2901: 		    unlink($file);
1.520     raeburn  2902:                     # for html files remove the associated .bak file 
                   2903:                     # which may have been created by the editor.
                   2904:                     if ($ufile =~ m{^((docs|supplemental)/(?:\d+|default)/\d+(?:|/.+)/)[^/]+\.x?html?$}i) {
                   2905:                         my $path = $1;
                   2906:                         if (-e $file.'.bak') {
                   2907:                             unlink($file.'.bak');
                   2908:                         }
                   2909:                     }
1.241     albertel 2910: 		} elsif(-d $file) {
                   2911: 		    rmdir($file);
1.240     banghart 2912: 		}
1.226     foxr     2913: 		if (-e $file) {
1.253     foxr     2914: 		    #  File is still there after we deleted it ?!?
                   2915: 
1.226     foxr     2916: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2917: 		} else {
                   2918: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2919: 		}
                   2920: 	    } else {
                   2921: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2922: 	    }
                   2923: 	} else {
                   2924: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2925: 	}
                   2926:     }
                   2927:     return 1;
                   2928: }
                   2929: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
                   2930: 
1.236     albertel 2931: #
                   2932: #   make a directory in a user's home directory userfiles subdirectory.
                   2933: # Parameters:
                   2934: #    cmd   - the Lond request keyword that got us here.
                   2935: #    tail  - the part of the command past the keyword.
                   2936: #    client- File descriptor connected with the client.
                   2937: #
                   2938: # Returns:
                   2939: #    1    - Continue processing.
                   2940: sub mkdir_user_file_handler {
                   2941:     my ($cmd, $tail, $client) = @_;
                   2942: 
                   2943:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2944:     $dir=&unescape($dir);
                   2945:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2946:     if ($ufile =~m|/\.\./|) {
                   2947: 	# any files paths with /../ in them refuse 
                   2948: 	# to deal with
                   2949: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2950:     } else {
                   2951: 	my $udir = &propath($udom,$uname);
                   2952: 	if (-e $udir) {
1.264     albertel 2953: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
                   2954: 	    if (!&mkpath($newdir)) {
                   2955: 		&Failure($client, "failed\n", "$cmd:$tail");
1.236     albertel 2956: 	    }
1.264     albertel 2957: 	    &Reply($client, "ok\n", "$cmd:$tail");
1.236     albertel 2958: 	} else {
                   2959: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2960: 	}
                   2961:     }
                   2962:     return 1;
                   2963: }
                   2964: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
                   2965: 
1.237     albertel 2966: #
                   2967: #   rename a file in a user's home directory userfiles subdirectory.
                   2968: # Parameters:
                   2969: #    cmd   - the Lond request keyword that got us here.
                   2970: #    tail  - the part of the command past the keyword.
                   2971: #    client- File descriptor connected with the client.
                   2972: #
                   2973: # Returns:
                   2974: #    1    - Continue processing.
                   2975: sub rename_user_file_handler {
                   2976:     my ($cmd, $tail, $client) = @_;
                   2977: 
                   2978:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
                   2979:     $old=&unescape($old);
                   2980:     $new=&unescape($new);
                   2981:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
                   2982: 	# any files paths with /../ in them refuse to deal with
                   2983: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2984:     } else {
                   2985: 	my $udir = &propath($udom,$uname);
                   2986: 	if (-e $udir) {
                   2987: 	    my $oldfile=$udir.'/userfiles/'.$old;
                   2988: 	    my $newfile=$udir.'/userfiles/'.$new;
                   2989: 	    if (-e $newfile) {
                   2990: 		&Failure($client, "exists\n", "$cmd:$tail");
                   2991: 	    } elsif (! -e $oldfile) {
                   2992: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2993: 	    } else {
                   2994: 		if (!rename($oldfile,$newfile)) {
                   2995: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2996: 		} else {
                   2997: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2998: 		}
                   2999: 	    }
                   3000: 	} else {
                   3001: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   3002: 	}
                   3003:     }
                   3004:     return 1;
                   3005: }
                   3006: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
                   3007: 
1.227     foxr     3008: #
1.382     albertel 3009: #  Checks if the specified user has an active session on the server
                   3010: #  return ok if so, not_found if not
                   3011: #
                   3012: # Parameters:
                   3013: #   cmd      - The request keyword that dispatched to tus.
                   3014: #   tail     - The tail of the request (colon separated parameters).
                   3015: #   client   - Filehandle open on the client.
                   3016: # Return:
                   3017: #    1.
                   3018: sub user_has_session_handler {
                   3019:     my ($cmd, $tail, $client) = @_;
                   3020: 
                   3021:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
                   3022:     
                   3023:     opendir(DIR,$perlvar{'lonIDsDir'});
                   3024:     my $filename;
                   3025:     while ($filename=readdir(DIR)) {
                   3026: 	last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
                   3027:     }
                   3028:     if ($filename) {
                   3029: 	&Reply($client, "ok\n", "$cmd:$tail");
                   3030:     } else {
                   3031: 	&Failure($client, "not_found\n", "$cmd:$tail");
                   3032:     }
                   3033:     return 1;
                   3034: 
                   3035: }
                   3036: &register_handler("userhassession", \&user_has_session_handler, 0,1,0);
                   3037: 
1.560     raeburn  3038: sub del_usersession_handler {
                   3039:     my ($cmd, $tail, $client) = @_;
                   3040: 
                   3041:     my $result;
                   3042:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
                   3043:     if (($udom =~ /^$LONCAPA::match_domain$/) && ($uname =~ /^$LONCAPA::match_username$/)) {
                   3044:         my $lonidsdir = $perlvar{'lonIDsDir'};
                   3045:         if (-d $lonidsdir) {
                   3046:             if (opendir(DIR,$lonidsdir)) {
                   3047:                 my $filename;
                   3048:                 while ($filename=readdir(DIR)) {
                   3049:                     if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/) {
                   3050:                         if (tie(my %oldenv,'GDBM_File',"$lonidsdir/$filename",
                   3051:                                 &GDBM_READER(),0640)) {
                   3052:                             my $linkedfile;
                   3053:                             if (exists($oldenv{'user.linkedenv'})) {
                   3054:                                 $linkedfile = $oldenv{'user.linkedenv'};
                   3055:                             }
                   3056:                             untie(%oldenv);
                   3057:                             $result = unlink("$lonidsdir/$filename");
                   3058:                             if ($result) {
                   3059:                                 if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   3060:                                     if (-l "$lonidsdir/$linkedfile.id") {
                   3061:                                         unlink("$lonidsdir/$linkedfile.id");
                   3062:                                     }
                   3063:                                 }
                   3064:                             }
                   3065:                         } else {
                   3066:                             $result = unlink("$lonidsdir/$filename");
                   3067:                         }
                   3068:                         last;
                   3069:                     }
                   3070:                 }
                   3071:             }
                   3072:         }
                   3073:         if ($result == 1) {
                   3074:             &Reply($client, "$result\n", "$cmd:$tail");
                   3075:         } else {
                   3076:             &Reply($client, "not_found\n", "$cmd:$tail");
                   3077:         }
                   3078:     } else {
                   3079:         &Failure($client, "invalid_user\n", "$cmd:$tail");
                   3080:     }
                   3081:     return 1;
                   3082: }
                   3083: 
                   3084: &register_handler("delusersession", \&del_usersession_handler, 0,1,0);
                   3085: 
1.382     albertel 3086: #
1.263     albertel 3087: #  Authenticate access to a user file by checking that the token the user's 
                   3088: #  passed also exists in their session file
1.227     foxr     3089: #
                   3090: # Parameters:
                   3091: #   cmd      - The request keyword that dispatched to tus.
                   3092: #   tail     - The tail of the request (colon separated parameters).
                   3093: #   client   - Filehandle open on the client.
                   3094: # Return:
                   3095: #    1.
                   3096: sub token_auth_user_file_handler {
                   3097:     my ($cmd, $tail, $client) = @_;
                   3098: 
                   3099:     my ($fname, $session) = split(/:/, $tail);
                   3100:     
                   3101:     chomp($session);
1.393     raeburn  3102:     my $reply="non_auth";
1.343     albertel 3103:     my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
                   3104:     if (open(ENVIN,"$file")) {
1.332     albertel 3105: 	flock(ENVIN,LOCK_SH);
1.343     albertel 3106: 	tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
                   3107: 	if (exists($disk_env{"userfile.$fname"})) {
1.393     raeburn  3108: 	    $reply="ok";
1.343     albertel 3109: 	} else {
                   3110: 	    foreach my $envname (keys(%disk_env)) {
                   3111: 		if ($envname=~ m|^userfile\.\Q$fname\E|) {
1.393     raeburn  3112: 		    $reply="ok";
1.343     albertel 3113: 		    last;
                   3114: 		}
                   3115: 	    }
1.227     foxr     3116: 	}
1.343     albertel 3117: 	untie(%disk_env);
1.227     foxr     3118: 	close(ENVIN);
1.387     albertel 3119: 	&Reply($client, \$reply, "$cmd:$tail");
1.227     foxr     3120:     } else {
                   3121: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
                   3122:     }
                   3123:     return 1;
                   3124: 
                   3125: }
                   3126: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229     foxr     3127: 
                   3128: #
                   3129: #   Unsubscribe from a resource.
                   3130: #
                   3131: # Parameters:
                   3132: #    $cmd      - The command that got us here.
                   3133: #    $tail     - Tail of the command (remaining parameters).
                   3134: #    $client   - File descriptor connected to client.
                   3135: # Returns
                   3136: #     0        - Requested to exit, caller should shut down.
                   3137: #     1        - Continue processing.
                   3138: #
                   3139: sub unsubscribe_handler {
                   3140:     my ($cmd, $tail, $client) = @_;
                   3141: 
                   3142:     my $userinput= "$cmd:$tail";
                   3143:     
                   3144:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
                   3145: 
                   3146:     &Debug("Unsubscribing $fname");
                   3147:     if (-e $fname) {
                   3148: 	&Debug("Exists");
                   3149: 	&Reply($client, &unsub($fname,$clientip), $userinput);
                   3150:     } else {
                   3151: 	&Failure($client, "not_found\n", $userinput);
                   3152:     }
                   3153:     return 1;
                   3154: }
                   3155: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
1.263     albertel 3156: 
1.230     foxr     3157: #   Subscribe to a resource
                   3158: #
                   3159: # Parameters:
                   3160: #    $cmd      - The command that got us here.
                   3161: #    $tail     - Tail of the command (remaining parameters).
                   3162: #    $client   - File descriptor connected to client.
                   3163: # Returns
                   3164: #     0        - Requested to exit, caller should shut down.
                   3165: #     1        - Continue processing.
                   3166: #
                   3167: sub subscribe_handler {
                   3168:     my ($cmd, $tail, $client)= @_;
                   3169: 
                   3170:     my $userinput  = "$cmd:$tail";
                   3171: 
                   3172:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
                   3173: 
                   3174:     return 1;
                   3175: }
                   3176: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
                   3177: 
                   3178: #
1.379     albertel 3179: #   Determine the latest version of a resource (it looks for the highest
                   3180: #   past version and then returns that +1)
1.230     foxr     3181: #
                   3182: # Parameters:
                   3183: #    $cmd      - The command that got us here.
                   3184: #    $tail     - Tail of the command (remaining parameters).
1.379     albertel 3185: #                 (Should consist of an absolute path to a file)
1.230     foxr     3186: #    $client   - File descriptor connected to client.
                   3187: # Returns
                   3188: #     0        - Requested to exit, caller should shut down.
                   3189: #     1        - Continue processing.
                   3190: #
                   3191: sub current_version_handler {
                   3192:     my ($cmd, $tail, $client) = @_;
                   3193: 
                   3194:     my $userinput= "$cmd:$tail";
                   3195:    
                   3196:     my $fname   = $tail;
                   3197:     &Reply( $client, &currentversion($fname)."\n", $userinput);
                   3198:     return 1;
                   3199: 
                   3200: }
                   3201: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
                   3202: 
                   3203: #  Make an entry in a user's activity log.
                   3204: #
                   3205: # Parameters:
                   3206: #    $cmd      - The command that got us here.
                   3207: #    $tail     - Tail of the command (remaining parameters).
                   3208: #    $client   - File descriptor connected to client.
                   3209: # Returns
                   3210: #     0        - Requested to exit, caller should shut down.
                   3211: #     1        - Continue processing.
                   3212: #
                   3213: sub activity_log_handler {
                   3214:     my ($cmd, $tail, $client) = @_;
                   3215: 
                   3216: 
                   3217:     my $userinput= "$cmd:$tail";
                   3218: 
                   3219:     my ($udom,$uname,$what)=split(/:/,$tail);
                   3220:     chomp($what);
                   3221:     my $proname=&propath($udom,$uname);
                   3222:     my $now=time;
                   3223:     my $hfh;
                   3224:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
                   3225: 	print $hfh "$now:$clientname:$what\n";
                   3226: 	&Reply( $client, "ok\n", $userinput); 
                   3227:     } else {
                   3228: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
                   3229: 		 ."while attempting log\n", 
                   3230: 		 $userinput);
                   3231:     }
                   3232: 
                   3233:     return 1;
                   3234: }
1.263     albertel 3235: &register_handler("log", \&activity_log_handler, 0, 1, 0);
1.230     foxr     3236: 
                   3237: #
                   3238: #   Put a namespace entry in a user profile hash.
                   3239: #   My druthers would be for this to be an encrypted interaction too.
                   3240: #   anything that might be an inadvertent covert channel about either
                   3241: #   user authentication or user personal information....
                   3242: #
                   3243: # Parameters:
                   3244: #    $cmd      - The command that got us here.
                   3245: #    $tail     - Tail of the command (remaining parameters).
                   3246: #    $client   - File descriptor connected to client.
                   3247: # Returns
                   3248: #     0        - Requested to exit, caller should shut down.
                   3249: #     1        - Continue processing.
                   3250: #
                   3251: sub put_user_profile_entry {
                   3252:     my ($cmd, $tail, $client)  = @_;
1.229     foxr     3253: 
1.230     foxr     3254:     my $userinput = "$cmd:$tail";
                   3255:     
1.242     raeburn  3256:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
1.230     foxr     3257:     if ($namespace ne 'roles') {
                   3258: 	chomp($what);
                   3259: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3260: 				  &GDBM_WRCREAT(),"P",$what);
                   3261: 	if($hashref) {
                   3262: 	    my @pairs=split(/\&/,$what);
                   3263: 	    foreach my $pair (@pairs) {
                   3264: 		my ($key,$value)=split(/=/,$pair);
                   3265: 		$hashref->{$key}=$value;
                   3266: 	    }
1.311     albertel 3267: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3268: 		&Reply( $client, "ok\n", $userinput);
                   3269: 	    } else {
                   3270: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3271: 			"while attempting put\n", 
                   3272: 			$userinput);
                   3273: 	    }
                   3274: 	} else {
1.316     albertel 3275: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.230     foxr     3276: 		     "while attempting put\n", $userinput);
                   3277: 	}
                   3278:     } else {
                   3279:         &Failure( $client, "refused\n", $userinput);
                   3280:     }
                   3281:     
                   3282:     return 1;
                   3283: }
                   3284: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
                   3285: 
1.283     albertel 3286: #   Put a piece of new data in hash, returns error if entry already exists
                   3287: # Parameters:
                   3288: #    $cmd      - The command that got us here.
                   3289: #    $tail     - Tail of the command (remaining parameters).
                   3290: #    $client   - File descriptor connected to client.
                   3291: # Returns
                   3292: #     0        - Requested to exit, caller should shut down.
                   3293: #     1        - Continue processing.
                   3294: #
                   3295: sub newput_user_profile_entry {
                   3296:     my ($cmd, $tail, $client)  = @_;
                   3297: 
                   3298:     my $userinput = "$cmd:$tail";
                   3299: 
                   3300:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
                   3301:     if ($namespace eq 'roles') {
                   3302:         &Failure( $client, "refused\n", $userinput);
                   3303: 	return 1;
                   3304:     }
                   3305: 
                   3306:     chomp($what);
                   3307: 
                   3308:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3309: 				 &GDBM_WRCREAT(),"N",$what);
                   3310:     if(!$hashref) {
1.316     albertel 3311: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.283     albertel 3312: 		  "while attempting put\n", $userinput);
                   3313: 	return 1;
                   3314:     }
                   3315: 
                   3316:     my @pairs=split(/\&/,$what);
                   3317:     foreach my $pair (@pairs) {
                   3318: 	my ($key,$value)=split(/=/,$pair);
                   3319: 	if (exists($hashref->{$key})) {
1.513     raeburn  3320:             if (!&untie_user_hash($hashref)) {
                   3321:                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   3322:                          "while attempting newput - early out as key exists");
                   3323:             }
                   3324:             &Failure($client, "key_exists: ".$key."\n",$userinput);
                   3325:             return 1;
1.283     albertel 3326: 	}
                   3327:     }
                   3328: 
                   3329:     foreach my $pair (@pairs) {
                   3330: 	my ($key,$value)=split(/=/,$pair);
                   3331: 	$hashref->{$key}=$value;
                   3332:     }
                   3333: 
1.311     albertel 3334:     if (&untie_user_hash($hashref)) {
1.283     albertel 3335: 	&Reply( $client, "ok\n", $userinput);
                   3336:     } else {
                   3337: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3338: 		 "while attempting put\n", 
                   3339: 		 $userinput);
                   3340:     }
                   3341:     return 1;
                   3342: }
                   3343: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
                   3344: 
1.230     foxr     3345: # 
                   3346: #   Increment a profile entry in the user history file.
                   3347: #   The history contains keyword value pairs.  In this case,
                   3348: #   The value itself is a pair of numbers.  The first, the current value
                   3349: #   the second an increment that this function applies to the current
                   3350: #   value.
                   3351: #
                   3352: # Parameters:
                   3353: #    $cmd      - The command that got us here.
                   3354: #    $tail     - Tail of the command (remaining parameters).
                   3355: #    $client   - File descriptor connected to client.
                   3356: # Returns
                   3357: #     0        - Requested to exit, caller should shut down.
                   3358: #     1        - Continue processing.
                   3359: #
                   3360: sub increment_user_value_handler {
                   3361:     my ($cmd, $tail, $client) = @_;
                   3362:     
                   3363:     my $userinput   = "$cmd:$tail";
                   3364:     
                   3365:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
                   3366:     if ($namespace ne 'roles') {
                   3367:         chomp($what);
                   3368: 	my $hashref = &tie_user_hash($udom, $uname,
                   3369: 				     $namespace, &GDBM_WRCREAT(),
                   3370: 				     "P",$what);
                   3371: 	if ($hashref) {
                   3372: 	    my @pairs=split(/\&/,$what);
                   3373: 	    foreach my $pair (@pairs) {
                   3374: 		my ($key,$value)=split(/=/,$pair);
1.284     raeburn  3375:                 $value = &unescape($value);
1.230     foxr     3376: 		# We could check that we have a number...
                   3377: 		if (! defined($value) || $value eq '') {
                   3378: 		    $value = 1;
                   3379: 		}
                   3380: 		$hashref->{$key}+=$value;
1.284     raeburn  3381:                 if ($namespace eq 'nohist_resourcetracker') {
                   3382:                     if ($hashref->{$key} < 0) {
                   3383:                         $hashref->{$key} = 0;
                   3384:                     }
                   3385:                 }
1.230     foxr     3386: 	    }
1.311     albertel 3387: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3388: 		&Reply( $client, "ok\n", $userinput);
                   3389: 	    } else {
                   3390: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3391: 			 "while attempting inc\n", $userinput);
                   3392: 	    }
                   3393: 	} else {
                   3394: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3395: 		     "while attempting inc\n", $userinput);
                   3396: 	}
                   3397:     } else {
                   3398: 	&Failure($client, "refused\n", $userinput);
                   3399:     }
                   3400:     
                   3401:     return 1;
                   3402: }
                   3403: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
                   3404: 
                   3405: #
                   3406: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
                   3407: #   Each 'role' a user has implies a set of permissions.  Adding a new role
                   3408: #   for a person grants the permissions packaged with that role
                   3409: #   to that user when the role is selected.
                   3410: #
                   3411: # Parameters:
                   3412: #    $cmd       - The command string (rolesput).
                   3413: #    $tail      - The remainder of the request line.  For rolesput this
                   3414: #                 consists of a colon separated list that contains:
                   3415: #                 The domain and user that is granting the role (logged).
                   3416: #                 The domain and user that is getting the role.
                   3417: #                 The roles being granted as a set of & separated pairs.
                   3418: #                 each pair a key value pair.
                   3419: #    $client    - File descriptor connected to the client.
                   3420: # Returns:
                   3421: #     0         - If the daemon should exit
                   3422: #     1         - To continue processing.
                   3423: #
                   3424: #
                   3425: sub roles_put_handler {
                   3426:     my ($cmd, $tail, $client) = @_;
                   3427: 
                   3428:     my $userinput  = "$cmd:$tail";
                   3429: 
                   3430:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
                   3431:     
                   3432: 
                   3433:     my $namespace='roles';
                   3434:     chomp($what);
                   3435:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3436: 				 &GDBM_WRCREAT(), "P",
                   3437: 				 "$exedom:$exeuser:$what");
                   3438:     #
                   3439:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
                   3440:     #  handle is open for the minimal amount of time.  Since the flush
                   3441:     #  is done on close this improves the chances the log will be an un-
                   3442:     #  corrupted ordered thing.
                   3443:     if ($hashref) {
1.261     foxr     3444: 	my $pass_entry = &get_auth_type($udom, $uname);
                   3445: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
                   3446: 	$auth_type = $auth_type.":";
1.230     foxr     3447: 	my @pairs=split(/\&/,$what);
                   3448: 	foreach my $pair (@pairs) {
                   3449: 	    my ($key,$value)=split(/=/,$pair);
                   3450: 	    &manage_permissions($key, $udom, $uname,
1.260     foxr     3451: 			       $auth_type);
1.230     foxr     3452: 	    $hashref->{$key}=$value;
                   3453: 	}
1.311     albertel 3454: 	if (&untie_user_hash($hashref)) {
1.230     foxr     3455: 	    &Reply($client, "ok\n", $userinput);
                   3456: 	} else {
                   3457: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3458: 		     "while attempting rolesput\n", $userinput);
                   3459: 	}
                   3460:     } else {
                   3461: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3462: 		 "while attempting rolesput\n", $userinput);
                   3463:     }
                   3464:     return 1;
                   3465: }
                   3466: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
                   3467: 
                   3468: #
1.231     foxr     3469: #   Deletes (removes) a role for a user.   This is equivalent to removing
                   3470: #  a permissions package associated with the role from the user's profile.
                   3471: #
                   3472: # Parameters:
                   3473: #     $cmd                 - The command (rolesdel)
                   3474: #     $tail                - The remainder of the request line. This consists
                   3475: #                             of:
                   3476: #                             The domain and user requesting the change (logged)
                   3477: #                             The domain and user being changed.
                   3478: #                             The roles being revoked.  These are shipped to us
                   3479: #                             as a bunch of & separated role name keywords.
                   3480: #     $client              - The file handle open on the client.
                   3481: # Returns:
                   3482: #     1                    - Continue processing
                   3483: #     0                    - Exit.
                   3484: #
                   3485: sub roles_delete_handler {
                   3486:     my ($cmd, $tail, $client)  = @_;
                   3487: 
                   3488:     my $userinput    = "$cmd:$tail";
                   3489:    
                   3490:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
                   3491:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
                   3492: 	   "what = ".$what);
                   3493:     my $namespace='roles';
                   3494:     chomp($what);
                   3495:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3496: 				 &GDBM_WRCREAT(), "D",
                   3497: 				 "$exedom:$exeuser:$what");
                   3498:     
                   3499:     if ($hashref) {
                   3500: 	my @rolekeys=split(/\&/,$what);
                   3501: 	
                   3502: 	foreach my $key (@rolekeys) {
                   3503: 	    delete $hashref->{$key};
                   3504: 	}
1.315     albertel 3505: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3506: 	    &Reply($client, "ok\n", $userinput);
                   3507: 	} else {
                   3508: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3509: 		     "while attempting rolesdel\n", $userinput);
                   3510: 	}
                   3511:     } else {
                   3512:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3513: 		 "while attempting rolesdel\n", $userinput);
                   3514:     }
                   3515:     
                   3516:     return 1;
                   3517: }
                   3518: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
                   3519: 
                   3520: # Unencrypted get from a user's profile database.  See 
                   3521: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
                   3522: # This function retrieves a keyed item from a specific named database in the
                   3523: # user's directory.
                   3524: #
                   3525: # Parameters:
                   3526: #   $cmd             - Command request keyword (get).
                   3527: #   $tail            - Tail of the command.  This is a colon separated list
                   3528: #                      consisting of the domain and username that uniquely
                   3529: #                      identifies the profile,
                   3530: #                      The 'namespace' which selects the gdbm file to 
                   3531: #                      do the lookup in, 
                   3532: #                      & separated list of keys to lookup.  Note that
                   3533: #                      the values are returned as an & separated list too.
                   3534: #   $client          - File descriptor open on the client.
                   3535: # Returns:
                   3536: #   1       - Continue processing.
                   3537: #   0       - Exit.
                   3538: #
                   3539: sub get_profile_entry {
                   3540:     my ($cmd, $tail, $client) = @_;
                   3541: 
                   3542:     my $userinput= "$cmd:$tail";
                   3543:    
                   3544:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3545:     chomp($what);
1.255     foxr     3546: 
1.390     raeburn  3547: 
1.255     foxr     3548:     my $replystring = read_profile($udom, $uname, $namespace, $what);
                   3549:     my ($first) = split(/:/,$replystring);
                   3550:     if($first ne "error") {
1.387     albertel 3551: 	&Reply($client, \$replystring, $userinput);
1.231     foxr     3552:     } else {
1.255     foxr     3553: 	&Failure($client, $replystring." while attempting get\n", $userinput);
1.231     foxr     3554:     }
                   3555:     return 1;
1.255     foxr     3556: 
                   3557: 
1.231     foxr     3558: }
                   3559: &register_handler("get", \&get_profile_entry, 0,1,0);
                   3560: 
                   3561: #
                   3562: #  Process the encrypted get request.  Note that the request is sent
                   3563: #  in clear, but the reply is encrypted.  This is a small covert channel:
                   3564: #  information about the sensitive keys is given to the snooper.  Just not
                   3565: #  information about the values of the sensitive key.  Hmm if I wanted to
                   3566: #  know these I'd snoop for the egets. Get the profile item names from them
                   3567: #  and then issue a get for them since there's no enforcement of the
                   3568: #  requirement of an encrypted get for particular profile items.  If I
                   3569: #  were re-doing this, I'd force the request to be encrypted as well as the
                   3570: #  reply.  I'd also just enforce encrypted transactions for all gets since
                   3571: #  that would prevent any covert channel snooping.
                   3572: #
                   3573: #  Parameters:
                   3574: #     $cmd               - Command keyword of request (eget).
1.536     raeburn  3575: #     $tail              - Tail of the command.  See GetProfileEntry
                   3576: #                          for more information about this.
1.231     foxr     3577: #     $client            - File open on the client.
                   3578: #  Returns:
                   3579: #     1      - Continue processing
                   3580: #     0      - server should exit.
                   3581: sub get_profile_entry_encrypted {
                   3582:     my ($cmd, $tail, $client) = @_;
                   3583: 
                   3584:     my $userinput = "$cmd:$tail";
                   3585:    
1.339     albertel 3586:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
1.231     foxr     3587:     chomp($what);
1.255     foxr     3588:     my $qresult = read_profile($udom, $uname, $namespace, $what);
                   3589:     my ($first) = split(/:/, $qresult);
                   3590:     if($first ne "error") {
                   3591: 	
                   3592: 	if ($cipher) {
                   3593: 	    my $cmdlength=length($qresult);
                   3594: 	    $qresult.="         ";
                   3595: 	    my $encqresult='';
                   3596: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   3597: 		$encqresult.= unpack("H16", 
                   3598: 				     $cipher->encrypt(substr($qresult,
                   3599: 							     $encidx,
                   3600: 							     8)));
                   3601: 	    }
                   3602: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   3603: 	} else {
1.231     foxr     3604: 		&Failure( $client, "error:no_key\n", $userinput);
                   3605: 	    }
                   3606:     } else {
1.255     foxr     3607: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
                   3608: 
1.231     foxr     3609:     }
                   3610:     
                   3611:     return 1;
                   3612: }
1.255     foxr     3613: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263     albertel 3614: 
1.231     foxr     3615: #
                   3616: #   Deletes a key in a user profile database.
                   3617: #   
                   3618: #   Parameters:
                   3619: #       $cmd                  - Command keyword (del).
                   3620: #       $tail                 - Command tail.  IN this case a colon
                   3621: #                               separated list containing:
                   3622: #                               The domain and user that identifies uniquely
                   3623: #                               the identity of the user.
                   3624: #                               The profile namespace (name of the profile
                   3625: #                               database file).
                   3626: #                               & separated list of keywords to delete.
                   3627: #       $client              - File open on client socket.
                   3628: # Returns:
                   3629: #     1   - Continue processing
                   3630: #     0   - Exit server.
                   3631: #
                   3632: #
                   3633: sub delete_profile_entry {
                   3634:     my ($cmd, $tail, $client) = @_;
                   3635: 
                   3636:     my $userinput = "cmd:$tail";
                   3637: 
                   3638:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3639:     chomp($what);
                   3640:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3641: 				 &GDBM_WRCREAT(),
                   3642: 				 "D",$what);
                   3643:     if ($hashref) {
                   3644:         my @keys=split(/\&/,$what);
                   3645: 	foreach my $key (@keys) {
                   3646: 	    delete($hashref->{$key});
                   3647: 	}
1.315     albertel 3648: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3649: 	    &Reply($client, "ok\n", $userinput);
                   3650: 	} else {
                   3651: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3652: 		    "while attempting del\n", $userinput);
                   3653: 	}
                   3654:     } else {
                   3655: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3656: 		 "while attempting del\n", $userinput);
                   3657:     }
                   3658:     return 1;
                   3659: }
                   3660: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263     albertel 3661: 
1.231     foxr     3662: #
                   3663: #  List the set of keys that are defined in a profile database file.
                   3664: #  A successful reply from this will contain an & separated list of
                   3665: #  the keys. 
                   3666: # Parameters:
                   3667: #     $cmd              - Command request (keys).
                   3668: #     $tail             - Remainder of the request, a colon separated
                   3669: #                         list containing domain/user that identifies the
                   3670: #                         user being queried, and the database namespace
                   3671: #                         (database filename essentially).
                   3672: #     $client           - File open on the client.
                   3673: #  Returns:
                   3674: #    1    - Continue processing.
                   3675: #    0    - Exit the server.
                   3676: #
                   3677: sub get_profile_keys {
                   3678:     my ($cmd, $tail, $client) = @_;
                   3679: 
                   3680:     my $userinput = "$cmd:$tail";
                   3681: 
                   3682:     my ($udom,$uname,$namespace)=split(/:/,$tail);
                   3683:     my $qresult='';
                   3684:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3685: 				  &GDBM_READER());
                   3686:     if ($hashref) {
                   3687: 	foreach my $key (keys %$hashref) {
                   3688: 	    $qresult.="$key&";
                   3689: 	}
1.315     albertel 3690: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3691: 	    $qresult=~s/\&$//;
1.387     albertel 3692: 	    &Reply($client, \$qresult, $userinput);
1.231     foxr     3693: 	} else {
                   3694: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3695: 		    "while attempting keys\n", $userinput);
                   3696: 	}
                   3697:     } else {
                   3698: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3699: 		 "while attempting keys\n", $userinput);
                   3700:     }
                   3701:    
                   3702:     return 1;
                   3703: }
                   3704: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
                   3705: 
                   3706: #
                   3707: #   Dump the contents of a user profile database.
                   3708: #   Note that this constitutes a very large covert channel too since
                   3709: #   the dump will return sensitive information that is not encrypted.
                   3710: #   The naive security assumption is that the session negotiation ensures
                   3711: #   our client is trusted and I don't believe that's assured at present.
                   3712: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
                   3713: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
                   3714: # 
                   3715: #  Parameters:
                   3716: #     $cmd           - The command request keyword (currentdump).
                   3717: #     $tail          - Remainder of the request, consisting of a colon
                   3718: #                      separated list that has the domain/username and
                   3719: #                      the namespace to dump (database file).
                   3720: #     $client        - file open on the remote client.
                   3721: # Returns:
                   3722: #     1    - Continue processing.
                   3723: #     0    - Exit the server.
                   3724: #
                   3725: sub dump_profile_database {
                   3726:     my ($cmd, $tail, $client) = @_;
                   3727: 
1.494     droeschl 3728:     my $res = LONCAPA::Lond::dump_profile_database($tail);
                   3729: 
                   3730:     if ($res =~ /^error:/) {
                   3731:         Failure($client, \$res, "$cmd:$tail");
                   3732:     } else {
                   3733:         Reply($client, \$res, "$cmd:$tail");
                   3734:     }
                   3735: 
                   3736:     return 1;  
                   3737: 
                   3738:     #TODO remove 
1.231     foxr     3739:     my $userinput = "$cmd:$tail";
                   3740:    
                   3741:     my ($udom,$uname,$namespace) = split(/:/,$tail);
                   3742:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3743: 				 &GDBM_READER());
                   3744:     if ($hashref) {
                   3745: 	# Structure of %data:
                   3746: 	# $data{$symb}->{$parameter}=$value;
                   3747: 	# $data{$symb}->{'v.'.$parameter}=$version;
                   3748: 	# since $parameter will be unescaped, we do not
                   3749:  	# have to worry about silly parameter names...
                   3750: 	
                   3751:         my $qresult='';
                   3752: 	my %data = ();                     # A hash of anonymous hashes..
                   3753: 	while (my ($key,$value) = each(%$hashref)) {
                   3754: 	    my ($v,$symb,$param) = split(/:/,$key);
                   3755: 	    next if ($v eq 'version' || $symb eq 'keys');
                   3756: 	    next if (exists($data{$symb}) && 
                   3757: 		     exists($data{$symb}->{$param}) &&
                   3758: 		     $data{$symb}->{'v.'.$param} > $v);
                   3759: 	    $data{$symb}->{$param}=$value;
                   3760: 	    $data{$symb}->{'v.'.$param}=$v;
                   3761: 	}
1.311     albertel 3762: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3763: 	    while (my ($symb,$param_hash) = each(%data)) {
                   3764: 		while(my ($param,$value) = each (%$param_hash)){
                   3765: 		    next if ($param =~ /^v\./);       # Ignore versions...
                   3766: 		    #
                   3767: 		    #   Just dump the symb=value pairs separated by &
                   3768: 		    #
                   3769: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
                   3770: 		}
                   3771: 	    }
                   3772: 	    chop($qresult);
1.387     albertel 3773: 	    &Reply($client , \$qresult, $userinput);
1.231     foxr     3774: 	} else {
                   3775: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3776: 		     "while attempting currentdump\n", $userinput);
                   3777: 	}
                   3778:     } else {
                   3779: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3780: 		"while attempting currentdump\n", $userinput);
                   3781:     }
                   3782: 
                   3783:     return 1;
                   3784: }
                   3785: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
                   3786: 
                   3787: #
                   3788: #   Dump a profile database with an optional regular expression
                   3789: #   to match against the keys.  In this dump, no effort is made
                   3790: #   to separate symb from version information. Presumably the
                   3791: #   databases that are dumped by this command are of a different
                   3792: #   structure.  Need to look at this and improve the documentation of
                   3793: #   both this and the currentdump handler.
                   3794: # Parameters:
                   3795: #    $cmd                     - The command keyword.
                   3796: #    $tail                    - All of the characters after the $cmd:
                   3797: #                               These are expected to be a colon
                   3798: #                               separated list containing:
                   3799: #                               domain/user - identifying the user.
                   3800: #                               namespace   - identifying the database.
                   3801: #                               regexp      - optional regular expression
                   3802: #                                             that is matched against
                   3803: #                                             database keywords to do
                   3804: #                                             selective dumps.
1.488     raeburn  3805: #                               range       - optional range of entries
                   3806: #                                             e.g., 10-20 would return the
                   3807: #                                             10th to 19th items, etc.  
1.231     foxr     3808: #   $client                   - Channel open on the client.
                   3809: # Returns:
                   3810: #    1    - Continue processing.
                   3811: # Side effects:
                   3812: #    response is written to $client.
                   3813: #
                   3814: sub dump_with_regexp {
                   3815:     my ($cmd, $tail, $client) = @_;
                   3816: 
1.494     droeschl 3817:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
1.490     droeschl 3818:     
                   3819:     if ($res =~ /^error:/) {
                   3820:         Failure($client, \$res, "$cmd:$tail");
                   3821:     } else {
                   3822:         Reply($client, \$res, "$cmd:$tail");
                   3823:     }
1.231     foxr     3824: 
                   3825:     return 1;
                   3826: }
                   3827: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
                   3828: 
                   3829: #  Store a set of key=value pairs associated with a versioned name.
                   3830: #
                   3831: #  Parameters:
                   3832: #    $cmd                - Request command keyword.
                   3833: #    $tail               - Tail of the request.  This is a colon
                   3834: #                          separated list containing:
                   3835: #                          domain/user - User and authentication domain.
                   3836: #                          namespace   - Name of the database being modified
                   3837: #                          rid         - Resource keyword to modify.
                   3838: #                          what        - new value associated with rid.
1.512     raeburn  3839: #                          laststore   - (optional) version=timestamp
                   3840: #                                        for most recent transaction for rid
                   3841: #                                        in namespace, when cstore was called
1.231     foxr     3842: #
                   3843: #    $client             - Socket open on the client.
                   3844: #
                   3845: #
                   3846: #  Returns:
                   3847: #      1 (keep on processing).
                   3848: #  Side-Effects:
                   3849: #    Writes to the client
1.512     raeburn  3850: #    Successful storage will cause either 'ok', or, if $laststore was included
                   3851: #    in the tail of the request, and the version number for the last transaction
                   3852: #    is larger than the version in $laststore, delay:$numtrans , where $numtrans
                   3853: #    is the number of store evevnts recorded for rid in namespace since
                   3854: #    lonnet::store() was called by the client.
                   3855: #
1.231     foxr     3856: sub store_handler {
                   3857:     my ($cmd, $tail, $client) = @_;
                   3858:  
                   3859:     my $userinput = "$cmd:$tail";
1.512     raeburn  3860:     chomp($tail);
                   3861:     my ($udom,$uname,$namespace,$rid,$what,$laststore) =split(/:/,$tail);
1.231     foxr     3862:     if ($namespace ne 'roles') {
                   3863: 
                   3864: 	my @pairs=split(/\&/,$what);
                   3865: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
1.268     albertel 3866: 				       &GDBM_WRCREAT(), "S",
1.231     foxr     3867: 				       "$rid:$what");
                   3868: 	if ($hashref) {
                   3869: 	    my $now = time;
1.512     raeburn  3870:             my $numtrans;
                   3871:             if ($laststore) {
                   3872:                 my ($previousversion,$previoustime) = split(/\=/,$laststore);
                   3873:                 my ($lastversion,$lasttime) = (0,0);
                   3874:                 $lastversion = $hashref->{"version:$rid"};
                   3875:                 if ($lastversion) {
                   3876:                     $lasttime = $hashref->{"$lastversion:$rid:timestamp"};
                   3877:                 }
                   3878:                 if (($previousversion) && ($previousversion !~ /\D/)) {
                   3879:                     if (($lastversion > $previousversion) && ($lasttime >= $previoustime)) {
                   3880:                         $numtrans = $lastversion - $previousversion;
                   3881:                     }
                   3882:                 } elsif ($lastversion) {
                   3883:                     $numtrans = $lastversion;
                   3884:                 }
                   3885:                 if ($numtrans) {
                   3886:                     $numtrans =~ s/D//g;
                   3887:                 }
                   3888:             }
1.231     foxr     3889: 	    $hashref->{"version:$rid"}++;
                   3890: 	    my $version=$hashref->{"version:$rid"};
                   3891: 	    my $allkeys=''; 
                   3892: 	    foreach my $pair (@pairs) {
                   3893: 		my ($key,$value)=split(/=/,$pair);
                   3894: 		$allkeys.=$key.':';
                   3895: 		$hashref->{"$version:$rid:$key"}=$value;
                   3896: 	    }
                   3897: 	    $hashref->{"$version:$rid:timestamp"}=$now;
                   3898: 	    $allkeys.='timestamp';
                   3899: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
1.311     albertel 3900: 	    if (&untie_user_hash($hashref)) {
1.512     raeburn  3901:                 my $msg = 'ok';
                   3902:                 if ($numtrans) {
                   3903:                     $msg = 'delay:'.$numtrans;
                   3904:                 }
                   3905: 		&Reply($client, "$msg\n", $userinput);
1.231     foxr     3906: 	    } else {
                   3907: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3908: 			"while attempting store\n", $userinput);
                   3909: 	    }
                   3910: 	} else {
                   3911: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3912: 		     "while attempting store\n", $userinput);
                   3913: 	}
                   3914:     } else {
                   3915: 	&Failure($client, "refused\n", $userinput);
                   3916:     }
                   3917: 
                   3918:     return 1;
                   3919: }
                   3920: &register_handler("store", \&store_handler, 0, 1, 0);
1.263     albertel 3921: 
1.323     albertel 3922: #  Modify a set of key=value pairs associated with a versioned name.
                   3923: #
                   3924: #  Parameters:
                   3925: #    $cmd                - Request command keyword.
                   3926: #    $tail               - Tail of the request.  This is a colon
                   3927: #                          separated list containing:
                   3928: #                          domain/user - User and authentication domain.
                   3929: #                          namespace   - Name of the database being modified
                   3930: #                          rid         - Resource keyword to modify.
                   3931: #                          v           - Version item to modify
                   3932: #                          what        - new value associated with rid.
                   3933: #
                   3934: #    $client             - Socket open on the client.
                   3935: #
                   3936: #
                   3937: #  Returns:
                   3938: #      1 (keep on processing).
                   3939: #  Side-Effects:
                   3940: #    Writes to the client
                   3941: sub putstore_handler {
                   3942:     my ($cmd, $tail, $client) = @_;
                   3943:  
                   3944:     my $userinput = "$cmd:$tail";
                   3945: 
                   3946:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
                   3947:     if ($namespace ne 'roles') {
                   3948: 
                   3949: 	chomp($what);
                   3950: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
                   3951: 				       &GDBM_WRCREAT(), "M",
                   3952: 				       "$rid:$v:$what");
                   3953: 	if ($hashref) {
                   3954: 	    my $now = time;
                   3955: 	    my %data = &hash_extract($what);
                   3956: 	    my @allkeys;
                   3957: 	    while (my($key,$value) = each(%data)) {
                   3958: 		push(@allkeys,$key);
                   3959: 		$hashref->{"$v:$rid:$key"} = $value;
                   3960: 	    }
                   3961: 	    my $allkeys = join(':',@allkeys);
                   3962: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
                   3963: 
                   3964: 	    if (&untie_user_hash($hashref)) {
                   3965: 		&Reply($client, "ok\n", $userinput);
                   3966: 	    } else {
                   3967: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3968: 			"while attempting store\n", $userinput);
                   3969: 	    }
                   3970: 	} else {
                   3971: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3972: 		     "while attempting store\n", $userinput);
                   3973: 	}
                   3974:     } else {
                   3975: 	&Failure($client, "refused\n", $userinput);
                   3976:     }
                   3977: 
                   3978:     return 1;
                   3979: }
                   3980: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
                   3981: 
                   3982: sub hash_extract {
                   3983:     my ($str)=@_;
                   3984:     my %hash;
                   3985:     foreach my $pair (split(/\&/,$str)) {
                   3986: 	my ($key,$value)=split(/=/,$pair);
                   3987: 	$hash{$key}=$value;
                   3988:     }
                   3989:     return (%hash);
                   3990: }
                   3991: sub hash_to_str {
                   3992:     my ($hash_ref)=@_;
                   3993:     my $str;
                   3994:     foreach my $key (keys(%$hash_ref)) {
                   3995: 	$str.=$key.'='.$hash_ref->{$key}.'&';
                   3996:     }
                   3997:     $str=~s/\&$//;
                   3998:     return $str;
                   3999: }
                   4000: 
1.231     foxr     4001: #
                   4002: #  Dump out all versions of a resource that has key=value pairs associated
                   4003: # with it for each version.  These resources are built up via the store
                   4004: # command.
                   4005: #
                   4006: #  Parameters:
                   4007: #     $cmd               - Command keyword.
                   4008: #     $tail              - Remainder of the request which consists of:
                   4009: #                          domain/user   - User and auth. domain.
                   4010: #                          namespace     - name of resource database.
                   4011: #                          rid           - Resource id.
                   4012: #    $client             - socket open on the client.
                   4013: #
                   4014: # Returns:
                   4015: #      1  indicating the caller should not yet exit.
                   4016: # Side-effects:
                   4017: #   Writes a reply to the client.
                   4018: #   The reply is a string of the following shape:
                   4019: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
                   4020: #    Where the 1 above represents version 1.
                   4021: #    this continues for all pairs of keys in all versions.
                   4022: #
                   4023: #
                   4024: #    
                   4025: #
                   4026: sub restore_handler {
                   4027:     my ($cmd, $tail, $client) = @_;
                   4028: 
                   4029:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
1.351     banghart 4030:     my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
1.352     albertel 4031:     $namespace=~s/\//\_/g;
1.350     albertel 4032:     $namespace = &LONCAPA::clean_username($namespace);
1.349     albertel 4033: 
1.231     foxr     4034:     chomp($rid);
                   4035:     my $qresult='';
1.309     albertel 4036:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
                   4037:     if ($hashref) {
                   4038: 	my $version=$hashref->{"version:$rid"};
1.231     foxr     4039: 	$qresult.="version=$version&";
                   4040: 	my $scope;
                   4041: 	for ($scope=1;$scope<=$version;$scope++) {
1.309     albertel 4042: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
1.231     foxr     4043: 	    my @keys=split(/:/,$vkeys);
                   4044: 	    my $key;
                   4045: 	    $qresult.="$scope:keys=$vkeys&";
                   4046: 	    foreach $key (@keys) {
1.309     albertel 4047: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
1.231     foxr     4048: 	    }                                  
                   4049: 	}
1.311     albertel 4050: 	if (&untie_user_hash($hashref)) {
1.231     foxr     4051: 	    $qresult=~s/\&$//;
1.387     albertel 4052: 	    &Reply( $client, \$qresult, $userinput);
1.231     foxr     4053: 	} else {
                   4054: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4055: 		    "while attempting restore\n", $userinput);
                   4056: 	}
                   4057:     } else {
                   4058: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4059: 		"while attempting restore\n", $userinput);
                   4060:     }
                   4061:   
                   4062:     return 1;
                   4063: 
                   4064: 
                   4065: }
                   4066: &register_handler("restore", \&restore_handler, 0,1,0);
1.234     foxr     4067: 
                   4068: #
1.324     raeburn  4069: #   Add a chat message to a synchronous discussion board.
1.234     foxr     4070: #
                   4071: # Parameters:
                   4072: #    $cmd                - Request keyword.
                   4073: #    $tail               - Tail of the command. A colon separated list
                   4074: #                          containing:
                   4075: #                          cdom    - Domain on which the chat board lives
1.324     raeburn  4076: #                          cnum    - Course containing the chat board.
                   4077: #                          newpost - Body of the posting.
                   4078: #                          group   - Optional group, if chat board is only 
                   4079: #                                    accessible in a group within the course 
1.234     foxr     4080: #   $client              - Socket open on the client.
                   4081: # Returns:
                   4082: #   1    - Indicating caller should keep on processing.
                   4083: #
                   4084: # Side-effects:
                   4085: #   writes a reply to the client.
                   4086: #
                   4087: #
                   4088: sub send_chat_handler {
                   4089:     my ($cmd, $tail, $client) = @_;
                   4090: 
                   4091:     
                   4092:     my $userinput = "$cmd:$tail";
                   4093: 
1.324     raeburn  4094:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
                   4095:     &chat_add($cdom,$cnum,$newpost,$group);
1.234     foxr     4096:     &Reply($client, "ok\n", $userinput);
                   4097: 
                   4098:     return 1;
                   4099: }
                   4100: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263     albertel 4101: 
1.234     foxr     4102: #
1.324     raeburn  4103: #   Retrieve the set of chat messages from a discussion board.
1.234     foxr     4104: #
                   4105: #  Parameters:
                   4106: #    $cmd             - Command keyword that initiated the request.
                   4107: #    $tail            - Remainder of the request after the command
                   4108: #                       keyword.  In this case a colon separated list of
                   4109: #                       chat domain    - Which discussion board.
                   4110: #                       chat id        - Discussion thread(?)
                   4111: #                       domain/user    - Authentication domain and username
                   4112: #                                        of the requesting person.
1.324     raeburn  4113: #                       group          - Optional course group containing
                   4114: #                                        the board.      
1.234     foxr     4115: #   $client           - Socket open on the client program.
                   4116: # Returns:
                   4117: #    1     - continue processing
                   4118: # Side effects:
                   4119: #    Response is written to the client.
                   4120: #
                   4121: sub retrieve_chat_handler {
                   4122:     my ($cmd, $tail, $client) = @_;
                   4123: 
                   4124: 
                   4125:     my $userinput = "$cmd:$tail";
                   4126: 
1.324     raeburn  4127:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
1.234     foxr     4128:     my $reply='';
1.324     raeburn  4129:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
1.234     foxr     4130: 	$reply.=&escape($_).':';
                   4131:     }
                   4132:     $reply=~s/\:$//;
1.387     albertel 4133:     &Reply($client, \$reply, $userinput);
1.234     foxr     4134: 
                   4135: 
                   4136:     return 1;
                   4137: }
                   4138: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
                   4139: 
                   4140: #
                   4141: #  Initiate a query of an sql database.  SQL query repsonses get put in
                   4142: #  a file for later retrieval.  This prevents sql query results from
                   4143: #  bottlenecking the system.  Note that with loncnew, perhaps this is
                   4144: #  less of an issue since multiple outstanding requests can be concurrently
                   4145: #  serviced.
                   4146: #
                   4147: #  Parameters:
1.535     raeburn  4148: #     $cmd       - Command keyword that initiated the request.
1.234     foxr     4149: #     $tail      - Remainder of the command after the keyword.
                   4150: #                  For this function, this consists of a query and
                   4151: #                  3 arguments that are self-documentingly labelled
                   4152: #                  in the original arg1, arg2, arg3.
                   4153: #     $client    - Socket open on the client.
                   4154: # Return:
                   4155: #    1   - Indicating processing should continue.
                   4156: # Side-effects:
                   4157: #    a reply is written to $client.
                   4158: #
                   4159: sub send_query_handler {
                   4160:     my ($cmd, $tail, $client) = @_;
                   4161: 
                   4162:     my $userinput = "$cmd:$tail";
                   4163: 
                   4164:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
                   4165:     $query=~s/\n*$//g;
1.534     raeburn  4166:     if (($query eq 'usersearch') || ($query eq 'instdirsearch')) {
                   4167:         my $usersearchconf = &get_usersearch_config($currentdomainid,'directorysrch');
                   4168:         my $earlyout;
                   4169:         if (ref($usersearchconf) eq 'HASH') {
                   4170:             if ($currentdomainid eq $clienthomedom) {
                   4171:                 if ($query eq 'usersearch') {
                   4172:                     if ($usersearchconf->{'lcavailable'} eq '0') {
                   4173:                         $earlyout = 1;
                   4174:                     }
                   4175:                 } else {
                   4176:                     if ($usersearchconf->{'available'} eq '0') {
                   4177:                         $earlyout = 1;
                   4178:                     }
                   4179:                 }
                   4180:             } else {
                   4181:                 if ($query eq 'usersearch') {
                   4182:                     if ($usersearchconf->{'lclocalonly'}) {
                   4183:                         $earlyout = 1;
                   4184:                     }
                   4185:                 } else {
                   4186:                     if ($usersearchconf->{'localonly'}) {
                   4187:                         $earlyout = 1;
                   4188:                     }
                   4189:                 }
                   4190:             }
                   4191:         }
                   4192:         if ($earlyout) {
                   4193:             &Reply($client, "query_not_authorized\n");
                   4194:             return 1;
                   4195:         }
                   4196:     }
1.234     foxr     4197:     &Reply($client, "". &sql_reply("$clientname\&$query".
                   4198: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
                   4199: 	  $userinput);
                   4200:     
                   4201:     return 1;
                   4202: }
                   4203: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
                   4204: 
                   4205: #
                   4206: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
                   4207: #   The query is submitted via a "querysend" transaction.
                   4208: #   There it is passed on to the lonsql daemon, queued and issued to
                   4209: #   mysql.
                   4210: #     This transaction is invoked when the sql transaction is complete
                   4211: #   it stores the query results in flie and indicates query completion.
                   4212: #   presumably local software then fetches this response... I'm guessing
                   4213: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
                   4214: #   lonsql on completion of the query interacts with the lond of our
                   4215: #   client to do a query reply storing two files:
                   4216: #    - id     - The results of the query.
                   4217: #    - id.end - Indicating the transaction completed. 
                   4218: #    NOTE: id is a unique id assigned to the query and querysend time.
                   4219: # Parameters:
                   4220: #    $cmd        - Command keyword that initiated this request.
                   4221: #    $tail       - Remainder of the tail.  In this case that's a colon
                   4222: #                  separated list containing the query Id and the 
                   4223: #                  results of the query.
                   4224: #    $client     - Socket open on the client.
                   4225: # Return:
                   4226: #    1           - Indicating that we should continue processing.
                   4227: # Side effects:
                   4228: #    ok written to the client.
                   4229: #
                   4230: sub reply_query_handler {
                   4231:     my ($cmd, $tail, $client) = @_;
                   4232: 
                   4233: 
                   4234:     my $userinput = "$cmd:$tail";
                   4235: 
1.339     albertel 4236:     my ($id,$reply)=split(/:/,$tail); 
1.234     foxr     4237:     my $store;
                   4238:     my $execdir=$perlvar{'lonDaemons'};
                   4239:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
                   4240: 	$reply=~s/\&/\n/g;
                   4241: 	print $store $reply;
                   4242: 	close $store;
                   4243: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
                   4244: 	print $store2 "done\n";
                   4245: 	close $store2;
                   4246: 	&Reply($client, "ok\n", $userinput);
                   4247:     } else {
                   4248: 	&Failure($client, "error: ".($!+0)
                   4249: 		." IO::File->new Failed ".
                   4250: 		"while attempting queryreply\n", $userinput);
                   4251:     }
                   4252:  
                   4253: 
                   4254:     return 1;
                   4255: }
                   4256: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
                   4257: 
                   4258: #
                   4259: #  Process the courseidput request.  Not quite sure what this means
                   4260: #  at the system level sense.  It appears a gdbm file in the 
                   4261: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
                   4262: #  a set of entries made in that database.
                   4263: #
                   4264: # Parameters:
                   4265: #   $cmd      - The command keyword that initiated this request.
                   4266: #   $tail     - Tail of the command.  In this case consists of a colon
                   4267: #               separated list contaning the domain to apply this to and
                   4268: #               an ampersand separated list of keyword=value pairs.
1.272     raeburn  4269: #               Each value is a colon separated list that includes:  
                   4270: #               description, institutional code and course owner.
                   4271: #               For backward compatibility with versions included
                   4272: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
                   4273: #               code and/or course owner are preserved from the existing 
                   4274: #               record when writing a new record in response to 1.1 or 
                   4275: #               1.2 implementations of lonnet::flushcourselogs().   
                   4276: #                      
1.234     foxr     4277: #   $client   - Socket open on the client.
                   4278: # Returns:
                   4279: #   1    - indicating that processing should continue
                   4280: #
                   4281: # Side effects:
                   4282: #   reply is written to the client.
                   4283: #
                   4284: sub put_course_id_handler {
                   4285:     my ($cmd, $tail, $client) = @_;
                   4286: 
                   4287: 
                   4288:     my $userinput = "$cmd:$tail";
                   4289: 
1.266     raeburn  4290:     my ($udom, $what) = split(/:/, $tail,2);
1.234     foxr     4291:     chomp($what);
                   4292:     my $now=time;
                   4293:     my @pairs=split(/\&/,$what);
                   4294: 
                   4295:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4296:     if ($hashref) {
                   4297: 	foreach my $pair (@pairs) {
1.271     raeburn  4298:             my ($key,$courseinfo) = split(/=/,$pair,2);
                   4299:             $courseinfo =~ s/=/:/g;
1.384     raeburn  4300:             if (defined($hashref->{$key})) {
                   4301:                 my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
                   4302:                 if (ref($value) eq 'HASH') {
                   4303:                     my @items = ('description','inst_code','owner','type');
                   4304:                     my @new_items = split(/:/,$courseinfo,-1);
                   4305:                     my %storehash; 
                   4306:                     for (my $i=0; $i<@new_items; $i++) {
1.391     raeburn  4307:                         $storehash{$items[$i]} = &unescape($new_items[$i]);
1.384     raeburn  4308:                     }
                   4309:                     $hashref->{$key} = 
                   4310:                         &Apache::lonnet::freeze_escape(\%storehash);
                   4311:                     my $unesc_key = &unescape($key);
                   4312:                     $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4313:                     next;
1.383     raeburn  4314:                 }
1.384     raeburn  4315:             }
                   4316:             my @current_items = split(/:/,$hashref->{$key},-1);
                   4317:             shift(@current_items); # remove description
                   4318:             pop(@current_items);   # remove last access
                   4319:             my $numcurrent = scalar(@current_items);
                   4320:             if ($numcurrent > 3) {
                   4321:                 $numcurrent = 3;
                   4322:             }
                   4323:             my @new_items = split(/:/,$courseinfo,-1);
                   4324:             my $numnew = scalar(@new_items);
                   4325:             if ($numcurrent > 0) {
                   4326:                 if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2 
                   4327:                     for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
                   4328:                         $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
1.333     raeburn  4329:                     }
1.272     raeburn  4330:                 }
                   4331:             }
1.384     raeburn  4332:             $hashref->{$key}=$courseinfo.':'.$now;
1.234     foxr     4333: 	}
1.311     albertel 4334: 	if (&untie_domain_hash($hashref)) {
1.253     foxr     4335: 	    &Reply( $client, "ok\n", $userinput);
1.234     foxr     4336: 	} else {
1.253     foxr     4337: 	    &Failure($client, "error: ".($!+0)
1.234     foxr     4338: 		     ." untie(GDBM) Failed ".
                   4339: 		     "while attempting courseidput\n", $userinput);
                   4340: 	}
                   4341:     } else {
1.253     foxr     4342: 	&Failure($client, "error: ".($!+0)
1.234     foxr     4343: 		 ." tie(GDBM) Failed ".
                   4344: 		 "while attempting courseidput\n", $userinput);
                   4345:     }
                   4346: 
                   4347:     return 1;
                   4348: }
                   4349: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
                   4350: 
1.383     raeburn  4351: sub put_course_id_hash_handler {
                   4352:     my ($cmd, $tail, $client) = @_;
                   4353:     my $userinput = "$cmd:$tail";
1.384     raeburn  4354:     my ($udom,$mode,$what) = split(/:/, $tail,3);
1.383     raeburn  4355:     chomp($what);
                   4356:     my $now=time;
                   4357:     my @pairs=split(/\&/,$what);
1.384     raeburn  4358:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
1.383     raeburn  4359:     if ($hashref) {
                   4360:         foreach my $pair (@pairs) {
                   4361:             my ($key,$value)=split(/=/,$pair);
1.384     raeburn  4362:             my $unesc_key = &unescape($key);
                   4363:             if ($mode ne 'timeonly') {
                   4364:                 if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
                   4365:                     my $curritems = &Apache::lonnet::thaw_unescape($key); 
                   4366:                     if (ref($curritems) ne 'HASH') {
                   4367:                         my @current_items = split(/:/,$hashref->{$key},-1);
                   4368:                         my $lasttime = pop(@current_items);
                   4369:                         $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
                   4370:                     } else {
                   4371:                         $hashref->{&escape('lasttime:'.$unesc_key)} = '';
                   4372:                     }
                   4373:                 } 
                   4374:                 $hashref->{$key} = $value;
                   4375:             }
                   4376:             if ($mode ne 'notime') {
                   4377:                 $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4378:             }
1.383     raeburn  4379:         }
                   4380:         if (&untie_domain_hash($hashref)) {
                   4381:             &Reply($client, "ok\n", $userinput);
                   4382:         } else {
                   4383:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4384:                      "while attempting courseidputhash\n", $userinput);
                   4385:         }
                   4386:     } else {
                   4387:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4388:                   "while attempting courseidputhash\n", $userinput);
                   4389:     }
                   4390:     return 1;
                   4391: }
                   4392: &register_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
                   4393: 
1.234     foxr     4394: #  Retrieves the value of a course id resource keyword pattern
                   4395: #  defined since a starting date.  Both the starting date and the
                   4396: #  keyword pattern are optional.  If the starting date is not supplied it
                   4397: #  is treated as the beginning of time.  If the pattern is not found,
                   4398: #  it is treatred as "." matching everything.
                   4399: #
                   4400: #  Parameters:
                   4401: #     $cmd     - Command keyword that resulted in us being dispatched.
                   4402: #     $tail    - The remainder of the command that, in this case, consists
                   4403: #                of a colon separated list of:
                   4404: #                 domain   - The domain in which the course database is 
                   4405: #                            defined.
                   4406: #                 since    - Optional parameter describing the minimum
                   4407: #                            time of definition(?) of the resources that
                   4408: #                            will match the dump.
                   4409: #                 description - regular expression that is used to filter
                   4410: #                            the dump.  Only keywords matching this regexp
                   4411: #                            will be used.
1.272     raeburn  4412: #                 institutional code - optional supplied code to filter 
                   4413: #                            the dump. Only courses with an institutional code 
                   4414: #                            that match the supplied code will be returned.
1.336     raeburn  4415: #                 owner    - optional supplied username and domain of owner to
                   4416: #                            filter the dump.  Only courses for which the course
                   4417: #                            owner matches the supplied username and/or domain
                   4418: #                            will be returned. Pre-2.2.0 legacy entries from 
                   4419: #                            nohist_courseiddump will only contain usernames.
1.384     raeburn  4420: #                 type     - optional parameter for selection 
1.418     raeburn  4421: #                 regexp_ok - if 1 or -1 allow the supplied institutional code
                   4422: #                            filter to behave as a regular expression:
                   4423: #	                      1 will not exclude the course if the instcode matches the RE 
                   4424: #                            -1 will exclude the course if the instcode matches the RE
1.384     raeburn  4425: #                 rtn_as_hash - whether to return the information available for
                   4426: #                            each matched item as a frozen hash of all 
                   4427: #                            key, value pairs in the item's hash, or as a 
                   4428: #                            colon-separated list of (in order) description,
                   4429: #                            institutional code, and course owner.
1.404     raeburn  4430: #                 selfenrollonly - filter by courses allowing self-enrollment  
                   4431: #                                  now or in the future (selfenrollonly = 1).
                   4432: #                 catfilter - filter by course category, assigned to a course 
                   4433: #                             using manually defined categories (i.e., not
1.407     raeburn  4434: #                             self-cataloging based on on institutional code).   
1.404     raeburn  4435: #                 showhidden - include course in results even if course  
1.407     raeburn  4436: #                              was set to be excluded from course catalog (DC only).
1.404     raeburn  4437: #                 caller -  if set to 'coursecatalog', courses set to be hidden
                   4438: #                           from course catalog will be excluded from results (unless
                   4439: #                           overridden by "showhidden".
1.427     raeburn  4440: #                 cloner - escaped username:domain of course cloner (if picking course to
1.419     raeburn  4441: #                          clone).
                   4442: #                 cc_clone_list - escaped comma separated list of courses for which 
                   4443: #                                 course cloner has active CC role (and so can clone
                   4444: #                                 automatically).
1.427     raeburn  4445: #                 cloneonly - filter by courses for which cloner has rights to clone.
                   4446: #                 createdbefore - include courses for which creation date preceeded this date.
                   4447: #                 createdafter - include courses for which creation date followed this date.
                   4448: #                 creationcontext - include courses created in specified context 
1.404     raeburn  4449: #
1.445     raeburn  4450: #                 domcloner - flag to indicate if user can create CCs in course's domain.
1.505     raeburn  4451: #                             If so, ability to clone course is automatic.
                   4452: #                 hasuniquecode - filter by courses for which a six character unique code has 
                   4453: #                                 been set.
1.445     raeburn  4454: #
1.234     foxr     4455: #     $client  - The socket open on the client.
                   4456: # Returns:
                   4457: #    1     - Continue processing.
                   4458: # Side Effects:
                   4459: #   a reply is written to $client.
                   4460: sub dump_course_id_handler {
                   4461:     my ($cmd, $tail, $client) = @_;
1.494     droeschl 4462: 
                   4463:     my $res = LONCAPA::Lond::dump_course_id_handler($tail);
                   4464:     if ($res =~ /^error:/) {
                   4465:         Failure($client, \$res, "$cmd:$tail");
                   4466:     } else {
                   4467:         Reply($client, \$res, "$cmd:$tail");
                   4468:     }
                   4469: 
                   4470:     return 1;  
                   4471: 
                   4472:     #TODO remove
1.234     foxr     4473:     my $userinput = "$cmd:$tail";
                   4474: 
1.333     raeburn  4475:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
1.404     raeburn  4476:         $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
1.427     raeburn  4477:         $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
1.505     raeburn  4478:         $creationcontext,$domcloner,$hasuniquecode) =split(/:/,$tail);
1.397     raeburn  4479:     my $now = time;
1.419     raeburn  4480:     my ($cloneruname,$clonerudom,%cc_clone);
1.234     foxr     4481:     if (defined($description)) {
                   4482: 	$description=&unescape($description);
                   4483:     } else {
                   4484: 	$description='.';
                   4485:     }
1.266     raeburn  4486:     if (defined($instcodefilter)) {
                   4487:         $instcodefilter=&unescape($instcodefilter);
                   4488:     } else {
                   4489:         $instcodefilter='.';
                   4490:     }
1.336     raeburn  4491:     my ($ownerunamefilter,$ownerdomfilter);
1.266     raeburn  4492:     if (defined($ownerfilter)) {
                   4493:         $ownerfilter=&unescape($ownerfilter);
1.336     raeburn  4494:         if ($ownerfilter ne '.' && defined($ownerfilter)) {
                   4495:             if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
                   4496:                  $ownerunamefilter = $1;
                   4497:                  $ownerdomfilter = $2;
                   4498:             } else {
                   4499:                 $ownerunamefilter = $ownerfilter;
                   4500:                 $ownerdomfilter = '';
                   4501:             }
                   4502:         }
1.266     raeburn  4503:     } else {
                   4504:         $ownerfilter='.';
                   4505:     }
1.336     raeburn  4506: 
1.282     raeburn  4507:     if (defined($coursefilter)) {
                   4508:         $coursefilter=&unescape($coursefilter);
                   4509:     } else {
                   4510:         $coursefilter='.';
                   4511:     }
1.333     raeburn  4512:     if (defined($typefilter)) {
                   4513:         $typefilter=&unescape($typefilter);
                   4514:     } else {
                   4515:         $typefilter='.';
                   4516:     }
1.344     raeburn  4517:     if (defined($regexp_ok)) {
                   4518:         $regexp_ok=&unescape($regexp_ok);
                   4519:     }
1.401     raeburn  4520:     if (defined($catfilter)) {
                   4521:         $catfilter=&unescape($catfilter);
                   4522:     }
1.419     raeburn  4523:     if (defined($cloner)) {
                   4524:         $cloner = &unescape($cloner);
                   4525:         ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/); 
                   4526:     }
                   4527:     if (defined($cc_clone_list)) {
                   4528:         $cc_clone_list = &unescape($cc_clone_list);
                   4529:         my @cc_cloners = split('&',$cc_clone_list);
                   4530:         foreach my $cid (@cc_cloners) {
                   4531:             my ($clonedom,$clonenum) = split(':',$cid);
                   4532:             next if ($clonedom ne $udom); 
                   4533:             $cc_clone{$clonedom.'_'.$clonenum} = 1;
                   4534:         } 
                   4535:     }
1.431     raeburn  4536:     if ($createdbefore ne '') {
1.427     raeburn  4537:         $createdbefore = &unescape($createdbefore);
                   4538:     } else {
                   4539:        $createdbefore = 0;
                   4540:     }
1.431     raeburn  4541:     if ($createdafter ne '') {
1.427     raeburn  4542:         $createdafter = &unescape($createdafter);
                   4543:     } else {
                   4544:         $createdafter = 0;
                   4545:     }
1.431     raeburn  4546:     if ($creationcontext ne '') {
1.427     raeburn  4547:         $creationcontext = &unescape($creationcontext);
                   4548:     } else {
                   4549:         $creationcontext = '.';
                   4550:     }
1.505     raeburn  4551:     unless ($hasuniquecode) {
                   4552:         $hasuniquecode = '.';
                   4553:     }
1.384     raeburn  4554:     my $unpack = 1;
1.485     raeburn  4555:     if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' && 
1.384     raeburn  4556:         $typefilter eq '.') {
                   4557:         $unpack = 0;
                   4558:     }
                   4559:     if (!defined($since)) { $since=0; }
1.234     foxr     4560:     my $qresult='';
                   4561:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4562:     if ($hashref) {
1.384     raeburn  4563: 	while (my ($key,$value) = each(%$hashref)) {
1.397     raeburn  4564:             my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
1.427     raeburn  4565:                 %unesc_val,$selfenroll_end,$selfenroll_types,$created,
                   4566:                 $context);
1.384     raeburn  4567:             $unesc_key = &unescape($key);
                   4568:             if ($unesc_key =~ /^lasttime:/) {
                   4569:                 next;
                   4570:             } else {
                   4571:                 $lasttime_key = &escape('lasttime:'.$unesc_key);
                   4572:             }
                   4573:             if ($hashref->{$lasttime_key} ne '') {
                   4574:                 $lasttime = $hashref->{$lasttime_key};
                   4575:                 next if ($lasttime<$since);
                   4576:             }
1.419     raeburn  4577:             my ($canclone,$valchange);
1.384     raeburn  4578:             my $items = &Apache::lonnet::thaw_unescape($value);
                   4579:             if (ref($items) eq 'HASH') {
1.429     raeburn  4580:                 if ($hashref->{$lasttime_key} eq '') {
1.430     raeburn  4581:                     next if ($since > 1);
1.429     raeburn  4582:                 }
1.384     raeburn  4583:                 $is_hash =  1;
1.445     raeburn  4584:                 if ($domcloner) {
                   4585:                     $canclone = 1;
                   4586:                 } elsif (defined($clonerudom)) {
1.419     raeburn  4587:                     if ($items->{'cloners'}) {
                   4588:                         my @cloneable = split(',',$items->{'cloners'});
                   4589:                         if (@cloneable) {
                   4590:                             if (grep(/^\*$/,@cloneable))  {
                   4591:                                 $canclone = 1;
                   4592:                             } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
                   4593:                                 $canclone = 1;
                   4594:                             } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
                   4595:                                 $canclone = 1;
                   4596:                             }
                   4597:                         }
                   4598:                         unless ($canclone) {
                   4599:                             if ($cloneruname ne '' && $clonerudom ne '') {
                   4600:                                 if ($cc_clone{$unesc_key}) {
                   4601:                                     $canclone = 1;
                   4602:                                     $items->{'cloners'} .= ','.$cloneruname.':'.
                   4603:                                                            $clonerudom;
                   4604:                                     $valchange = 1;
                   4605:                                 }
                   4606:                             }
                   4607:                         }
                   4608:                     } elsif (defined($cloneruname)) {
                   4609:                         if ($cc_clone{$unesc_key}) {
                   4610:                             $canclone = 1;
                   4611:                             $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4612:                             $valchange = 1;
                   4613:                         }
1.437     raeburn  4614:                         unless ($canclone) {
                   4615:                             if ($items->{'owner'} =~ /:/) {
                   4616:                                 if ($items->{'owner'} eq $cloner) {
                   4617:                                     $canclone = 1;
                   4618:                                 }
1.444     raeburn  4619:                             } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
1.437     raeburn  4620:                                 $canclone = 1;
                   4621:                             }
                   4622:                             if ($canclone) {
                   4623:                                 $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4624:                                 $valchange = 1;
                   4625:                             }
                   4626:                         }
1.419     raeburn  4627:                     }
                   4628:                 }
1.384     raeburn  4629:                 if ($unpack || !$rtn_as_hash) {
                   4630:                     $unesc_val{'descr'} = $items->{'description'};
                   4631:                     $unesc_val{'inst_code'} = $items->{'inst_code'};
                   4632:                     $unesc_val{'owner'} = $items->{'owner'};
                   4633:                     $unesc_val{'type'} = $items->{'type'};
1.419     raeburn  4634:                     $unesc_val{'cloners'} = $items->{'cloners'};
1.427     raeburn  4635:                     $unesc_val{'created'} = $items->{'created'};
                   4636:                     $unesc_val{'context'} = $items->{'context'};
1.404     raeburn  4637:                 }
                   4638:                 $selfenroll_types = $items->{'selfenroll_types'};
                   4639:                 $selfenroll_end = $items->{'selfenroll_end_date'};
1.427     raeburn  4640:                 $created = $items->{'created'};
                   4641:                 $context = $items->{'context'};
1.505     raeburn  4642:                 if ($hasuniquecode ne '.') {
                   4643:                     next unless ($items->{'uniquecode'});
                   4644:                 }
1.404     raeburn  4645:                 if ($selfenrollonly) {
                   4646:                     next if (!$selfenroll_types);
                   4647:                     if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
                   4648:                         next;
1.397     raeburn  4649:                     }
1.404     raeburn  4650:                 }
1.427     raeburn  4651:                 if ($creationcontext ne '.') {
                   4652:                     next if (($context ne '') && ($context ne $creationcontext));  
                   4653:                 }
                   4654:                 if ($createdbefore > 0) {
                   4655:                     next if (($created eq '') || ($created > $createdbefore));   
                   4656:                 }
                   4657:                 if ($createdafter > 0) {
                   4658:                     next if (($created eq '') || ($created <= $createdafter)); 
                   4659:                 }
1.404     raeburn  4660:                 if ($catfilter ne '') {
1.406     raeburn  4661:                     next if ($items->{'categories'} eq '');
                   4662:                     my @categories = split('&',$items->{'categories'}); 
1.407     raeburn  4663:                     next if (@categories == 0);
                   4664:                     my @subcats = split('&',$catfilter);
                   4665:                     my $matchcat = 0;
                   4666:                     foreach my $cat (@categories) {
                   4667:                         if (grep(/^\Q$cat\E$/,@subcats)) {
                   4668:                             $matchcat = 1;
                   4669:                             last;
                   4670:                         }
                   4671:                     }
                   4672:                     next if (!$matchcat);
1.404     raeburn  4673:                 }
                   4674:                 if ($caller eq 'coursecatalog') {
1.405     raeburn  4675:                     if ($items->{'hidefromcat'} eq 'yes') {
                   4676:                         next if !$showhidden;
1.401     raeburn  4677:                     }
1.384     raeburn  4678:                 }
1.383     raeburn  4679:             } else {
1.401     raeburn  4680:                 next if ($catfilter ne '');
1.419     raeburn  4681:                 next if ($selfenrollonly);
1.427     raeburn  4682:                 next if ($createdbefore || $createdafter);
                   4683:                 next if ($creationcontext ne '.');
1.419     raeburn  4684:                 if ((defined($clonerudom)) && (defined($cloneruname)))  {
                   4685:                     if ($cc_clone{$unesc_key}) {
                   4686:                         $canclone = 1;
                   4687:                         $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
                   4688:                     }
                   4689:                 }
1.384     raeburn  4690:                 $is_hash =  0;
1.388     raeburn  4691:                 my @courseitems = split(/:/,$value);
1.403     raeburn  4692:                 $lasttime = pop(@courseitems);
1.402     raeburn  4693:                 if ($hashref->{$lasttime_key} eq '') {
                   4694:                     next if ($lasttime<$since);
                   4695:                 }
1.384     raeburn  4696: 	        ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
1.383     raeburn  4697:             }
1.419     raeburn  4698:             if ($cloneonly) {
                   4699:                next unless ($canclone);
                   4700:             }
1.266     raeburn  4701:             my $match = 1;
1.384     raeburn  4702: 	    if ($description ne '.') {
                   4703:                 if (!$is_hash) {
                   4704:                     $unesc_val{'descr'} = &unescape($val{'descr'});
                   4705:                 }
                   4706:                 if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
1.266     raeburn  4707:                     $match = 0;
1.384     raeburn  4708:                 }
1.266     raeburn  4709:             }
1.384     raeburn  4710:             if ($instcodefilter ne '.') {
                   4711:                 if (!$is_hash) {
                   4712:                     $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
                   4713:                 }
1.418     raeburn  4714:                 if ($regexp_ok == 1) {
1.384     raeburn  4715:                     if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
1.344     raeburn  4716:                         $match = 0;
                   4717:                     }
1.418     raeburn  4718:                 } elsif ($regexp_ok == -1) {
                   4719:                     if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
                   4720:                         $match = 0;
                   4721:                     }
1.344     raeburn  4722:                 } else {
1.384     raeburn  4723:                     if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
1.344     raeburn  4724:                         $match = 0;
                   4725:                     }
1.266     raeburn  4726:                 }
1.234     foxr     4727: 	    }
1.384     raeburn  4728:             if ($ownerfilter ne '.') {
                   4729:                 if (!$is_hash) {
                   4730:                     $unesc_val{'owner'} = &unescape($val{'owner'});
                   4731:                 }
1.336     raeburn  4732:                 if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
1.384     raeburn  4733:                     if ($unesc_val{'owner'} =~ /:/) {
                   4734:                         if (eval{$unesc_val{'owner'} !~ 
                   4735:                              /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
1.336     raeburn  4736:                             $match = 0;
                   4737:                         } 
                   4738:                     } else {
1.384     raeburn  4739:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4740:                             $match = 0;
                   4741:                         }
                   4742:                     }
                   4743:                 } elsif ($ownerunamefilter ne '') {
1.384     raeburn  4744:                     if ($unesc_val{'owner'} =~ /:/) {
                   4745:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
1.336     raeburn  4746:                              $match = 0;
                   4747:                         }
                   4748:                     } else {
1.384     raeburn  4749:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4750:                             $match = 0;
                   4751:                         }
                   4752:                     }
                   4753:                 } elsif ($ownerdomfilter ne '') {
1.384     raeburn  4754:                     if ($unesc_val{'owner'} =~ /:/) {
                   4755:                         if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
1.336     raeburn  4756:                              $match = 0;
                   4757:                         }
                   4758:                     } else {
                   4759:                         if ($ownerdomfilter ne $udom) {
                   4760:                             $match = 0;
                   4761:                         }
                   4762:                     }
1.266     raeburn  4763:                 }
                   4764:             }
1.384     raeburn  4765:             if ($coursefilter ne '.') {
                   4766:                 if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
1.282     raeburn  4767:                     $match = 0;
                   4768:                 }
                   4769:             }
1.384     raeburn  4770:             if ($typefilter ne '.') {
                   4771:                 if (!$is_hash) {
                   4772:                     $unesc_val{'type'} = &unescape($val{'type'});
                   4773:                 }
                   4774:                 if ($unesc_val{'type'} eq '') {
1.333     raeburn  4775:                     if ($typefilter ne 'Course') {
                   4776:                         $match = 0;
                   4777:                     }
1.383     raeburn  4778:                 } else {
1.384     raeburn  4779:                     if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
1.333     raeburn  4780:                         $match = 0;
                   4781:                     }
                   4782:                 }
                   4783:             }
1.266     raeburn  4784:             if ($match == 1) {
1.384     raeburn  4785:                 if ($rtn_as_hash) {
                   4786:                     if ($is_hash) {
1.419     raeburn  4787:                         if ($valchange) {
                   4788:                             my $newvalue = &Apache::lonnet::freeze_escape($items);
                   4789:                             $qresult.=$key.'='.$newvalue.'&';
                   4790:                         } else {
                   4791:                             $qresult.=$key.'='.$value.'&';
                   4792:                         }
1.384     raeburn  4793:                     } else {
1.388     raeburn  4794:                         my %rtnhash = ( 'description' => &unescape($val{'descr'}),
                   4795:                                         'inst_code' => &unescape($val{'inst_code'}),
                   4796:                                         'owner'     => &unescape($val{'owner'}),
                   4797:                                         'type'      => &unescape($val{'type'}),
1.419     raeburn  4798:                                         'cloners'   => &unescape($val{'cloners'}),
1.384     raeburn  4799:                                       );
                   4800:                         my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
                   4801:                         $qresult.=$key.'='.$items.'&';
                   4802:                     }
1.383     raeburn  4803:                 } else {
1.384     raeburn  4804:                     if ($is_hash) {
                   4805:                         $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
                   4806:                                     &escape($unesc_val{'inst_code'}).':'.
                   4807:                                     &escape($unesc_val{'owner'}).'&';
                   4808:                     } else {
                   4809:                         $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
                   4810:                                     ':'.$val{'owner'}.'&';
                   4811:                     }
1.383     raeburn  4812:                 }
1.266     raeburn  4813:             }
1.234     foxr     4814: 	}
1.311     albertel 4815: 	if (&untie_domain_hash($hashref)) {
1.234     foxr     4816: 	    chop($qresult);
1.387     albertel 4817: 	    &Reply($client, \$qresult, $userinput);
1.234     foxr     4818: 	} else {
                   4819: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4820: 		    "while attempting courseiddump\n", $userinput);
                   4821: 	}
                   4822:     } else {
                   4823: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4824: 		"while attempting courseiddump\n", $userinput);
                   4825:     }
                   4826:     return 1;
                   4827: }
                   4828: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238     foxr     4829: 
1.438     raeburn  4830: sub course_lastaccess_handler {
                   4831:     my ($cmd, $tail, $client) = @_;
                   4832:     my $userinput = "$cmd:$tail";
                   4833:     my ($cdom,$cnum) = split(':',$tail); 
                   4834:     my (%lastaccess,$qresult);
                   4835:     my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
                   4836:     if ($hashref) {
                   4837:         while (my ($key,$value) = each(%$hashref)) {
                   4838:             my ($unesc_key,$lasttime);
                   4839:             $unesc_key = &unescape($key);
                   4840:             if ($cnum) {
                   4841:                 next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
                   4842:             }
                   4843:             if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
                   4844:                 $lastaccess{$1} = $value;
                   4845:             } else {
                   4846:                 my $items = &Apache::lonnet::thaw_unescape($value);
                   4847:                 if (ref($items) eq 'HASH') {
                   4848:                     unless ($lastaccess{$unesc_key}) {
                   4849:                         $lastaccess{$unesc_key} = '';
                   4850:                     }
                   4851:                 } else {
                   4852:                     my @courseitems = split(':',$value);
                   4853:                     $lastaccess{$unesc_key} = pop(@courseitems);
                   4854:                 }
                   4855:             }
                   4856:         }
                   4857:         foreach my $cid (sort(keys(%lastaccess))) {
                   4858:             $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&'; 
                   4859:         }
                   4860:         if (&untie_domain_hash($hashref)) {
                   4861:             if ($qresult) {
                   4862:                 chop($qresult);
                   4863:             }
                   4864:             &Reply($client, \$qresult, $userinput);
                   4865:         } else {
                   4866:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4867:                     "while attempting lastacourseaccess\n", $userinput);
                   4868:         }
                   4869:     } else {
                   4870:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4871:                 "while attempting lastcourseaccess\n", $userinput);
                   4872:     }
                   4873:     return 1;
                   4874: }
                   4875: &register_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
                   4876: 
1.561     raeburn  4877: sub course_sessions_handler {
                   4878:     my ($cmd, $tail, $client) = @_;
                   4879:     my $userinput = "$cmd:$tail";
                   4880:     my ($cdom,$cnum,$lastactivity) = split(':',$tail);
                   4881:     my $dbsuffix = '_'.$cdom.'_'.$cnum.'.db';
                   4882:     my (%sessions,$qresult);
                   4883:     my $now=time;
                   4884:     if (opendir(DIR,$perlvar{'lonIDsDir'})) {
                   4885:         my $filename;
                   4886:         while ($filename=readdir(DIR)) {
                   4887:             next if ($filename=~/^\./);
                   4888:             next if ($filename=~/^publicuser_/);
                   4889:             next if ($filename=~/^[a-f0-9]+_(linked|lti_\d+)\.id$/);
1.562   ! raeburn  4890:             if ($filename =~ /^($LONCAPA::match_username)_\d+_($LONCAPA::match_domain)_/) {
1.561     raeburn  4891:                 my ($uname,$udom) = ($1,$2);
1.562   ! raeburn  4892:                 next unless (-e "$perlvar{'lonDaemons'}/tmp/$uname$dbsuffix");
1.561     raeburn  4893:                 my $mtime = (stat("$perlvar{'lonIDsDir'}/$filename"))[9];
                   4894:                 my $since=$now-$mtime;
                   4895:                 if ($lastactivity < 0) {
                   4896:                     next if ($since <= $lastactivity);
                   4897:                 } else {
                   4898:                     next if ($since > $lastactivity);
                   4899:                 }
                   4900:                 $sessions{$uname.':'.$udom} = $mtime;
                   4901:             }
                   4902:         }
                   4903:         closedir(DIR); 
                   4904:     }
                   4905:     foreach my $user (keys(%sessions)) {
                   4906:         $qresult.=&escape($user).'='.$sessions{$user}.'&';
                   4907:     }
                   4908:     if ($qresult) {
                   4909:         chop($qresult);
                   4910:     }
                   4911:     &Reply($client, \$qresult, $userinput);
                   4912:     return 1;
                   4913: }
                   4914: &register_handler("coursesessions",\&course_sessions_handler, 0, 1, 0);
                   4915: 
1.238     foxr     4916: #
1.348     raeburn  4917: # Puts an unencrypted entry in a namespace db file at the domain level 
                   4918: #
                   4919: # Parameters:
                   4920: #    $cmd      - The command that got us here.
                   4921: #    $tail     - Tail of the command (remaining parameters).
                   4922: #    $client   - File descriptor connected to client.
                   4923: # Returns
                   4924: #     0        - Requested to exit, caller should shut down.
                   4925: #     1        - Continue processing.
                   4926: #  Side effects:
                   4927: #     reply is written to $client.
                   4928: #
                   4929: sub put_domain_handler {
                   4930:     my ($cmd,$tail,$client) = @_;
                   4931: 
                   4932:     my $userinput = "$cmd:$tail";
                   4933: 
                   4934:     my ($udom,$namespace,$what) =split(/:/,$tail,3);
                   4935:     chomp($what);
                   4936:     my @pairs=split(/\&/,$what);
                   4937:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
                   4938:                                    "P", $what);
                   4939:     if ($hashref) {
                   4940:         foreach my $pair (@pairs) {
                   4941:             my ($key,$value)=split(/=/,$pair);
                   4942:             $hashref->{$key}=$value;
                   4943:         }
                   4944:         if (&untie_domain_hash($hashref)) {
                   4945:             &Reply($client, "ok\n", $userinput);
                   4946:         } else {
                   4947:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4948:                      "while attempting putdom\n", $userinput);
                   4949:         }
                   4950:     } else {
                   4951:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4952:                   "while attempting putdom\n", $userinput);
                   4953:     }
                   4954: 
                   4955:     return 1;
                   4956: }
                   4957: &register_handler("putdom", \&put_domain_handler, 0, 1, 0);
                   4958: 
1.517     raeburn  4959: # Updates one or more entries in clickers.db file at the domain level
                   4960: #
                   4961: # Parameters:
                   4962: #    $cmd      - The command that got us here.
                   4963: #    $tail     - Tail of the command (remaining parameters).
                   4964: #                In this case a colon separated list containing:
                   4965: #                (a) the domain for which we are updating the entries,
                   4966: #                (b) the action required -- add or del -- and
                   4967: #                (c) a &-separated list of entries to add or delete.
                   4968: #    $client   - File descriptor connected to client.
                   4969: # Returns
                   4970: #     1        - Continue processing.
                   4971: #     0        - Requested to exit, caller should shut down.
                   4972: #  Side effects:
                   4973: #     reply is written to $client.
                   4974: #
                   4975: 
                   4976: 
                   4977: sub update_clickers {
                   4978:     my ($cmd, $tail, $client)  = @_;
                   4979: 
                   4980:     my $userinput = "$cmd:$tail";
                   4981:     my ($udom,$action,$what) =split(/:/,$tail,3);
                   4982:     chomp($what);
                   4983: 
                   4984:     my $hashref = &tie_domain_hash($udom, "clickers", &GDBM_WRCREAT(),
                   4985:                                  "U","$action:$what");
                   4986: 
                   4987:     if (!$hashref) {
                   4988:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4989:                   "while attempting updateclickers\n", $userinput);
                   4990:         return 1;
                   4991:     }
                   4992: 
                   4993:     my @pairs=split(/\&/,$what);
                   4994:     foreach my $pair (@pairs) {
                   4995:         my ($key,$value)=split(/=/,$pair);
                   4996:         if ($action eq 'add') {
                   4997:             if (exists($hashref->{$key})) {
                   4998:                 my @newvals = split(/,/,&unescape($value));
                   4999:                 my @currvals = split(/,/,&unescape($hashref->{$key}));
                   5000:                 my @merged = sort(keys(%{{map { $_ => 1 } (@newvals,@currvals)}}));
                   5001:                 $hashref->{$key}=&escape(join(',',@merged));
                   5002:             } else {
                   5003:                 $hashref->{$key}=$value;
                   5004:             }
                   5005:         } elsif ($action eq 'del') {
                   5006:             if (exists($hashref->{$key})) {
                   5007:                 my %current;
                   5008:                 map { $current{$_} = 1; } split(/,/,&unescape($hashref->{$key}));
                   5009:                 map { delete($current{$_}); } split(/,/,&unescape($value));
                   5010:                 if (keys(%current)) {
                   5011:                     $hashref->{$key}=&escape(join(',',sort(keys(%current))));
                   5012:                 } else {
                   5013:                     delete($hashref->{$key});
                   5014:                 }
                   5015:             }
                   5016:         }
                   5017:     }
                   5018:     if (&untie_user_hash($hashref)) {
                   5019:         &Reply( $client, "ok\n", $userinput);
                   5020:     } else {
                   5021:         &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   5022:                  "while attempting put\n",
                   5023:                  $userinput);
                   5024:     }
                   5025:     return 1;
                   5026: }
                   5027: &register_handler("updateclickers", \&update_clickers, 0, 1, 0);
                   5028: 
                   5029: 
                   5030: # Deletes one or more entries in a namespace db file at the domain level
                   5031: #
                   5032: # Parameters:
                   5033: #    $cmd      - The command that got us here.
                   5034: #    $tail     - Tail of the command (remaining parameters).
                   5035: #                In this case a colon separated list containing:
                   5036: #                (a) the domain for which we are deleting the entries,
                   5037: #                (b) &-separated list of keys to delete.  
                   5038: #    $client   - File descriptor connected to client.
                   5039: # Returns
                   5040: #     1        - Continue processing.
                   5041: #     0        - Requested to exit, caller should shut down.
                   5042: #  Side effects:
                   5043: #     reply is written to $client.
                   5044: #
                   5045: 
                   5046: sub del_domain_handler {
                   5047:     my ($cmd,$tail,$client) = @_;
                   5048: 
                   5049:     my $userinput = "$cmd:$tail";
                   5050: 
                   5051:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   5052:     chomp($what);
                   5053:     my $hashref = &tie_domain_hash($udom,$namespace,&GDBM_WRCREAT(),
                   5054:                                    "D", $what);
                   5055:     if ($hashref) {
                   5056:         my @keys=split(/\&/,$what);
                   5057:         foreach my $key (@keys) {
                   5058:             delete($hashref->{$key});
                   5059:         }
                   5060:         if (&untie_user_hash($hashref)) {
                   5061:             &Reply($client, "ok\n", $userinput);
                   5062:         } else {
                   5063:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5064:                     "while attempting deldom\n", $userinput);
                   5065:         }
                   5066:     } else {
                   5067:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5068:                  "while attempting deldom\n", $userinput);
                   5069:     }
                   5070:     return 1;
                   5071: }
                   5072: &register_handler("deldom", \&del_domain_handler, 0, 1, 0);
                   5073: 
                   5074: 
1.348     raeburn  5075: # Unencrypted get from the namespace database file at the domain level.
                   5076: # This function retrieves a keyed item from a specific named database in the
                   5077: # domain directory.
                   5078: #
                   5079: # Parameters:
                   5080: #   $cmd             - Command request keyword (get).
                   5081: #   $tail            - Tail of the command.  This is a colon separated list
                   5082: #                      consisting of the domain and the 'namespace' 
                   5083: #                      which selects the gdbm file to do the lookup in,
                   5084: #                      & separated list of keys to lookup.  Note that
                   5085: #                      the values are returned as an & separated list too.
                   5086: #   $client          - File descriptor open on the client.
                   5087: # Returns:
                   5088: #   1       - Continue processing.
                   5089: #   0       - Exit.
                   5090: #  Side effects:
                   5091: #     reply is written to $client.
                   5092: #
                   5093: 
                   5094: sub get_domain_handler {
                   5095:     my ($cmd, $tail, $client) = @_;
                   5096: 
1.461     foxr     5097: 
1.536     raeburn  5098:     my $userinput = "$cmd:$tail";
                   5099: 
                   5100:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   5101:     chomp($what);
                   5102:     if ($namespace =~ /^enc/) {
                   5103:         &Failure( $client, "refused\n", $userinput);
                   5104:     } else {
                   5105:         my @queries=split(/\&/,$what);
                   5106:         my $qresult='';
                   5107:         my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
                   5108:         if ($hashref) {
                   5109:             for (my $i=0;$i<=$#queries;$i++) {
                   5110:                 $qresult.="$hashref->{$queries[$i]}&";
                   5111:             }
                   5112:             if (&untie_domain_hash($hashref)) {
                   5113:                 $qresult=~s/\&$//;
                   5114:                 &Reply($client, \$qresult, $userinput);
                   5115:             } else {
                   5116:                 &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5117:                           "while attempting getdom\n",$userinput);
                   5118:             }
                   5119:         } else {
                   5120:             &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5121:                      "while attempting getdom\n",$userinput);
                   5122:         }
                   5123:     }
                   5124: 
                   5125:     return 1;
                   5126: }
                   5127: &register_handler("getdom", \&get_domain_handler, 0, 1, 0);
                   5128: 
                   5129: sub encrypted_get_domain_handler {
                   5130:     my ($cmd, $tail, $client) = @_;
                   5131: 
                   5132:     my $userinput = "$cmd:$tail";
1.348     raeburn  5133: 
                   5134:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   5135:     chomp($what);
                   5136:     my @queries=split(/\&/,$what);
                   5137:     my $qresult='';
                   5138:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
                   5139:     if ($hashref) {
                   5140:         for (my $i=0;$i<=$#queries;$i++) {
                   5141:             $qresult.="$hashref->{$queries[$i]}&";
                   5142:         }
                   5143:         if (&untie_domain_hash($hashref)) {
                   5144:             $qresult=~s/\&$//;
1.536     raeburn  5145:             if ($cipher) {
                   5146:                 my $cmdlength=length($qresult);
                   5147:                 $qresult.="         ";
                   5148:                 my $encqresult='';
                   5149:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   5150:                     $encqresult.= unpack("H16",
                   5151:                                          $cipher->encrypt(substr($qresult,
                   5152:                                                                  $encidx,
                   5153:                                                                  8)));
                   5154:                 }
                   5155:                 &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   5156:             } else {
                   5157:                 &Failure( $client, "error:no_key\n", $userinput);
                   5158:             }
1.348     raeburn  5159:         } else {
                   5160:             &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
1.536     raeburn  5161:                       "while attempting egetdom\n",$userinput);
1.348     raeburn  5162:         }
                   5163:     } else {
                   5164:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
1.536     raeburn  5165:                  "while attempting egetdom\n",$userinput);
1.348     raeburn  5166:     }
                   5167:     return 1;
                   5168: }
1.536     raeburn  5169: &register_handler("egetdom", \&encrypted_get_domain_handler, 1, 1, 0);
1.348     raeburn  5170: 
1.420     raeburn  5171: #
1.238     foxr     5172: #  Puts an id to a domains id database. 
                   5173: #
                   5174: #  Parameters:
                   5175: #   $cmd     - The command that triggered us.
                   5176: #   $tail    - Remainder of the request other than the command. This is a 
                   5177: #              colon separated list containing:
                   5178: #              $domain  - The domain for which we are writing the id.
                   5179: #              $pairs  - The id info to write... this is and & separated list
                   5180: #                        of keyword=value.
                   5181: #   $client  - Socket open on the client.
                   5182: #  Returns:
                   5183: #    1   - Continue processing.
                   5184: #  Side effects:
                   5185: #     reply is written to $client.
                   5186: #
                   5187: sub put_id_handler {
                   5188:     my ($cmd,$tail,$client) = @_;
                   5189: 
                   5190: 
                   5191:     my $userinput = "$cmd:$tail";
                   5192: 
                   5193:     my ($udom,$what)=split(/:/,$tail);
                   5194:     chomp($what);
                   5195:     my @pairs=split(/\&/,$what);
                   5196:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   5197: 				   "P", $what);
                   5198:     if ($hashref) {
                   5199: 	foreach my $pair (@pairs) {
                   5200: 	    my ($key,$value)=split(/=/,$pair);
                   5201: 	    $hashref->{$key}=$value;
                   5202: 	}
1.311     albertel 5203: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     5204: 	    &Reply($client, "ok\n", $userinput);
                   5205: 	} else {
                   5206: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5207: 		     "while attempting idput\n", $userinput);
                   5208: 	}
                   5209:     } else {
                   5210: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5211: 		  "while attempting idput\n", $userinput);
                   5212:     }
                   5213: 
                   5214:     return 1;
                   5215: }
1.263     albertel 5216: &register_handler("idput", \&put_id_handler, 0, 1, 0);
1.238     foxr     5217: 
                   5218: #
                   5219: #  Retrieves a set of id values from the id database.
                   5220: #  Returns an & separated list of results, one for each requested id to the
                   5221: #  client.
                   5222: #
                   5223: # Parameters:
                   5224: #   $cmd       - Command keyword that caused us to be dispatched.
                   5225: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5226: #               domain - the domain whose id table we dump
                   5227: #               ids      Consists of an & separated list of
                   5228: #                        id keywords whose values will be fetched.
                   5229: #                        nonexisting keywords will have an empty value.
                   5230: #   $client    - Socket open on the client.
                   5231: #
                   5232: # Returns:
                   5233: #    1 - indicating processing should continue.
                   5234: # Side effects:
                   5235: #   An & separated list of results is written to $client.
                   5236: #
                   5237: sub get_id_handler {
                   5238:     my ($cmd, $tail, $client) = @_;
                   5239: 
                   5240:     
                   5241:     my $userinput = "$client:$tail";
                   5242:     
                   5243:     my ($udom,$what)=split(/:/,$tail);
                   5244:     chomp($what);
                   5245:     my @queries=split(/\&/,$what);
                   5246:     my $qresult='';
                   5247:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
                   5248:     if ($hashref) {
                   5249: 	for (my $i=0;$i<=$#queries;$i++) {
                   5250: 	    $qresult.="$hashref->{$queries[$i]}&";
                   5251: 	}
1.311     albertel 5252: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     5253: 	    $qresult=~s/\&$//;
1.387     albertel 5254: 	    &Reply($client, \$qresult, $userinput);
1.238     foxr     5255: 	} else {
                   5256: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5257: 		      "while attempting idget\n",$userinput);
                   5258: 	}
                   5259:     } else {
                   5260: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5261: 		 "while attempting idget\n",$userinput);
                   5262:     }
                   5263:     
                   5264:     return 1;
                   5265: }
1.263     albertel 5266: &register_handler("idget", \&get_id_handler, 0, 1, 0);
1.238     foxr     5267: 
1.501     raeburn  5268: #   Deletes one or more ids in a domain's id database.
                   5269: #
                   5270: #   Parameters:
                   5271: #       $cmd                  - Command keyword (iddel).
                   5272: #       $tail                 - Command tail.  In this case a colon
                   5273: #                               separated list containing:
                   5274: #                               The domain for which we are deleting the id(s).
                   5275: #                               &-separated list of id(s) to delete.
                   5276: #       $client               - File open on client socket.
                   5277: # Returns:
                   5278: #     1   - Continue processing
                   5279: #     0   - Exit server.
                   5280: #     
                   5281: #
                   5282: 
                   5283: sub del_id_handler {
                   5284:     my ($cmd,$tail,$client) = @_;
                   5285: 
                   5286:     my $userinput = "$cmd:$tail";
                   5287: 
                   5288:     my ($udom,$what)=split(/:/,$tail);
                   5289:     chomp($what);
                   5290:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   5291:                                    "D", $what);
                   5292:     if ($hashref) {
                   5293:         my @keys=split(/\&/,$what);
                   5294:         foreach my $key (@keys) {
                   5295:             delete($hashref->{$key});
                   5296:         }
                   5297:         if (&untie_user_hash($hashref)) {
                   5298:             &Reply($client, "ok\n", $userinput);
                   5299:         } else {
                   5300:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5301:                     "while attempting iddel\n", $userinput);
                   5302:         }
                   5303:     } else {
                   5304:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5305:                  "while attempting iddel\n", $userinput);
                   5306:     }
                   5307:     return 1;
                   5308: }
                   5309: &register_handler("iddel", \&del_id_handler, 0, 1, 0);
                   5310: 
1.238     foxr     5311: #
1.299     raeburn  5312: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
                   5313: #
                   5314: # Parameters
                   5315: #   $cmd       - Command keyword that caused us to be dispatched.
                   5316: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5317: #               domain - the domain whose dcmail we are recording
                   5318: #               email    Consists of key=value pair 
                   5319: #                        where key is unique msgid
                   5320: #                        and value is message (in XML)
                   5321: #   $client    - Socket open on the client.
                   5322: #
                   5323: # Returns:
                   5324: #    1 - indicating processing should continue.
                   5325: # Side effects
                   5326: #     reply is written to $client.
                   5327: #
                   5328: sub put_dcmail_handler {
                   5329:     my ($cmd,$tail,$client) = @_;
                   5330:     my $userinput = "$cmd:$tail";
1.463     foxr     5331: 
                   5332: 
1.299     raeburn  5333:     my ($udom,$what)=split(/:/,$tail);
                   5334:     chomp($what);
                   5335:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5336:     if ($hashref) {
                   5337:         my ($key,$value)=split(/=/,$what);
                   5338:         $hashref->{$key}=$value;
                   5339:     }
1.311     albertel 5340:     if (&untie_domain_hash($hashref)) {
1.299     raeburn  5341:         &Reply($client, "ok\n", $userinput);
                   5342:     } else {
                   5343:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5344:                  "while attempting dcmailput\n", $userinput);
                   5345:     }
                   5346:     return 1;
                   5347: }
                   5348: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
                   5349: 
                   5350: #
                   5351: # Retrieves broadcast e-mail from nohist_dcmail database
                   5352: # Returns to client an & separated list of key=value pairs,
                   5353: # where key is msgid and value is message information.
                   5354: #
                   5355: # Parameters
                   5356: #   $cmd       - Command keyword that caused us to be dispatched.
                   5357: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5358: #               domain - the domain whose dcmail table we dump
                   5359: #               startfilter - beginning of time window 
                   5360: #               endfilter - end of time window
                   5361: #               sendersfilter - & separated list of username:domain 
                   5362: #                 for senders to search for.
                   5363: #   $client    - Socket open on the client.
                   5364: #
                   5365: # Returns:
                   5366: #    1 - indicating processing should continue.
                   5367: # Side effects
                   5368: #     reply (& separated list of msgid=messageinfo pairs) is 
                   5369: #     written to $client.
                   5370: #
                   5371: sub dump_dcmail_handler {
                   5372:     my ($cmd, $tail, $client) = @_;
                   5373:                                                                                 
                   5374:     my $userinput = "$cmd:$tail";
                   5375:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
                   5376:     chomp($sendersfilter);
                   5377:     my @senders = ();
                   5378:     if (defined($startfilter)) {
                   5379:         $startfilter=&unescape($startfilter);
                   5380:     } else {
                   5381:         $startfilter='.';
                   5382:     }
                   5383:     if (defined($endfilter)) {
                   5384:         $endfilter=&unescape($endfilter);
                   5385:     } else {
                   5386:         $endfilter='.';
                   5387:     }
                   5388:     if (defined($sendersfilter)) {
                   5389:         $sendersfilter=&unescape($sendersfilter);
1.300     albertel 5390: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
1.299     raeburn  5391:     }
                   5392: 
                   5393:     my $qresult='';
                   5394:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5395:     if ($hashref) {
                   5396:         while (my ($key,$value) = each(%$hashref)) {
                   5397:             my $match = 1;
1.303     albertel 5398:             my ($timestamp,$subj,$uname,$udom) = 
                   5399: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
1.299     raeburn  5400:             $subj = &unescape($subj);
                   5401:             unless ($startfilter eq '.' || !defined($startfilter)) {
                   5402:                 if ($timestamp < $startfilter) {
                   5403:                     $match = 0;
                   5404:                 }
                   5405:             }
                   5406:             unless ($endfilter eq '.' || !defined($endfilter)) {
                   5407:                 if ($timestamp > $endfilter) {
                   5408:                     $match = 0;
                   5409:                 }
                   5410:             }
                   5411:             unless (@senders < 1) {
                   5412:                 unless (grep/^$uname:$udom$/,@senders) {
                   5413:                     $match = 0;
                   5414:                 }
                   5415:             }
                   5416:             if ($match == 1) {
                   5417:                 $qresult.=$key.'='.$value.'&';
                   5418:             }
                   5419:         }
1.311     albertel 5420:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5421:             chop($qresult);
1.387     albertel 5422:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5423:         } else {
                   5424:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5425:                     "while attempting dcmaildump\n", $userinput);
                   5426:         }
                   5427:     } else {
                   5428:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5429:                 "while attempting dcmaildump\n", $userinput);
                   5430:     }
                   5431:     return 1;
                   5432: }
                   5433: 
                   5434: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
                   5435: 
                   5436: #
                   5437: # Puts domain roles in nohist_domainroles database
                   5438: #
                   5439: # Parameters
                   5440: #   $cmd       - Command keyword that caused us to be dispatched.
                   5441: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5442: #               domain - the domain whose roles we are recording  
                   5443: #               role -   Consists of key=value pair
                   5444: #                        where key is unique role
                   5445: #                        and value is start/end date information
                   5446: #   $client    - Socket open on the client.
                   5447: #
                   5448: # Returns:
                   5449: #    1 - indicating processing should continue.
                   5450: # Side effects
                   5451: #     reply is written to $client.
                   5452: #
                   5453: 
                   5454: sub put_domainroles_handler {
                   5455:     my ($cmd,$tail,$client) = @_;
                   5456: 
                   5457:     my $userinput = "$cmd:$tail";
                   5458:     my ($udom,$what)=split(/:/,$tail);
                   5459:     chomp($what);
                   5460:     my @pairs=split(/\&/,$what);
                   5461:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5462:     if ($hashref) {
                   5463:         foreach my $pair (@pairs) {
                   5464:             my ($key,$value)=split(/=/,$pair);
                   5465:             $hashref->{$key}=$value;
                   5466:         }
1.311     albertel 5467:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5468:             &Reply($client, "ok\n", $userinput);
                   5469:         } else {
                   5470:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5471:                      "while attempting domroleput\n", $userinput);
                   5472:         }
                   5473:     } else {
                   5474:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5475:                   "while attempting domroleput\n", $userinput);
                   5476:     }
                   5477:                                                                                   
                   5478:     return 1;
                   5479: }
                   5480: 
                   5481: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
                   5482: 
                   5483: #
                   5484: # Retrieves domain roles from nohist_domainroles database
                   5485: # Returns to client an & separated list of key=value pairs,
                   5486: # where key is role and value is start and end date information.
                   5487: #
                   5488: # Parameters
                   5489: #   $cmd       - Command keyword that caused us to be dispatched.
                   5490: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5491: #               domain - the domain whose domain roles table we dump
                   5492: #   $client    - Socket open on the client.
                   5493: #
                   5494: # Returns:
                   5495: #    1 - indicating processing should continue.
                   5496: # Side effects
                   5497: #     reply (& separated list of role=start/end info pairs) is
                   5498: #     written to $client.
                   5499: #
                   5500: sub dump_domainroles_handler {
                   5501:     my ($cmd, $tail, $client) = @_;
                   5502:                                                                                            
                   5503:     my $userinput = "$cmd:$tail";
                   5504:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
                   5505:     chomp($rolesfilter);
                   5506:     my @roles = ();
                   5507:     if (defined($startfilter)) {
                   5508:         $startfilter=&unescape($startfilter);
                   5509:     } else {
                   5510:         $startfilter='.';
                   5511:     }
                   5512:     if (defined($endfilter)) {
                   5513:         $endfilter=&unescape($endfilter);
                   5514:     } else {
                   5515:         $endfilter='.';
                   5516:     }
                   5517:     if (defined($rolesfilter)) {
                   5518:         $rolesfilter=&unescape($rolesfilter);
1.300     albertel 5519: 	@roles = split(/\&/,$rolesfilter);
1.299     raeburn  5520:     }
1.421     raeburn  5521: 
1.299     raeburn  5522:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5523:     if ($hashref) {
                   5524:         my $qresult = '';
                   5525:         while (my ($key,$value) = each(%$hashref)) {
                   5526:             my $match = 1;
1.421     raeburn  5527:             my ($end,$start) = split(/:/,&unescape($value));
1.299     raeburn  5528:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
1.421     raeburn  5529:             unless (@roles < 1) {
                   5530:                 unless (grep/^\Q$trole\E$/,@roles) {
                   5531:                     $match = 0;
                   5532:                     next;
                   5533:                 }
                   5534:             }
1.299     raeburn  5535:             unless ($startfilter eq '.' || !defined($startfilter)) {
1.415     raeburn  5536:                 if ((defined($start)) && ($start >= $startfilter)) {
1.299     raeburn  5537:                     $match = 0;
1.421     raeburn  5538:                     next;
1.299     raeburn  5539:                 }
                   5540:             }
                   5541:             unless ($endfilter eq '.' || !defined($endfilter)) {
1.421     raeburn  5542:                 if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
1.299     raeburn  5543:                     $match = 0;
1.421     raeburn  5544:                     next;
1.299     raeburn  5545:                 }
                   5546:             }
                   5547:             if ($match == 1) {
                   5548:                 $qresult.=$key.'='.$value.'&';
                   5549:             }
                   5550:         }
1.311     albertel 5551:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5552:             chop($qresult);
1.387     albertel 5553:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5554:         } else {
                   5555:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5556:                     "while attempting domrolesdump\n", $userinput);
                   5557:         }
                   5558:     } else {
                   5559:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5560:                 "while attempting domrolesdump\n", $userinput);
                   5561:     }
                   5562:     return 1;
                   5563: }
                   5564: 
                   5565: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
                   5566: 
                   5567: 
1.238     foxr     5568: #  Process the tmpput command I'm not sure what this does.. Seems to
                   5569: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
                   5570: # where Id is the client's ip concatenated with a sequence number.
                   5571: # The file will contain some value that is passed in.  Is this e.g.
                   5572: # a login token?
                   5573: #
                   5574: # Parameters:
                   5575: #    $cmd     - The command that got us dispatched.
                   5576: #    $tail    - The remainder of the request following $cmd:
                   5577: #               In this case this will be the contents of the file.
                   5578: #    $client  - Socket connected to the client.
                   5579: # Returns:
                   5580: #    1 indicating processing can continue.
                   5581: # Side effects:
                   5582: #   A file is created in the local filesystem.
                   5583: #   A reply is sent to the client.
                   5584: sub tmp_put_handler {
                   5585:     my ($cmd, $what, $client) = @_;
                   5586: 
                   5587:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
                   5588: 
1.347     raeburn  5589:     my ($record,$context) = split(/:/,$what);
                   5590:     if ($context ne '') {
                   5591:         chomp($context);
                   5592:         $context = &unescape($context);
                   5593:     }
                   5594:     my ($id,$store);
1.238     foxr     5595:     $tmpsnum++;
1.454     raeburn  5596:     if (($context eq 'resetpw') || ($context eq 'createaccount')) {
1.347     raeburn  5597:         $id = &md5_hex(&md5_hex(time.{}.rand().$$));
                   5598:     } else {
                   5599:         $id = $$.'_'.$clientip.'_'.$tmpsnum;
                   5600:     }
1.238     foxr     5601:     $id=~s/\W/\_/g;
1.347     raeburn  5602:     $record=~s/\n//g;
1.238     foxr     5603:     my $execdir=$perlvar{'lonDaemons'};
                   5604:     if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
1.347     raeburn  5605: 	print $store $record;
1.238     foxr     5606: 	close $store;
1.387     albertel 5607: 	&Reply($client, \$id, $userinput);
1.238     foxr     5608:     } else {
                   5609: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5610: 		  "while attempting tmpput\n", $userinput);
                   5611:     }
                   5612:     return 1;
                   5613:   
                   5614: }
                   5615: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263     albertel 5616: 
1.238     foxr     5617: #   Processes the tmpget command.  This command returns the contents
                   5618: #  of a temporary resource file(?) created via tmpput.
                   5619: #
                   5620: # Paramters:
                   5621: #    $cmd      - Command that got us dispatched.
                   5622: #    $id       - Tail of the command, contain the id of the resource
                   5623: #                we want to fetch.
                   5624: #    $client   - socket open on the client.
                   5625: # Return:
                   5626: #    1         - Inidcating processing can continue.
                   5627: # Side effects:
                   5628: #   A reply is sent to the client.
                   5629: #
                   5630: sub tmp_get_handler {
                   5631:     my ($cmd, $id, $client) = @_;
                   5632: 
                   5633:     my $userinput = "$cmd:$id"; 
                   5634:     
                   5635: 
                   5636:     $id=~s/\W/\_/g;
                   5637:     my $store;
                   5638:     my $execdir=$perlvar{'lonDaemons'};
                   5639:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
                   5640: 	my $reply=<$store>;
1.387     albertel 5641: 	&Reply( $client, \$reply, $userinput);
1.238     foxr     5642: 	close $store;
                   5643:     } else {
                   5644: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5645: 		  "while attempting tmpget\n", $userinput);
                   5646:     }
                   5647: 
                   5648:     return 1;
                   5649: }
                   5650: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263     albertel 5651: 
1.238     foxr     5652: #
                   5653: #  Process the tmpdel command.  This command deletes a temp resource
                   5654: #  created by the tmpput command.
                   5655: #
                   5656: # Parameters:
                   5657: #   $cmd      - Command that got us here.
                   5658: #   $id       - Id of the temporary resource created.
                   5659: #   $client   - socket open on the client process.
                   5660: #
                   5661: # Returns:
                   5662: #   1     - Indicating processing should continue.
                   5663: # Side Effects:
                   5664: #   A file is deleted
                   5665: #   A reply is sent to the client.
                   5666: sub tmp_del_handler {
                   5667:     my ($cmd, $id, $client) = @_;
                   5668:     
                   5669:     my $userinput= "$cmd:$id";
                   5670:     
                   5671:     chomp($id);
                   5672:     $id=~s/\W/\_/g;
                   5673:     my $execdir=$perlvar{'lonDaemons'};
                   5674:     if (unlink("$execdir/tmp/$id.tmp")) {
                   5675: 	&Reply($client, "ok\n", $userinput);
                   5676:     } else {
                   5677: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
                   5678: 		  "while attempting tmpdel\n", $userinput);
                   5679:     }
                   5680:     
                   5681:     return 1;
                   5682: 
                   5683: }
                   5684: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263     albertel 5685: 
1.238     foxr     5686: #
1.551     raeburn  5687: #  Process the delbalcookie command. This command deletes a balancer
                   5688: #  cookie in the lonBalancedir directory created by switchserver
                   5689: #
                   5690: # Parameters:
                   5691: #   $cmd      - Command that got us here.
                   5692: #   $cookie   - Cookie to be deleted.
                   5693: #   $client   - socket open on the client process.
                   5694: #
                   5695: # Returns:
                   5696: #   1     - Indicating processing should continue.
                   5697: # Side Effects:
                   5698: #   A cookie file is deleted from the lonBalancedir directory
                   5699: #   A reply is sent to the client.
                   5700: sub del_balcookie_handler {
                   5701:     my ($cmd, $cookie, $client) = @_;
                   5702: 
                   5703:     my $userinput= "$cmd:$cookie";
                   5704: 
                   5705:     chomp($cookie);
                   5706:     my $deleted = '';
                   5707:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
                   5708:         my $execdir=$perlvar{'lonBalanceDir'};
                   5709:         if (-e "$execdir/$cookie.id") {
                   5710:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
                   5711:                 my $dodelete;
                   5712:                 while (my $line = <$fh>) {
                   5713:                     chomp($line);
                   5714:                     if ($line eq $clientname) {
                   5715:                         $dodelete = 1;
1.554     raeburn  5716:                         last;
1.551     raeburn  5717:                     }
                   5718:                 }
1.554     raeburn  5719:                 close($fh);
1.551     raeburn  5720:                 if ($dodelete) {
                   5721:                     if (unlink("$execdir/$cookie.id")) {
                   5722:                         $deleted = 1;
                   5723:                     }
                   5724:                 }
                   5725:             }
                   5726:         }
                   5727:     }
                   5728:     if ($deleted) {
                   5729:         &Reply($client, "ok\n", $userinput);
                   5730:     } else {
                   5731:         &Failure( $client, "error: ".($!+0)."Unlinking cookie file Failed ".
                   5732:                   "while attempting delbalcookie\n", $userinput);
                   5733:     }
                   5734:     return 1;
                   5735: }
                   5736: &register_handler("delbalcookie", \&del_balcookie_handler, 0, 1, 0);
                   5737: 
                   5738: #
1.246     foxr     5739: #   Processes the setannounce command.  This command
                   5740: #   creates a file named announce.txt in the top directory of
                   5741: #   the documentn root and sets its contents.  The announce.txt file is
                   5742: #   printed in its entirety at the LonCAPA login page.  Note:
                   5743: #   once the announcement.txt fileis created it cannot be deleted.
                   5744: #   However, setting the contents of the file to empty removes the
                   5745: #   announcement from the login page of loncapa so who cares.
                   5746: #
                   5747: # Parameters:
                   5748: #    $cmd          - The command that got us dispatched.
                   5749: #    $announcement - The text of the announcement.
                   5750: #    $client       - Socket open on the client process.
                   5751: # Retunrns:
                   5752: #   1             - Indicating request processing should continue
                   5753: # Side Effects:
                   5754: #   The file {DocRoot}/announcement.txt is created.
                   5755: #   A reply is sent to $client.
                   5756: #
                   5757: sub set_announce_handler {
                   5758:     my ($cmd, $announcement, $client) = @_;
                   5759:   
                   5760:     my $userinput    = "$cmd:$announcement";
                   5761: 
                   5762:     chomp($announcement);
                   5763:     $announcement=&unescape($announcement);
                   5764:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
                   5765: 				'/announcement.txt')) {
                   5766: 	print $store $announcement;
                   5767: 	close $store;
                   5768: 	&Reply($client, "ok\n", $userinput);
                   5769:     } else {
                   5770: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
                   5771:     }
                   5772: 
                   5773:     return 1;
                   5774: }
                   5775: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263     albertel 5776: 
1.246     foxr     5777: #
                   5778: #  Return the version of the daemon.  This can be used to determine
                   5779: #  the compatibility of cross version installations or, alternatively to
                   5780: #  simply know who's out of date and who isn't.  Note that the version
                   5781: #  is returned concatenated with the tail.
                   5782: # Parameters:
                   5783: #   $cmd        - the request that dispatched to us.
                   5784: #   $tail       - Tail of the request (client's version?).
                   5785: #   $client     - Socket open on the client.
                   5786: #Returns:
                   5787: #   1 - continue processing requests.
                   5788: # Side Effects:
                   5789: #   Replies with version to $client.
                   5790: sub get_version_handler {
                   5791:     my ($cmd, $tail, $client) = @_;
                   5792: 
                   5793:     my $userinput  = $cmd.$tail;
                   5794:     
                   5795:     &Reply($client, &version($userinput)."\n", $userinput);
                   5796: 
                   5797: 
                   5798:     return 1;
                   5799: }
                   5800: &register_handler("version", \&get_version_handler, 0, 1, 0);
1.263     albertel 5801: 
1.246     foxr     5802: #  Set the current host and domain.  This is used to support
                   5803: #  multihomed systems.  Each IP of the system, or even separate daemons
                   5804: #  on the same IP can be treated as handling a separate lonCAPA virtual
                   5805: #  machine.  This command selects the virtual lonCAPA.  The client always
                   5806: #  knows the right one since it is lonc and it is selecting the domain/system
                   5807: #  from the hosts.tab file.
                   5808: # Parameters:
                   5809: #    $cmd      - Command that dispatched us.
                   5810: #    $tail     - Tail of the command (domain/host requested).
                   5811: #    $socket   - Socket open on the client.
                   5812: #
                   5813: # Returns:
                   5814: #     1   - Indicates the program should continue to process requests.
                   5815: # Side-effects:
                   5816: #     The default domain/system context is modified for this daemon.
                   5817: #     a reply is sent to the client.
                   5818: #
                   5819: sub set_virtual_host_handler {
                   5820:     my ($cmd, $tail, $socket) = @_;
                   5821:   
                   5822:     my $userinput  ="$cmd:$tail";
                   5823: 
                   5824:     &Reply($client, &sethost($userinput)."\n", $userinput);
                   5825: 
                   5826: 
                   5827:     return 1;
                   5828: }
1.247     albertel 5829: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246     foxr     5830: 
                   5831: #  Process a request to exit:
                   5832: #   - "bye" is sent to the client.
                   5833: #   - The client socket is shutdown and closed.
                   5834: #   - We indicate to the caller that we should exit.
                   5835: # Formal Parameters:
                   5836: #   $cmd                - The command that got us here.
                   5837: #   $tail               - Tail of the command (empty).
                   5838: #   $client             - Socket open on the tail.
                   5839: # Returns:
                   5840: #   0      - Indicating the program should exit!!
                   5841: #
                   5842: sub exit_handler {
                   5843:     my ($cmd, $tail, $client) = @_;
                   5844: 
                   5845:     my $userinput = "$cmd:$tail";
                   5846: 
                   5847:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
                   5848:     &Reply($client, "bye\n", $userinput);
                   5849:     $client->shutdown(2);        # shutdown the socket forcibly.
                   5850:     $client->close();
                   5851: 
                   5852:     return 0;
                   5853: }
1.248     foxr     5854: &register_handler("exit", \&exit_handler, 0,1,1);
                   5855: &register_handler("init", \&exit_handler, 0,1,1);
                   5856: &register_handler("quit", \&exit_handler, 0,1,1);
                   5857: 
                   5858: #  Determine if auto-enrollment is enabled.
                   5859: #  Note that the original had what I believe to be a defect.
                   5860: #  The original returned 0 if the requestor was not a registerd client.
                   5861: #  It should return "refused".
                   5862: # Formal Parameters:
                   5863: #   $cmd       - The command that invoked us.
                   5864: #   $tail      - The tail of the command (Extra command parameters.
                   5865: #   $client    - The socket open on the client that issued the request.
                   5866: # Returns:
                   5867: #    1         - Indicating processing should continue.
                   5868: #
                   5869: sub enrollment_enabled_handler {
                   5870:     my ($cmd, $tail, $client) = @_;
                   5871:     my $userinput = $cmd.":".$tail; # For logging purposes.
                   5872: 
                   5873:     
1.337     albertel 5874:     my ($cdom) = split(/:/, $tail, 2);   # Domain we're asking about.
                   5875: 
1.248     foxr     5876:     my $outcome  = &localenroll::run($cdom);
1.387     albertel 5877:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5878: 
                   5879:     return 1;
                   5880: }
                   5881: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
                   5882: 
1.417     raeburn  5883: #
1.423     raeburn  5884: #   Validate an institutional code used for a LON-CAPA course.          
1.417     raeburn  5885: #
                   5886: # Formal Parameters:
                   5887: #   $cmd          - The command request that got us dispatched.
                   5888: #   $tail         - The tail of the command.  In this case,
                   5889: #                   this is a colon separated set of words that will be split
                   5890: #                   into:
1.424     raeburn  5891: #                        $dom      - The domain for which the check of 
                   5892: #                                    institutional course code will occur.
                   5893: #
                   5894: #                        $instcode - The institutional code for the course
                   5895: #                                    being requested, or validated for rights
                   5896: #                                    to request.
                   5897: #
                   5898: #                        $owner    - The course requestor (who will be the
                   5899: #                                    course owner, in the form username:domain
                   5900: #
1.417     raeburn  5901: #   $client       - Socket open on the client.
                   5902: # Returns:
                   5903: #    1           - Indicating processing should continue.
                   5904: #
                   5905: sub validate_instcode_handler {
                   5906:     my ($cmd, $tail, $client) = @_;
                   5907:     my $userinput = "$cmd:$tail";
1.423     raeburn  5908:     my ($dom,$instcode,$owner) = split(/:/, $tail);
1.422     raeburn  5909:     $instcode = &unescape($instcode);
                   5910:     $owner = &unescape($owner);
1.498     raeburn  5911:     my ($outcome,$description,$credits) = 
1.426     raeburn  5912:         &localenroll::validate_instcode($dom,$instcode,$owner);
1.498     raeburn  5913:     my $result = &escape($outcome).'&'.&escape($description).'&'.
                   5914:                  &escape($credits);
1.426     raeburn  5915:     &Reply($client, \$result, $userinput);
1.417     raeburn  5916: 
                   5917:     return 1;
                   5918: }
                   5919: &register_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
                   5920: 
1.248     foxr     5921: #   Get the official sections for which auto-enrollment is possible.
                   5922: #   Since the admin people won't know about 'unofficial sections' 
                   5923: #   we cannot auto-enroll on them.
                   5924: # Formal Parameters:
                   5925: #    $cmd     - The command request that got us dispatched here.
                   5926: #    $tail    - The remainder of the request.  In our case this
                   5927: #               will be split into:
                   5928: #               $coursecode   - The course name from the admin point of view.
                   5929: #               $cdom         - The course's domain(?).
                   5930: #    $client  - Socket open on the client.
                   5931: # Returns:
                   5932: #    1    - Indiciting processing should continue.
                   5933: #
                   5934: sub get_sections_handler {
                   5935:     my ($cmd, $tail, $client) = @_;
                   5936:     my $userinput = "$cmd:$tail";
                   5937: 
                   5938:     my ($coursecode, $cdom) = split(/:/, $tail);
                   5939:     my @secs = &localenroll::get_sections($coursecode,$cdom);
                   5940:     my $seclist = &escape(join(':',@secs));
                   5941: 
1.387     albertel 5942:     &Reply($client, \$seclist, $userinput);
1.248     foxr     5943:     
                   5944: 
                   5945:     return 1;
                   5946: }
                   5947: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
                   5948: 
                   5949: #   Validate the owner of a new course section.  
                   5950: #
                   5951: # Formal Parameters:
                   5952: #   $cmd      - Command that got us dispatched.
                   5953: #   $tail     - the remainder of the command.  For us this consists of a
                   5954: #               colon separated string containing:
                   5955: #                  $inst    - Course Id from the institutions point of view.
                   5956: #                  $owner   - Proposed owner of the course.
                   5957: #                  $cdom    - Domain of the course (from the institutions
                   5958: #                             point of view?)..
                   5959: #   $client   - Socket open on the client.
                   5960: #
                   5961: # Returns:
                   5962: #   1        - Processing should continue.
                   5963: #
                   5964: sub validate_course_owner_handler {
                   5965:     my ($cmd, $tail, $client)  = @_;
                   5966:     my $userinput = "$cmd:$tail";
1.470     raeburn  5967:     my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
                   5968:     
1.336     raeburn  5969:     $owner = &unescape($owner);
1.470     raeburn  5970:     $coowners = &unescape($coowners);
                   5971:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
1.387     albertel 5972:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5973: 
                   5974: 
                   5975: 
                   5976:     return 1;
                   5977: }
                   5978: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263     albertel 5979: 
1.248     foxr     5980: #
                   5981: #   Validate a course section in the official schedule of classes
                   5982: #   from the institutions point of view (part of autoenrollment).
                   5983: #
                   5984: # Formal Parameters:
                   5985: #   $cmd          - The command request that got us dispatched.
                   5986: #   $tail         - The tail of the command.  In this case,
                   5987: #                   this is a colon separated set of words that will be split
                   5988: #                   into:
                   5989: #                        $inst_course_id - The course/section id from the
                   5990: #                                          institutions point of view.
                   5991: #                        $cdom           - The domain from the institutions
                   5992: #                                          point of view.
                   5993: #   $client       - Socket open on the client.
                   5994: # Returns:
                   5995: #    1           - Indicating processing should continue.
                   5996: #
                   5997: sub validate_course_section_handler {
                   5998:     my ($cmd, $tail, $client) = @_;
                   5999:     my $userinput = "$cmd:$tail";
                   6000:     my ($inst_course_id, $cdom) = split(/:/, $tail);
                   6001: 
                   6002:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
1.387     albertel 6003:     &Reply($client, \$outcome, $userinput);
1.248     foxr     6004: 
                   6005: 
                   6006:     return 1;
                   6007: }
                   6008: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
                   6009: 
                   6010: #
1.340     raeburn  6011: #   Validate course owner's access to enrollment data for specific class section. 
                   6012: #   
                   6013: #
                   6014: # Formal Parameters:
                   6015: #    $cmd     - The command request that got us dispatched.
                   6016: #    $tail    - The tail of the command.   In this case this is a colon separated
1.542     raeburn  6017: #               set of values that will be split into:
1.340     raeburn  6018: #               $inst_class  - Institutional code for the specific class section   
1.542     raeburn  6019: #               $ownerlist   - An escaped comma-separated list of username:domain 
                   6020: #                              of the course owner, and co-owner(s).
1.340     raeburn  6021: #               $cdom        - The domain of the course from the institution's
                   6022: #                              point of view.
                   6023: #    $client  - The socket open on the client.
                   6024: # Returns:
                   6025: #    1 - continue processing.
                   6026: #
                   6027: 
                   6028: sub validate_class_access_handler {
                   6029:     my ($cmd, $tail, $client) = @_;
                   6030:     my $userinput = "$cmd:$tail";
1.383     raeburn  6031:     my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
1.392     raeburn  6032:     my $owners = &unescape($ownerlist);
1.341     albertel 6033:     my $outcome;
                   6034:     eval {
                   6035: 	local($SIG{__DIE__})='DEFAULT';
1.392     raeburn  6036: 	$outcome=&localenroll::check_section($inst_class,$owners,$cdom);
1.341     albertel 6037:     };
1.387     albertel 6038:     &Reply($client,\$outcome, $userinput);
1.340     raeburn  6039: 
                   6040:     return 1;
                   6041: }
                   6042: &register_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
                   6043: 
                   6044: #
1.542     raeburn  6045: #   Validate course owner or co-owners(s) access to enrollment data for all sections
                   6046: #   and crosslistings for a particular course.
                   6047: #
                   6048: #
                   6049: # Formal Parameters:
                   6050: #    $cmd     - The command request that got us dispatched.
                   6051: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6052: #               set of values that will be split into:
                   6053: #               $ownerlist   - An escaped comma-separated list of username:domain
                   6054: #                              of the course owner, and co-owner(s).
                   6055: #               $cdom        - The domain of the course from the institution's
                   6056: #                              point of view.
                   6057: #               $classes     - Frozen hash of institutional course sections and
                   6058: #                              crosslistings.
                   6059: #    $client  - The socket open on the client.
                   6060: # Returns:
                   6061: #    1 - continue processing.
                   6062: #
                   6063: 
                   6064: sub validate_classes_handler {
                   6065:     my ($cmd, $tail, $client) = @_;
                   6066:     my $userinput = "$cmd:$tail";
                   6067:     my ($ownerlist,$cdom,$classes) = split(/:/, $tail);
                   6068:     my $classesref = &Apache::lonnet::thaw_unescape($classes);
                   6069:     my $owners = &unescape($ownerlist);
                   6070:     my $result;
                   6071:     eval {
                   6072:         local($SIG{__DIE__})='DEFAULT';
                   6073:         my %validations;
                   6074:         my $response = &localenroll::check_instclasses($owners,$cdom,$classesref,
                   6075:                                                        \%validations);
                   6076:         if ($response eq 'ok') {
                   6077:             foreach my $key (keys(%validations)) {
                   6078:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   6079:             }
                   6080:             $result =~ s/\&$//;
                   6081:         } else {
                   6082:             $result = 'error';
                   6083:         }
                   6084:     };
                   6085:     if (!$@) {
                   6086:         &Reply($client, \$result, $userinput);
                   6087:     } else {
                   6088:         &Failure($client,"unknown_cmd\n",$userinput);
                   6089:     }
                   6090:     return 1;
                   6091: }
                   6092: &register_handler("autovalidateinstclasses", \&validate_classes_handler, 0, 1, 0);
                   6093: 
                   6094: #
1.340     raeburn  6095: #   Create a password for a new LON-CAPA user added by auto-enrollment.
                   6096: #   Only used for case where authentication method for new user is localauth
1.248     foxr     6097: #
                   6098: # Formal Parameters:
                   6099: #    $cmd     - The command request that got us dispatched.
                   6100: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6101: #               set of words that will be split into:
1.340     raeburn  6102: #               $authparam - An authentication parameter (localauth parameter).
1.248     foxr     6103: #               $cdom      - The domain of the course from the institution's
                   6104: #                            point of view.
                   6105: #    $client  - The socket open on the client.
                   6106: # Returns:
                   6107: #    1 - continue processing.
                   6108: #
                   6109: sub create_auto_enroll_password_handler {
                   6110:     my ($cmd, $tail, $client) = @_;
                   6111:     my $userinput = "$cmd:$tail";
                   6112: 
                   6113:     my ($authparam, $cdom) = split(/:/, $userinput);
                   6114: 
                   6115:     my ($create_passwd,$authchk);
                   6116:     ($authparam,
                   6117:      $create_passwd,
                   6118:      $authchk) = &localenroll::create_password($authparam,$cdom);
                   6119: 
                   6120:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
                   6121: 	   $userinput);
                   6122: 
                   6123: 
                   6124:     return 1;
                   6125: }
                   6126: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
                   6127: 		  0, 1, 0);
                   6128: 
1.522     raeburn  6129: sub auto_export_grades_handler {
                   6130:     my ($cmd, $tail, $client) = @_;
                   6131:     my $userinput = "$cmd:$tail";
                   6132:     my ($cdom,$cnum,$info,$data) = split(/:/,$tail);
                   6133:     my $inforef = &Apache::lonnet::thaw_unescape($info);
                   6134:     my $dataref = &Apache::lonnet::thaw_unescape($data);
                   6135:     my ($outcome,$result);;
                   6136:     eval {
                   6137:         local($SIG{__DIE__})='DEFAULT';
                   6138:         my %rtnhash;
                   6139:         $outcome=&localenroll::export_grades($cdom,$cnum,$inforef,$dataref,\%rtnhash);
                   6140:         if ($outcome eq 'ok') {
                   6141:             foreach my $key (keys(%rtnhash)) {
                   6142:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   6143:             }
                   6144:             $result =~ s/\&$//;
                   6145:         }
                   6146:     };
                   6147:     if (!$@) {
                   6148:         if ($outcome eq 'ok') {
                   6149:             if ($cipher) {
                   6150:                 my $cmdlength=length($result);
                   6151:                 $result.="         ";
                   6152:                 my $encresult='';
                   6153:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   6154:                     $encresult.= unpack("H16",
                   6155:                                         $cipher->encrypt(substr($result,
                   6156:                                                                 $encidx,
                   6157:                                                                 8)));
                   6158:                 }
                   6159:                 &Reply( $client, "enc:$cmdlength:$encresult\n", $userinput);
                   6160:             } else {
                   6161:                 &Failure( $client, "error:no_key\n", $userinput);
                   6162:             }
                   6163:         } else {
                   6164:             &Reply($client, "$outcome\n", $userinput);
                   6165:         }
                   6166:     } else {
                   6167:         &Failure($client,"export_error\n",$userinput);
                   6168:     }
                   6169:     return 1;
                   6170: }
                   6171: &register_handler("autoexportgrades", \&auto_export_grades_handler,
1.536     raeburn  6172:                   1, 1, 0);
1.522     raeburn  6173: 
1.248     foxr     6174: #   Retrieve and remove temporary files created by/during autoenrollment.
                   6175: #
                   6176: # Formal Parameters:
                   6177: #    $cmd      - The command that got us dispatched.
                   6178: #    $tail     - The tail of the command.  In our case this is a colon 
                   6179: #                separated list that will be split into:
1.526     raeburn  6180: #                $filename - The name of the file to retrieve.
1.248     foxr     6181: #                            The filename is given as a path relative to
                   6182: #                            the LonCAPA temp file directory.
                   6183: #    $client   - Socket open on the client.
                   6184: #
                   6185: # Returns:
                   6186: #   1     - Continue processing.
                   6187: sub retrieve_auto_file_handler {
                   6188:     my ($cmd, $tail, $client)    = @_;
                   6189:     my $userinput                = "cmd:$tail";
                   6190: 
                   6191:     my ($filename)   = split(/:/, $tail);
                   6192: 
                   6193:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
1.521     raeburn  6194: 
                   6195:     if ($filename =~m{/\.\./}) {
                   6196:         &Failure($client, "refused\n", $userinput);
1.526     raeburn  6197:     } elsif ($filename !~ /^$LONCAPA::match_domain\_$LONCAPA::match_courseid\_.+_classlist\.xml$/) {
                   6198:         &Failure($client, "refused\n", $userinput);
1.521     raeburn  6199:     } elsif ( (-e $source) && ($filename ne '') ) {
1.248     foxr     6200: 	my $reply = '';
                   6201: 	if (open(my $fh,$source)) {
                   6202: 	    while (<$fh>) {
                   6203: 		chomp($_);
                   6204: 		$_ =~ s/^\s+//g;
                   6205: 		$_ =~ s/\s+$//g;
                   6206: 		$reply .= $_;
                   6207: 	    }
                   6208: 	    close($fh);
                   6209: 	    &Reply($client, &escape($reply)."\n", $userinput);
                   6210: 
                   6211: #   Does this have to be uncommented??!?  (RF).
                   6212: #
                   6213: #                                unlink($source);
                   6214: 	} else {
                   6215: 	    &Failure($client, "error\n", $userinput);
                   6216: 	}
                   6217:     } else {
                   6218: 	&Failure($client, "error\n", $userinput);
                   6219:     }
                   6220:     
                   6221: 
                   6222:     return 1;
                   6223: }
                   6224: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
                   6225: 
1.423     raeburn  6226: sub crsreq_checks_handler {
                   6227:     my ($cmd, $tail, $client) = @_;
                   6228:     my $userinput = "$cmd:$tail";
                   6229:     my $dom = $tail;
                   6230:     my $result;
1.519     raeburn  6231:     my @reqtypes = ('official','unofficial','community','textbook','placement');
1.423     raeburn  6232:     eval {
                   6233:         local($SIG{__DIE__})='DEFAULT';
                   6234:         my %validations;
1.424     raeburn  6235:         my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
                   6236:                                                    \%validations);
1.423     raeburn  6237:         if ($response eq 'ok') { 
                   6238:             foreach my $key (keys(%validations)) {
                   6239:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   6240:             }
                   6241:             $result =~ s/\&$//;
                   6242:         } else {
                   6243:             $result = 'error';
                   6244:         }
                   6245:     };
                   6246:     if (!$@) {
                   6247:         &Reply($client, \$result, $userinput);
                   6248:     } else {
                   6249:         &Failure($client,"unknown_cmd\n",$userinput);
                   6250:     }
                   6251:     return 1;
                   6252: }
                   6253: &register_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
                   6254: 
                   6255: sub validate_crsreq_handler {
                   6256:     my ($cmd, $tail, $client) = @_;
                   6257:     my $userinput = "$cmd:$tail";
1.508     raeburn  6258:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
1.423     raeburn  6259:     $instcode = &unescape($instcode);
                   6260:     $owner = &unescape($owner);
                   6261:     $crstype = &unescape($crstype);
                   6262:     $inststatuslist = &unescape($inststatuslist);
                   6263:     $instcode = &unescape($instcode);
                   6264:     $instseclist = &unescape($instseclist);
1.508     raeburn  6265:     my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
1.423     raeburn  6266:     my $outcome;
                   6267:     eval {
                   6268:         local($SIG{__DIE__})='DEFAULT';
                   6269:         $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
                   6270:                                                  $inststatuslist,$instcode,
1.508     raeburn  6271:                                                  $instseclist,$custominfo);
1.423     raeburn  6272:     };
                   6273:     if (!$@) {
                   6274:         &Reply($client, \$outcome, $userinput);
                   6275:     } else {
                   6276:         &Failure($client,"unknown_cmd\n",$userinput);
                   6277:     }
                   6278:     return 1;
                   6279: }
                   6280: &register_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
                   6281: 
1.506     raeburn  6282: sub crsreq_update_handler {
                   6283:     my ($cmd, $tail, $client) = @_;
                   6284:     my $userinput = "$cmd:$tail";
1.509     raeburn  6285:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
                   6286:         $accessstart,$accessend,$infohashref) =
1.506     raeburn  6287:         split(/:/, $tail);
                   6288:     $crstype = &unescape($crstype);
                   6289:     $action = &unescape($action);
                   6290:     $ownername = &unescape($ownername);
                   6291:     $ownerdomain = &unescape($ownerdomain);
                   6292:     $fullname = &unescape($fullname);
                   6293:     $title = &unescape($title);
                   6294:     $code = &unescape($code);
1.509     raeburn  6295:     $accessstart = &unescape($accessstart);
                   6296:     $accessend = &unescape($accessend);
1.506     raeburn  6297:     my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
                   6298:     my ($result,$outcome);
                   6299:     eval {
                   6300:         local($SIG{__DIE__})='DEFAULT';
                   6301:         my %rtnhash;
                   6302:         $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
                   6303:                                                 $ownername,$ownerdomain,$fullname,
1.509     raeburn  6304:                                                 $title,$code,$accessstart,$accessend,
                   6305:                                                 $incoming,\%rtnhash);
1.506     raeburn  6306:         if ($outcome eq 'ok') {
1.515     raeburn  6307:             my @posskeys = qw(createdweb createdmsg createdcustomized createdactions queuedweb queuedmsg formitems reviewweb validationjs onload javascript);
1.506     raeburn  6308:             foreach my $key (keys(%rtnhash)) {
                   6309:                 if (grep(/^\Q$key\E/,@posskeys)) {
                   6310:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   6311:                 }
                   6312:             }
                   6313:             $result =~ s/\&$//;
                   6314:         }
                   6315:     };
                   6316:     if (!$@) {
                   6317:         if ($outcome eq 'ok') {
                   6318:             &Reply($client, \$result, $userinput);
                   6319:         } else {
                   6320:             &Reply($client, "format_error\n", $userinput);
                   6321:         }
                   6322:     } else {
                   6323:         &Failure($client,"unknown_cmd\n",$userinput);
                   6324:     }
                   6325:     return 1;
                   6326: }
                   6327: &register_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
                   6328: 
1.248     foxr     6329: #
                   6330: #   Read and retrieve institutional code format (for support form).
                   6331: # Formal Parameters:
                   6332: #    $cmd        - Command that dispatched us.
                   6333: #    $tail       - Tail of the command.  In this case it conatins 
                   6334: #                  the course domain and the coursename.
                   6335: #    $client     - Socket open on the client.
                   6336: # Returns:
                   6337: #    1     - Continue processing.
                   6338: #
                   6339: sub get_institutional_code_format_handler {
                   6340:     my ($cmd, $tail, $client)   = @_;
                   6341:     my $userinput               = "$cmd:$tail";
                   6342: 
                   6343:     my $reply;
                   6344:     my($cdom,$course) = split(/:/,$tail);
                   6345:     my @pairs = split/\&/,$course;
                   6346:     my %instcodes = ();
                   6347:     my %codes = ();
                   6348:     my @codetitles = ();
                   6349:     my %cat_titles = ();
                   6350:     my %cat_order = ();
                   6351:     foreach (@pairs) {
                   6352: 	my ($key,$value) = split/=/,$_;
                   6353: 	$instcodes{&unescape($key)} = &unescape($value);
                   6354:     }
                   6355:     my $formatreply = &localenroll::instcode_format($cdom,
                   6356: 						    \%instcodes,
                   6357: 						    \%codes,
                   6358: 						    \@codetitles,
                   6359: 						    \%cat_titles,
                   6360: 						    \%cat_order);
                   6361:     if ($formatreply eq 'ok') {
1.365     albertel 6362: 	my $codes_str = &Apache::lonnet::hash2str(%codes);
                   6363: 	my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
                   6364: 	my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
                   6365: 	my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
1.248     foxr     6366: 	&Reply($client,
                   6367: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
                   6368: 	       .$cat_order_str."\n",
                   6369: 	       $userinput);
                   6370:     } else {
                   6371: 	# this else branch added by RF since if not ok, lonc will
                   6372: 	# hang waiting on reply until timeout.
                   6373: 	#
                   6374: 	&Reply($client, "format_error\n", $userinput);
                   6375:     }
                   6376:     
                   6377:     return 1;
                   6378: }
1.265     albertel 6379: &register_handler("autoinstcodeformat",
                   6380: 		  \&get_institutional_code_format_handler,0,1,0);
1.246     foxr     6381: 
1.345     raeburn  6382: sub get_institutional_defaults_handler {
                   6383:     my ($cmd, $tail, $client)   = @_;
                   6384:     my $userinput               = "$cmd:$tail";
                   6385: 
                   6386:     my $dom = $tail;
                   6387:     my %defaults_hash;
                   6388:     my @code_order;
                   6389:     my $outcome;
                   6390:     eval {
                   6391:         local($SIG{__DIE__})='DEFAULT';
                   6392:         $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
                   6393:                                                    \@code_order);
                   6394:     };
                   6395:     if (!$@) {
                   6396:         if ($outcome eq 'ok') {
                   6397:             my $result='';
                   6398:             while (my ($key,$value) = each(%defaults_hash)) {
                   6399:                 $result.=&escape($key).'='.&escape($value).'&';
                   6400:             }
                   6401:             $result .= 'code_order='.&escape(join('&',@code_order));
1.387     albertel 6402:             &Reply($client,\$result,$userinput);
1.345     raeburn  6403:         } else {
                   6404:             &Reply($client,"error\n", $userinput);
                   6405:         }
                   6406:     } else {
                   6407:         &Failure($client,"unknown_cmd\n",$userinput);
                   6408:     }
                   6409: }
                   6410: &register_handler("autoinstcodedefaults",
                   6411:                   \&get_institutional_defaults_handler,0,1,0);
                   6412: 
1.416     raeburn  6413: sub get_possible_instcodes_handler {
                   6414:     my ($cmd, $tail, $client)   = @_;
                   6415:     my $userinput               = "$cmd:$tail";
                   6416: 
                   6417:     my $reply;
                   6418:     my $cdom = $tail;
1.417     raeburn  6419:     my (@codetitles,%cat_titles,%cat_order,@code_order);
1.416     raeburn  6420:     my $formatreply = &localenroll::possible_instcodes($cdom,
                   6421:                                                        \@codetitles,
                   6422:                                                        \%cat_titles,
1.417     raeburn  6423:                                                        \%cat_order,
                   6424:                                                        \@code_order);
1.416     raeburn  6425:     if ($formatreply eq 'ok') {
                   6426:         my $result = join('&',map {&escape($_);} (@codetitles)).':';
1.417     raeburn  6427:         $result .= join('&',map {&escape($_);} (@code_order)).':';
1.416     raeburn  6428:         foreach my $key (keys(%cat_titles)) {
                   6429:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
                   6430:         }
                   6431:         $result =~ s/\&$//;
                   6432:         $result .= ':';
                   6433:         foreach my $key (keys(%cat_order)) {
                   6434:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
                   6435:         }
                   6436:         $result =~ s/\&$//;
                   6437:         &Reply($client,\$result,$userinput);
                   6438:     } else {
                   6439:         &Reply($client, "format_error\n", $userinput);
                   6440:     }
                   6441:     return 1;
                   6442: }
                   6443: &register_handler("autopossibleinstcodes",
                   6444:                   \&get_possible_instcodes_handler,0,1,0);
                   6445: 
1.381     raeburn  6446: sub get_institutional_user_rules {
                   6447:     my ($cmd, $tail, $client)   = @_;
                   6448:     my $userinput               = "$cmd:$tail";
                   6449:     my $dom = &unescape($tail);
                   6450:     my (%rules_hash,@rules_order);
                   6451:     my $outcome;
                   6452:     eval {
                   6453:         local($SIG{__DIE__})='DEFAULT';
                   6454:         $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
                   6455:     };
                   6456:     if (!$@) {
                   6457:         if ($outcome eq 'ok') {
                   6458:             my $result;
                   6459:             foreach my $key (keys(%rules_hash)) {
                   6460:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6461:             }
                   6462:             $result =~ s/\&$//;
                   6463:             $result .= ':';
                   6464:             if (@rules_order > 0) {
                   6465:                 foreach my $item (@rules_order) {
                   6466:                     $result .= &escape($item).'&';
                   6467:                 }
                   6468:             }
                   6469:             $result =~ s/\&$//;
1.387     albertel 6470:             &Reply($client,\$result,$userinput);
1.381     raeburn  6471:         } else {
                   6472:             &Reply($client,"error\n", $userinput);
                   6473:         }
                   6474:     } else {
                   6475:         &Failure($client,"unknown_cmd\n",$userinput);
                   6476:     }
                   6477: }
                   6478: &register_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
                   6479: 
1.389     raeburn  6480: sub get_institutional_id_rules {
                   6481:     my ($cmd, $tail, $client)   = @_;
                   6482:     my $userinput               = "$cmd:$tail";
                   6483:     my $dom = &unescape($tail);
                   6484:     my (%rules_hash,@rules_order);
                   6485:     my $outcome;
                   6486:     eval {
                   6487:         local($SIG{__DIE__})='DEFAULT';
                   6488:         $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
                   6489:     };
                   6490:     if (!$@) {
                   6491:         if ($outcome eq 'ok') {
                   6492:             my $result;
                   6493:             foreach my $key (keys(%rules_hash)) {
                   6494:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6495:             }
                   6496:             $result =~ s/\&$//;
                   6497:             $result .= ':';
                   6498:             if (@rules_order > 0) {
                   6499:                 foreach my $item (@rules_order) {
                   6500:                     $result .= &escape($item).'&';
                   6501:                 }
                   6502:             }
                   6503:             $result =~ s/\&$//;
                   6504:             &Reply($client,\$result,$userinput);
                   6505:         } else {
                   6506:             &Reply($client,"error\n", $userinput);
                   6507:         }
                   6508:     } else {
                   6509:         &Failure($client,"unknown_cmd\n",$userinput);
                   6510:     }
                   6511: }
                   6512: &register_handler("instidrules",\&get_institutional_id_rules,0,1,0);
                   6513: 
1.397     raeburn  6514: sub get_institutional_selfcreate_rules {
1.396     raeburn  6515:     my ($cmd, $tail, $client)   = @_;
                   6516:     my $userinput               = "$cmd:$tail";
                   6517:     my $dom = &unescape($tail);
                   6518:     my (%rules_hash,@rules_order);
                   6519:     my $outcome;
                   6520:     eval {
                   6521:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6522:         $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
1.396     raeburn  6523:     };
                   6524:     if (!$@) {
                   6525:         if ($outcome eq 'ok') {
                   6526:             my $result;
                   6527:             foreach my $key (keys(%rules_hash)) {
                   6528:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6529:             }
                   6530:             $result =~ s/\&$//;
                   6531:             $result .= ':';
                   6532:             if (@rules_order > 0) {
                   6533:                 foreach my $item (@rules_order) {
                   6534:                     $result .= &escape($item).'&';
                   6535:                 }
                   6536:             }
                   6537:             $result =~ s/\&$//;
                   6538:             &Reply($client,\$result,$userinput);
                   6539:         } else {
                   6540:             &Reply($client,"error\n", $userinput);
                   6541:         }
                   6542:     } else {
                   6543:         &Failure($client,"unknown_cmd\n",$userinput);
                   6544:     }
                   6545: }
1.397     raeburn  6546: &register_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
1.396     raeburn  6547: 
1.381     raeburn  6548: 
                   6549: sub institutional_username_check {
                   6550:     my ($cmd, $tail, $client)   = @_;
                   6551:     my $userinput               = "$cmd:$tail";
                   6552:     my %rulecheck;
                   6553:     my $outcome;
                   6554:     my ($udom,$uname,@rules) = split(/:/,$tail);
                   6555:     $udom = &unescape($udom);
                   6556:     $uname = &unescape($uname);
                   6557:     @rules = map {&unescape($_);} (@rules);
                   6558:     eval {
                   6559:         local($SIG{__DIE__})='DEFAULT';
                   6560:         $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
                   6561:     };
                   6562:     if (!$@) {
                   6563:         if ($outcome eq 'ok') {
                   6564:             my $result='';
                   6565:             foreach my $key (keys(%rulecheck)) {
                   6566:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6567:             }
1.387     albertel 6568:             &Reply($client,\$result,$userinput);
1.381     raeburn  6569:         } else {
                   6570:             &Reply($client,"error\n", $userinput);
                   6571:         }
                   6572:     } else {
                   6573:         &Failure($client,"unknown_cmd\n",$userinput);
                   6574:     }
                   6575: }
                   6576: &register_handler("instrulecheck",\&institutional_username_check,0,1,0);
                   6577: 
1.389     raeburn  6578: sub institutional_id_check {
                   6579:     my ($cmd, $tail, $client)   = @_;
                   6580:     my $userinput               = "$cmd:$tail";
                   6581:     my %rulecheck;
                   6582:     my $outcome;
                   6583:     my ($udom,$id,@rules) = split(/:/,$tail);
                   6584:     $udom = &unescape($udom);
                   6585:     $id = &unescape($id);
                   6586:     @rules = map {&unescape($_);} (@rules);
                   6587:     eval {
                   6588:         local($SIG{__DIE__})='DEFAULT';
                   6589:         $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
                   6590:     };
                   6591:     if (!$@) {
                   6592:         if ($outcome eq 'ok') {
                   6593:             my $result='';
                   6594:             foreach my $key (keys(%rulecheck)) {
                   6595:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6596:             }
                   6597:             &Reply($client,\$result,$userinput);
                   6598:         } else {
                   6599:             &Reply($client,"error\n", $userinput);
                   6600:         }
                   6601:     } else {
                   6602:         &Failure($client,"unknown_cmd\n",$userinput);
                   6603:     }
                   6604: }
                   6605: &register_handler("instidrulecheck",\&institutional_id_check,0,1,0);
1.345     raeburn  6606: 
1.397     raeburn  6607: sub institutional_selfcreate_check {
1.396     raeburn  6608:     my ($cmd, $tail, $client)   = @_;
                   6609:     my $userinput               = "$cmd:$tail";
                   6610:     my %rulecheck;
                   6611:     my $outcome;
                   6612:     my ($udom,$email,@rules) = split(/:/,$tail);
                   6613:     $udom = &unescape($udom);
                   6614:     $email = &unescape($email);
                   6615:     @rules = map {&unescape($_);} (@rules);
                   6616:     eval {
                   6617:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6618:         $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
1.396     raeburn  6619:     };
                   6620:     if (!$@) {
                   6621:         if ($outcome eq 'ok') {
                   6622:             my $result='';
                   6623:             foreach my $key (keys(%rulecheck)) {
                   6624:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6625:             }
                   6626:             &Reply($client,\$result,$userinput);
                   6627:         } else {
                   6628:             &Reply($client,"error\n", $userinput);
                   6629:         }
                   6630:     } else {
                   6631:         &Failure($client,"unknown_cmd\n",$userinput);
                   6632:     }
                   6633: }
1.397     raeburn  6634: &register_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
1.396     raeburn  6635: 
1.317     raeburn  6636: # Get domain specific conditions for import of student photographs to a course
                   6637: #
                   6638: # Retrieves information from photo_permission subroutine in localenroll.
                   6639: # Returns outcome (ok) if no processing errors, and whether course owner is 
                   6640: # required to accept conditions of use (yes/no).
                   6641: #
                   6642: #    
                   6643: sub photo_permission_handler {
                   6644:     my ($cmd, $tail, $client)   = @_;
                   6645:     my $userinput               = "$cmd:$tail";
                   6646:     my $cdom = $tail;
                   6647:     my ($perm_reqd,$conditions);
1.320     albertel 6648:     my $outcome;
                   6649:     eval {
                   6650: 	local($SIG{__DIE__})='DEFAULT';
                   6651: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
                   6652: 						  \$conditions);
                   6653:     };
                   6654:     if (!$@) {
                   6655: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
                   6656: 	       $userinput);
                   6657:     } else {
                   6658: 	&Failure($client,"unknown_cmd\n",$userinput);
                   6659:     }
                   6660:     return 1;
1.317     raeburn  6661: }
                   6662: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
                   6663: 
                   6664: #
                   6665: # Checks if student photo is available for a user in the domain, in the user's
                   6666: # directory (in /userfiles/internal/studentphoto.jpg).
                   6667: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
                   6668: # the student's photo.   
                   6669: 
                   6670: sub photo_check_handler {
                   6671:     my ($cmd, $tail, $client)   = @_;
                   6672:     my $userinput               = "$cmd:$tail";
                   6673:     my ($udom,$uname,$pid) = split(/:/,$tail);
                   6674:     $udom = &unescape($udom);
                   6675:     $uname = &unescape($uname);
                   6676:     $pid = &unescape($pid);
                   6677:     my $path=&propath($udom,$uname).'/userfiles/internal/';
                   6678:     if (!-e $path) {
                   6679:         &mkpath($path);
                   6680:     }
                   6681:     my $response;
                   6682:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
                   6683:     $result .= ':'.$response;
                   6684:     &Reply($client, &escape($result)."\n",$userinput);
1.320     albertel 6685:     return 1;
1.317     raeburn  6686: }
                   6687: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
                   6688: 
                   6689: #
                   6690: # Retrieve information from localenroll about whether to provide a button     
                   6691: # for users who have enbled import of student photos to initiate an 
                   6692: # update of photo files for registered students. Also include 
                   6693: # comment to display alongside button.  
                   6694: 
                   6695: sub photo_choice_handler {
                   6696:     my ($cmd, $tail, $client) = @_;
                   6697:     my $userinput             = "$cmd:$tail";
                   6698:     my $cdom                  = &unescape($tail);
1.320     albertel 6699:     my ($update,$comment);
                   6700:     eval {
                   6701: 	local($SIG{__DIE__})='DEFAULT';
                   6702: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
                   6703:     };
                   6704:     if (!$@) {
                   6705: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
                   6706:     } else {
                   6707: 	&Failure($client,"unknown_cmd\n",$userinput);
                   6708:     }
                   6709:     return 1;
1.317     raeburn  6710: }
                   6711: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
                   6712: 
1.265     albertel 6713: #
                   6714: # Gets a student's photo to exist (in the correct image type) in the user's 
                   6715: # directory.
                   6716: # Formal Parameters:
                   6717: #    $cmd     - The command request that got us dispatched.
                   6718: #    $tail    - A colon separated set of words that will be split into:
                   6719: #               $domain - student's domain
                   6720: #               $uname  - student username
                   6721: #               $type   - image type desired
                   6722: #    $client  - The socket open on the client.
                   6723: # Returns:
                   6724: #    1 - continue processing.
1.317     raeburn  6725: 
1.265     albertel 6726: sub student_photo_handler {
                   6727:     my ($cmd, $tail, $client) = @_;
1.317     raeburn  6728:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
1.265     albertel 6729: 
1.317     raeburn  6730:     my $path=&propath($domain,$uname). '/userfiles/internal/';
                   6731:     my $filename = 'studentphoto.'.$ext;
                   6732:     if ($type eq 'thumbnail') {
                   6733:         $filename = 'studentphoto_tn.'.$ext;
                   6734:     }
                   6735:     if (-e $path.$filename) {
1.265     albertel 6736: 	&Reply($client,"ok\n","$cmd:$tail");
                   6737: 	return 1;
                   6738:     }
                   6739:     &mkpath($path);
1.317     raeburn  6740:     my $file;
                   6741:     if ($type eq 'thumbnail') {
1.320     albertel 6742: 	eval {
                   6743: 	    local($SIG{__DIE__})='DEFAULT';
                   6744: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
                   6745: 	};
1.317     raeburn  6746:     } else {
                   6747:         $file=&localstudentphoto::fetch($domain,$uname);
                   6748:     }
1.265     albertel 6749:     if (!$file) {
                   6750: 	&Failure($client,"unavailable\n","$cmd:$tail");
                   6751: 	return 1;
                   6752:     }
1.317     raeburn  6753:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
                   6754:     if (-e $path.$filename) {
1.265     albertel 6755: 	&Reply($client,"ok\n","$cmd:$tail");
                   6756: 	return 1;
                   6757:     }
                   6758:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
                   6759:     return 1;
                   6760: }
                   6761: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246     foxr     6762: 
1.361     raeburn  6763: sub inst_usertypes_handler {
                   6764:     my ($cmd, $domain, $client) = @_;
                   6765:     my $res;
                   6766:     my $userinput = $cmd.":".$domain; # For logging purposes.
1.370     albertel 6767:     my (%typeshash,@order,$result);
                   6768:     eval {
                   6769: 	local($SIG{__DIE__})='DEFAULT';
                   6770: 	$result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
                   6771:     };
                   6772:     if ($result eq 'ok') {
1.361     raeburn  6773:         if (keys(%typeshash) > 0) {
                   6774:             foreach my $key (keys(%typeshash)) {
                   6775:                 $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
                   6776:             }
                   6777:         }
                   6778:         $res=~s/\&$//;
                   6779:         $res .= ':';
                   6780:         if (@order > 0) {
                   6781:             foreach my $item (@order) {
                   6782:                 $res .= &escape($item).'&';
                   6783:             }
                   6784:         }
                   6785:         $res=~s/\&$//;
                   6786:     }
1.387     albertel 6787:     &Reply($client, \$res, $userinput);
1.361     raeburn  6788:     return 1;
                   6789: }
                   6790: &register_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
                   6791: 
1.264     albertel 6792: # mkpath makes all directories for a file, expects an absolute path with a
                   6793: # file or a trailing / if just a dir is passed
                   6794: # returns 1 on success 0 on failure
                   6795: sub mkpath {
                   6796:     my ($file)=@_;
                   6797:     my @parts=split(/\//,$file,-1);
                   6798:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
                   6799:     for (my $i=3;$i<= ($#parts-1);$i++) {
1.265     albertel 6800: 	$now.='/'.$parts[$i]; 
1.264     albertel 6801: 	if (!-e $now) {
                   6802: 	    if  (!mkdir($now,0770)) { return 0; }
                   6803: 	}
                   6804:     }
                   6805:     return 1;
                   6806: }
                   6807: 
1.207     foxr     6808: #---------------------------------------------------------------
                   6809: #
                   6810: #   Getting, decoding and dispatching requests:
                   6811: #
                   6812: #
                   6813: #   Get a Request:
                   6814: #   Gets a Request message from the client.  The transaction
                   6815: #   is defined as a 'line' of text.  We remove the new line
                   6816: #   from the text line.  
1.226     foxr     6817: #
1.211     albertel 6818: sub get_request {
1.207     foxr     6819:     my $input = <$client>;
                   6820:     chomp($input);
1.226     foxr     6821: 
1.234     foxr     6822:     &Debug("get_request: Request = $input\n");
1.207     foxr     6823: 
                   6824:     &status('Processing '.$clientname.':'.$input);
                   6825: 
                   6826:     return $input;
                   6827: }
1.212     foxr     6828: #---------------------------------------------------------------
                   6829: #
                   6830: #  Process a request.  This sub should shrink as each action
                   6831: #  gets farmed out into a separat sub that is registered 
                   6832: #  with the dispatch hash.  
                   6833: #
                   6834: # Parameters:
                   6835: #    user_input   - The request received from the client (lonc).
1.525     raeburn  6836: #
1.212     foxr     6837: # Returns:
                   6838: #    true to keep processing, false if caller should exit.
                   6839: #
                   6840: sub process_request {
1.525     raeburn  6841:     my ($userinput) = @_; # Easier for now to break style than to
                   6842:                           # fix all the userinput -> user_input.
1.212     foxr     6843:     my $wasenc    = 0;		# True if request was encrypted.
                   6844: # ------------------------------------------------------------ See if encrypted
1.322     albertel 6845:     # for command
                   6846:     # sethost:<server>
                   6847:     # <command>:<args>
                   6848:     #   we just send it to the processor
                   6849:     # for
                   6850:     # sethost:<server>:<command>:<args>
                   6851:     #  we do the implict set host and then do the command
                   6852:     if ($userinput =~ /^sethost:/) {
                   6853: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
                   6854: 	if (defined($userinput)) {
                   6855: 	    &sethost("$cmd:$newid");
                   6856: 	} else {
                   6857: 	    $userinput = "$cmd:$newid";
                   6858: 	}
                   6859:     }
                   6860: 
1.212     foxr     6861:     if ($userinput =~ /^enc/) {
                   6862: 	$userinput = decipher($userinput);
                   6863: 	$wasenc=1;
                   6864: 	if(!$userinput) {	# Cipher not defined.
1.251     foxr     6865: 	    &Failure($client, "error: Encrypted data without negotated key\n");
1.212     foxr     6866: 	    return 0;
                   6867: 	}
                   6868:     }
                   6869:     Debug("process_request: $userinput\n");
                   6870:     
1.213     foxr     6871:     #  
                   6872:     #   The 'correct way' to add a command to lond is now to
                   6873:     #   write a sub to execute it and Add it to the command dispatch
                   6874:     #   hash via a call to register_handler..  The comments to that
                   6875:     #   sub should give you enough to go on to show how to do this
                   6876:     #   along with the examples that are building up as this code
                   6877:     #   is getting refactored.   Until all branches of the
                   6878:     #   if/elseif monster below have been factored out into
                   6879:     #   separate procesor subs, if the dispatch hash is missing
                   6880:     #   the command keyword, we will fall through to the remainder
                   6881:     #   of the if/else chain below in order to keep this thing in 
                   6882:     #   working order throughout the transmogrification.
                   6883: 
                   6884:     my ($command, $tail) = split(/:/, $userinput, 2);
                   6885:     chomp($command);
                   6886:     chomp($tail);
                   6887:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
1.214     foxr     6888:     $command =~ s/(\r)//;	# And this too for parameterless commands.
                   6889:     if(!$tail) {
                   6890: 	$tail ="";		# defined but blank.
                   6891:     }
1.213     foxr     6892: 
                   6893:     &Debug("Command received: $command, encoded = $wasenc");
                   6894: 
                   6895:     if(defined $Dispatcher{$command}) {
                   6896: 
                   6897: 	my $dispatch_info = $Dispatcher{$command};
                   6898: 	my $handler       = $$dispatch_info[0];
                   6899: 	my $need_encode   = $$dispatch_info[1];
                   6900: 	my $client_types  = $$dispatch_info[2];
                   6901: 	Debug("Matched dispatch hash: mustencode: $need_encode "
                   6902: 	      ."ClientType $client_types");
                   6903:       
                   6904: 	#  Validate the request:
                   6905:       
                   6906: 	my $ok = 1;
                   6907: 	my $requesterprivs = 0;
                   6908: 	if(&isClient()) {
                   6909: 	    $requesterprivs |= $CLIENT_OK;
                   6910: 	}
                   6911: 	if(&isManager()) {
                   6912: 	    $requesterprivs |= $MANAGER_OK;
                   6913: 	}
                   6914: 	if($need_encode && (!$wasenc)) {
                   6915: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
                   6916: 	    $ok = 0;
                   6917: 	}
                   6918: 	if(($client_types & $requesterprivs) == 0) {
                   6919: 	    Debug("Client not privileged to do this operation");
                   6920: 	    $ok = 0;
                   6921: 	}
1.525     raeburn  6922:         if ($ok) {
1.535     raeburn  6923:             my $realcommand = $command;
                   6924:             if ($command eq 'querysend') {
                   6925:                 my ($query,$rest)=split(/\:/,$tail,2);
                   6926:                 $query=~s/\n*$//g;
                   6927:                 my @possqueries = 
                   6928:                     qw(userlog courselog fetchenrollment institutionalphotos usersearch instdirsearch getinstuser getmultinstusers);
                   6929:                 if (grep(/^\Q$query\E$/,@possqueries)) {
                   6930:                     $command .= '_'.$query;
                   6931:                 } elsif ($query eq 'prepare activity log') {
                   6932:                     $command .= '_activitylog';
                   6933:                 }
                   6934:             }
1.525     raeburn  6935:             if (ref($trust{$command}) eq 'HASH') {
                   6936:                 my $donechecks;
                   6937:                 if ($trust{$command}{'anywhere'}) {
                   6938:                    $donechecks = 1;
                   6939:                 } elsif ($trust{$command}{'manageronly'}) {
                   6940:                     unless (&isManager()) {
                   6941:                         $ok = 0;
                   6942:                     }
                   6943:                     $donechecks = 1;
                   6944:                 } elsif ($trust{$command}{'institutiononly'}) {
                   6945:                     unless ($clientsameinst) {
                   6946:                         $ok = 0;
                   6947:                     }
                   6948:                     $donechecks = 1;
                   6949:                 } elsif ($clientsameinst) {
                   6950:                     $donechecks = 1;
                   6951:                 }
                   6952:                 unless ($donechecks) {
                   6953:                     foreach my $rule (keys(%{$trust{$command}})) {
                   6954:                         next if ($rule eq 'remote');
                   6955:                         if ($trust{$command}{$rule}) {
                   6956:                             if ($clientprohibited{$rule}) {
                   6957:                                 $ok = 0;
                   6958:                             } else {
                   6959:                                 $ok = 1;
                   6960:                                 $donechecks = 1;
                   6961:                                 last;
                   6962:                             }
                   6963:                         }
                   6964:                     }
                   6965:                 }
                   6966:                 unless ($donechecks) {
                   6967:                     if ($trust{$command}{'remote'}) {
                   6968:                         if ($clientremoteok) {
                   6969:                             $ok = 1;
                   6970:                         } else {
                   6971:                             $ok = 0;
                   6972:                         } 
                   6973:                     }
                   6974:                 }
                   6975:             }
1.535     raeburn  6976:             $command = $realcommand;
1.525     raeburn  6977:         }
1.213     foxr     6978: 
                   6979: 	if($ok) {
                   6980: 	    Debug("Dispatching to handler $command $tail");
                   6981: 	    my $keep_going = &$handler($command, $tail, $client);
                   6982: 	    return $keep_going;
                   6983: 	} else {
                   6984: 	    Debug("Refusing to dispatch because client did not match requirements");
                   6985: 	    Failure($client, "refused\n", $userinput);
                   6986: 	    return 1;
                   6987: 	}
1.525     raeburn  6988:     }
1.213     foxr     6989: 
1.262     foxr     6990:     print $client "unknown_cmd\n";
1.212     foxr     6991: # -------------------------------------------------------------------- complete
                   6992:     Debug("process_request - returning 1");
                   6993:     return 1;
                   6994: }
1.207     foxr     6995: #
                   6996: #   Decipher encoded traffic
                   6997: #  Parameters:
                   6998: #     input      - Encoded data.
                   6999: #  Returns:
                   7000: #     Decoded data or undef if encryption key was not yet negotiated.
                   7001: #  Implicit input:
                   7002: #     cipher  - This global holds the negotiated encryption key.
                   7003: #
1.211     albertel 7004: sub decipher {
1.207     foxr     7005:     my ($input)  = @_;
                   7006:     my $output = '';
1.212     foxr     7007:     
                   7008:     
1.207     foxr     7009:     if($cipher) {
                   7010: 	my($enc, $enclength, $encinput) = split(/:/, $input);
                   7011: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
                   7012: 	    $output .= 
                   7013: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
                   7014: 	}
                   7015: 	return substr($output, 0, $enclength);
                   7016:     } else {
                   7017: 	return undef;
                   7018:     }
                   7019: }
                   7020: 
                   7021: #
                   7022: #   Register a command processor.  This function is invoked to register a sub
                   7023: #   to process a request.  Once registered, the ProcessRequest sub can automatically
                   7024: #   dispatch requests to an appropriate sub, and do the top level validity checking
                   7025: #   as well:
                   7026: #    - Is the keyword recognized.
                   7027: #    - Is the proper client type attempting the request.
                   7028: #    - Is the request encrypted if it has to be.
                   7029: #   Parameters:
                   7030: #    $request_name         - Name of the request being registered.
                   7031: #                           This is the command request that will match
                   7032: #                           against the hash keywords to lookup the information
                   7033: #                           associated with the dispatch information.
                   7034: #    $procedure           - Reference to a sub to call to process the request.
                   7035: #                           All subs get called as follows:
                   7036: #                             Procedure($cmd, $tail, $replyfd, $key)
                   7037: #                             $cmd    - the actual keyword that invoked us.
                   7038: #                             $tail   - the tail of the request that invoked us.
                   7039: #                             $replyfd- File descriptor connected to the client
                   7040: #    $must_encode          - True if the request must be encoded to be good.
                   7041: #    $client_ok            - True if it's ok for a client to request this.
                   7042: #    $manager_ok           - True if it's ok for a manager to request this.
                   7043: # Side effects:
                   7044: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
                   7045: #      - On failure, the program will die as it's a bad internal bug to try to 
                   7046: #        register a duplicate command handler.
                   7047: #
1.211     albertel 7048: sub register_handler {
1.212     foxr     7049:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
1.207     foxr     7050: 
                   7051:     #  Don't allow duplication#
                   7052:    
                   7053:     if (defined $Dispatcher{$request_name}) {
                   7054: 	die "Attempting to define a duplicate request handler for $request_name\n";
                   7055:     }
                   7056:     #   Build the client type mask:
                   7057:     
                   7058:     my $client_type_mask = 0;
                   7059:     if($client_ok) {
                   7060: 	$client_type_mask  |= $CLIENT_OK;
                   7061:     }
                   7062:     if($manager_ok) {
                   7063: 	$client_type_mask  |= $MANAGER_OK;
                   7064:     }
                   7065:    
                   7066:     #  Enter the hash:
                   7067:       
                   7068:     my @entry = ($procedure, $must_encode, $client_type_mask);
                   7069:    
                   7070:     $Dispatcher{$request_name} = \@entry;
                   7071:    
                   7072: }
                   7073: 
                   7074: 
                   7075: #------------------------------------------------------------------
                   7076: 
                   7077: 
                   7078: 
                   7079: 
1.141     foxr     7080: #
1.96      foxr     7081: #  Convert an error return code from lcpasswd to a string value.
                   7082: #
                   7083: sub lcpasswdstrerror {
                   7084:     my $ErrorCode = shift;
1.97      foxr     7085:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     7086: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   7087:     } else {
1.98      foxr     7088: 	return $passwderrors[$ErrorCode];
1.96      foxr     7089:     }
                   7090: }
                   7091: 
1.23      harris41 7092: # grabs exception and records it to log before exiting
                   7093: sub catchexception {
1.27      albertel 7094:     my ($error)=@_;
1.25      www      7095:     $SIG{'QUIT'}='DEFAULT';
                   7096:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 7097:     &status("Catching exception");
1.190     albertel 7098:     &logthis("<font color='red'>CRITICAL: "
1.373     albertel 7099:      ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
1.27      albertel 7100:      ."a crash with this error msg->[$error]</font>");
1.57      www      7101:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 7102:     if ($client) { print $client "error: $error\n"; }
1.59      www      7103:     $server->close();
1.27      albertel 7104:     die($error);
1.23      harris41 7105: }
1.63      www      7106: sub timeout {
1.165     albertel 7107:     &status("Handling Timeout");
1.190     albertel 7108:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63      www      7109:     &catchexception('Timeout');
                   7110: }
1.22      harris41 7111: # -------------------------------- Set signal handlers to record abnormal exits
                   7112: 
1.226     foxr     7113: 
1.22      harris41 7114: $SIG{'QUIT'}=\&catchexception;
                   7115: $SIG{__DIE__}=\&catchexception;
                   7116: 
1.81      matthew  7117: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 7118: &status("Read loncapa.conf and loncapa_apache.conf");
                   7119: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     7120: %perlvar=%{$perlvarref};
1.80      harris41 7121: undef $perlvarref;
1.19      www      7122: 
1.35      harris41 7123: # ----------------------------- Make sure this process is running from user=www
                   7124: my $wwwid=getpwnam('www');
                   7125: if ($wwwid!=$<) {
1.134     albertel 7126:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   7127:    my $subj="LON: $currenthostid User ID mismatch";
1.550     raeburn  7128:    system("echo 'User ID mismatch.  lond must be run as user www.' |".
                   7129:           " mail -s '$subj' $emailto > /dev/null");
1.35      harris41 7130:    exit 1;
                   7131: }
                   7132: 
1.19      www      7133: # --------------------------------------------- Check if other instance running
                   7134: 
                   7135: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   7136: 
                   7137: if (-e $pidfile) {
                   7138:    my $lfh=IO::File->new("$pidfile");
                   7139:    my $pide=<$lfh>;
                   7140:    chomp($pide);
1.29      harris41 7141:    if (kill 0 => $pide) { die "already running"; }
1.19      www      7142: }
1.1       albertel 7143: 
                   7144: # ------------------------------------------------------------- Read hosts file
                   7145: 
                   7146: 
                   7147: 
                   7148: # establish SERVER socket, bind and listen.
                   7149: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   7150:                                 Type      => SOCK_STREAM,
                   7151:                                 Proto     => 'tcp',
1.469     foxr     7152:                                 ReuseAddr     => 1,
1.1       albertel 7153:                                 Listen    => 10 )
1.29      harris41 7154:   or die "making socket: $@\n";
1.1       albertel 7155: 
                   7156: # --------------------------------------------------------- Do global variables
                   7157: 
                   7158: # global variables
                   7159: 
1.134     albertel 7160: my %children               = ();       # keys are current child process IDs
1.1       albertel 7161: 
                   7162: sub REAPER {                        # takes care of dead children
                   7163:     $SIG{CHLD} = \&REAPER;
1.165     albertel 7164:     &status("Handling child death");
1.178     foxr     7165:     my $pid;
                   7166:     do {
                   7167: 	$pid = waitpid(-1,&WNOHANG());
                   7168: 	if (defined($children{$pid})) {
                   7169: 	    &logthis("Child $pid died");
                   7170: 	    delete($children{$pid});
1.183     albertel 7171: 	} elsif ($pid > 0) {
1.178     foxr     7172: 	    &logthis("Unknown Child $pid died");
                   7173: 	}
                   7174:     } while ( $pid > 0 );
                   7175:     foreach my $child (keys(%children)) {
                   7176: 	$pid = waitpid($child,&WNOHANG());
                   7177: 	if ($pid > 0) {
                   7178: 	    &logthis("Child $child - $pid looks like we missed it's death");
                   7179: 	    delete($children{$pid});
                   7180: 	}
1.176     albertel 7181:     }
1.165     albertel 7182:     &status("Finished Handling child death");
1.1       albertel 7183: }
                   7184: 
                   7185: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 7186:     &status("Killing children (INT)");
1.1       albertel 7187:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   7188:     kill 'INT' => keys %children;
1.59      www      7189:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 7190:     my $execdir=$perlvar{'lonDaemons'};
                   7191:     unlink("$execdir/logs/lond.pid");
1.190     albertel 7192:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165     albertel 7193:     &status("Done killing children");
1.1       albertel 7194:     exit;                           # clean up with dignity
                   7195: }
                   7196: 
                   7197: sub HUPSMAN {                      # signal handler for SIGHUP
                   7198:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 7199:     &status("Killing children for restart (HUP)");
1.1       albertel 7200:     kill 'INT' => keys %children;
1.59      www      7201:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190     albertel 7202:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134     albertel 7203:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 7204:     unlink("$execdir/logs/lond.pid");
1.165     albertel 7205:     &status("Restarting self (HUP)");
1.1       albertel 7206:     exec("$execdir/lond");         # here we go again
                   7207: }
                   7208: 
1.144     foxr     7209: #
1.148     foxr     7210: #  Reload the Apache daemon's state.
1.150     foxr     7211: #  This is done by invoking /home/httpd/perl/apachereload
                   7212: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     7213: #
                   7214: sub ReloadApache {
1.473     raeburn  7215: # --------------------------- Handle case of another apachereload process (locking)
1.474     raeburn  7216:     if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
                   7217:         my $execdir = $perlvar{'lonDaemons'};
                   7218:         my $script  = $execdir."/apachereload";
                   7219:         system($script);
                   7220:         unlink('/tmp/lock_apachereload'); #  Remove the lock file.
                   7221:     }
1.148     foxr     7222: }
                   7223: 
                   7224: #
1.144     foxr     7225: #   Called in response to a USR2 signal.
                   7226: #   - Reread hosts.tab
                   7227: #   - All children connected to hosts that were removed from hosts.tab
                   7228: #     are killed via SIGINT
                   7229: #   - All children connected to previously existing hosts are sent SIGUSR1
                   7230: #   - Our internal hosts hash is updated to reflect the new contents of
                   7231: #     hosts.tab causing connections from hosts added to hosts.tab to
                   7232: #     now be honored.
                   7233: #
                   7234: sub UpdateHosts {
1.165     albertel 7235:     &status("Reload hosts.tab");
1.147     foxr     7236:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     7237:     #
                   7238:     #  The %children hash has the set of IP's we currently have children
                   7239:     #  on.  These need to be matched against records in the hosts.tab
                   7240:     #  Any ip's no longer in the table get killed off they correspond to
                   7241:     #  either dropped or changed hosts.  Note that the re-read of the table
                   7242:     #  will take care of new and changed hosts as connections come into being.
                   7243: 
1.371     albertel 7244:     &Apache::lonnet::reset_hosts_info();
1.532     raeburn  7245:     my %active;
1.148     foxr     7246: 
1.368     albertel 7247:     foreach my $child (keys(%children)) {
1.148     foxr     7248: 	my $childip = $children{$child};
1.374     albertel 7249: 	if ($childip ne '127.0.0.1'
                   7250: 	    && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
1.149     foxr     7251: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   7252: 		    ." $child for ip $childip </font>");
1.148     foxr     7253: 	    kill('INT', $child);
1.149     foxr     7254: 	} else {
1.532     raeburn  7255:             $active{$child} = $childip;
1.149     foxr     7256: 	    logthis('<font color="green"> keeping child for ip '
                   7257: 		    ." $childip (pid=$child) </font>");
1.148     foxr     7258: 	}
                   7259:     }
1.532     raeburn  7260: 
                   7261:     my %oldconf = %secureconf;
                   7262:     my %connchange;
1.555     raeburn  7263:     if (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
1.545     raeburn  7264:         logthis('<font color="blue"> Reloaded SSL connection rules and cleared CRL checking history </font>');
1.532     raeburn  7265:     } else {
1.545     raeburn  7266:         logthis('<font color="yellow"> Failed to reload SSL connection rules and clear CRL checking history </font>');
1.532     raeburn  7267:     }
                   7268:     if ((ref($oldconf{'connfrom'}) eq 'HASH') && (ref($secureconf{'connfrom'}) eq 'HASH')) {
                   7269:         foreach my $type ('dom','intdom','other') {
                   7270:             if ((($oldconf{'connfrom'}{$type} eq 'no') && ($secureconf{'connfrom'}{$type} eq 'req')) ||
                   7271:                 (($oldconf{'connfrom'}{$type} eq 'req') && ($secureconf{'connfrom'}{$type} eq 'no'))) {
                   7272:                 $connchange{$type} = 1;
                   7273:             }
                   7274:         }
                   7275:     }
                   7276:     if (keys(%connchange)) {
                   7277:         foreach my $child (keys(%active)) {
                   7278:             my $childip = $active{$child};
                   7279:             if ($childip ne '127.0.0.1') {
                   7280:                 my $childhostname  = gethostbyaddr(Socket::inet_aton($childip),AF_INET);
                   7281:                 if ($childhostname ne '') {
                   7282:                     my $childlonhost = &Apache::lonnet::get_server_homeID($childhostname);
                   7283:                     my ($samedom,$sameinst) = &set_client_info($childlonhost);
                   7284:                     if ($samedom) {
                   7285:                         if ($connchange{'dom'}) {
                   7286:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7287:                                    ." $child for ip $childip </font>");
                   7288:                             kill('INT', $child);
                   7289:                         }
                   7290:                     } elsif ($sameinst) {
                   7291:                         if ($connchange{'intdom'}) {
                   7292:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7293:                                    ." $child for ip $childip </font>");
                   7294:                            kill('INT', $child);
                   7295:                         }
                   7296:                     } else {
                   7297:                         if ($connchange{'other'}) {
                   7298:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7299:                                    ." $child for ip $childip </font>");
                   7300:                             kill('INT', $child);
                   7301:                         }
                   7302:                     }
                   7303:                 }
                   7304:             }
                   7305:         }
                   7306:     }
1.148     foxr     7307:     ReloadApache;
1.165     albertel 7308:     &status("Finished reloading hosts.tab");
1.144     foxr     7309: }
                   7310: 
1.57      www      7311: sub checkchildren {
1.165     albertel 7312:     &status("Checking on the children (sending signals)");
1.57      www      7313:     &initnewstatus();
                   7314:     &logstatus();
                   7315:     &logthis('Going to check on the children');
1.134     albertel 7316:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 7317:     foreach (sort keys %children) {
1.221     albertel 7318: 	#sleep 1;
1.57      www      7319:         unless (kill 'USR1' => $_) {
                   7320: 	    &logthis ('Child '.$_.' is dead');
                   7321:             &logstatus($$.' is dead');
1.221     albertel 7322: 	    delete($children{$_});
1.57      www      7323:         } 
1.61      harris41 7324:     }
1.63      www      7325:     sleep 5;
1.212     foxr     7326:     $SIG{ALRM} = sub { Debug("timeout"); 
                   7327: 		       die "timeout";  };
1.113     albertel 7328:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 7329:     &status("Checking on the children (waiting for reports)");
1.63      www      7330:     foreach (sort keys %children) {
                   7331:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 7332:           eval {
                   7333:             alarm(300);
1.63      www      7334: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 7335: 	    kill 9 => $_;
1.131     albertel 7336: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   7337: 	    #$subj="LON: $currenthostid killed lond process $_";
                   7338: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   7339: 	    #$execdir=$perlvar{'lonDaemons'};
                   7340: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221     albertel 7341: 	    delete($children{$_});
1.113     albertel 7342: 	    alarm(0);
                   7343: 	  }
1.63      www      7344:         }
                   7345:     }
1.113     albertel 7346:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 7347:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 7348:     &status("Finished checking children");
1.221     albertel 7349:     &logthis('Finished Checking children');
1.57      www      7350: }
                   7351: 
1.1       albertel 7352: # --------------------------------------------------------------------- Logging
                   7353: 
                   7354: sub logthis {
                   7355:     my $message=shift;
                   7356:     my $execdir=$perlvar{'lonDaemons'};
                   7357:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   7358:     my $now=time;
                   7359:     my $local=localtime($now);
1.58      www      7360:     $lastlog=$local.': '.$message;
1.1       albertel 7361:     print $fh "$local ($$): $message\n";
                   7362: }
                   7363: 
1.77      foxr     7364: # ------------------------- Conditional log if $DEBUG true.
                   7365: sub Debug {
                   7366:     my $message = shift;
                   7367:     if($DEBUG) {
                   7368: 	&logthis($message);
                   7369:     }
                   7370: }
1.161     foxr     7371: 
                   7372: #
                   7373: #   Sub to do replies to client.. this gives a hook for some
                   7374: #   debug tracing too:
                   7375: #  Parameters:
                   7376: #     fd      - File open on client.
                   7377: #     reply   - Text to send to client.
                   7378: #     request - Original request from client.
                   7379: #
1.490     droeschl 7380: #NOTE $reply must be terminated by exactly *one* \n. If $reply is a reference
                   7381: #this is done automatically ($$reply must not contain any \n in this case). 
                   7382: #If $reply is a string the caller has to ensure this.
1.161     foxr     7383: sub Reply {
1.192     foxr     7384:     my ($fd, $reply, $request) = @_;
1.387     albertel 7385:     if (ref($reply)) {
                   7386: 	print $fd $$reply;
                   7387: 	print $fd "\n";
                   7388: 	if ($DEBUG) { Debug("Request was $request  Reply was $$reply"); }
                   7389:     } else {
                   7390: 	print $fd $reply;
                   7391: 	if ($DEBUG) { Debug("Request was $request  Reply was $reply"); }
                   7392:     }
1.212     foxr     7393:     $Transactions++;
                   7394: }
                   7395: 
                   7396: 
                   7397: #
                   7398: #    Sub to report a failure.
                   7399: #    This function:
                   7400: #     -   Increments the failure statistic counters.
                   7401: #     -   Invokes Reply to send the error message to the client.
                   7402: # Parameters:
                   7403: #    fd       - File descriptor open on the client
                   7404: #    reply    - Reply text to emit.
                   7405: #    request  - The original request message (used by Reply
                   7406: #               to debug if that's enabled.
                   7407: # Implicit outputs:
                   7408: #    $Failures- The number of failures is incremented.
                   7409: #    Reply (invoked here) sends a message to the 
                   7410: #    client:
                   7411: #
                   7412: sub Failure {
                   7413:     my $fd      = shift;
                   7414:     my $reply   = shift;
                   7415:     my $request = shift;
                   7416:    
                   7417:     $Failures++;
                   7418:     Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     7419: }
1.57      www      7420: # ------------------------------------------------------------------ Log status
                   7421: 
                   7422: sub logstatus {
1.178     foxr     7423:     &status("Doing logging");
                   7424:     my $docdir=$perlvar{'lonDocRoot'};
                   7425:     {
                   7426: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200     matthew  7427:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178     foxr     7428:         $fh->close();
                   7429:     }
1.221     albertel 7430:     &status("Finished $$.txt");
                   7431:     {
                   7432: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
                   7433: 	flock(LOG,LOCK_EX);
                   7434: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
                   7435: 	    .$status."\t".$lastlog."\t $keymode\n";
1.275     albertel 7436: 	flock(LOG,LOCK_UN);
1.221     albertel 7437: 	close(LOG);
                   7438:     }
1.178     foxr     7439:     &status("Finished logging");
1.57      www      7440: }
                   7441: 
                   7442: sub initnewstatus {
                   7443:     my $docdir=$perlvar{'lonDocRoot'};
                   7444:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
1.460     foxr     7445:     my $now=time();
1.57      www      7446:     my $local=localtime($now);
                   7447:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      7448:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 7449:     while (my $filename=readdir(DIR)) {
1.64      www      7450:         unlink("$docdir/lon-status/londchld/$filename");
                   7451:     }
                   7452:     closedir(DIR);
1.57      www      7453: }
                   7454: 
                   7455: # -------------------------------------------------------------- Status setting
                   7456: 
                   7457: sub status {
                   7458:     my $what=shift;
                   7459:     my $now=time;
                   7460:     my $local=localtime($now);
1.178     foxr     7461:     $status=$local.': '.$what;
                   7462:     $0='lond: '.$what.' '.$local;
1.57      www      7463: }
1.11      www      7464: 
1.13      www      7465: # -------------------------------------------------------------- Talk to lonsql
                   7466: 
1.234     foxr     7467: sub sql_reply {
1.12      harris41 7468:     my ($cmd)=@_;
1.234     foxr     7469:     my $answer=&sub_sql_reply($cmd);
                   7470:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12      harris41 7471:     return $answer;
                   7472: }
                   7473: 
1.234     foxr     7474: sub sub_sql_reply {
1.12      harris41 7475:     my ($cmd)=@_;
                   7476:     my $unixsock="mysqlsock";
                   7477:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   7478:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   7479:                                       Type    => SOCK_STREAM,
                   7480:                                       Timeout => 10)
                   7481:        or return "con_lost";
1.319     www      7482:     print $sclient "$cmd:$currentdomainid\n";
1.12      harris41 7483:     my $answer=<$sclient>;
                   7484:     chomp($answer);
                   7485:     if (!$answer) { $answer="con_lost"; }
                   7486:     return $answer;
                   7487: }
                   7488: 
1.1       albertel 7489: # --------------------------------------- Is this the home server of an author?
1.11      www      7490: 
1.1       albertel 7491: sub ishome {
                   7492:     my $author=shift;
                   7493:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   7494:     my ($udom,$uname)=split(/\//,$author);
                   7495:     my $proname=propath($udom,$uname);
                   7496:     if (-e $proname) {
                   7497: 	return 'owner';
                   7498:     } else {
                   7499:         return 'not_owner';
                   7500:     }
                   7501: }
                   7502: 
                   7503: # ======================================================= Continue main program
                   7504: # ---------------------------------------------------- Fork once and dissociate
                   7505: 
1.134     albertel 7506: my $fpid=fork;
1.1       albertel 7507: exit if $fpid;
1.29      harris41 7508: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 7509: 
1.29      harris41 7510: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 7511: 
                   7512: # ------------------------------------------------------- Write our PID on disk
                   7513: 
1.134     albertel 7514: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 7515: open (PIDSAVE,">$execdir/logs/lond.pid");
                   7516: print PIDSAVE "$$\n";
                   7517: close(PIDSAVE);
1.190     albertel 7518: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57      www      7519: &status('Starting');
1.1       albertel 7520: 
1.106     foxr     7521: 
1.1       albertel 7522: 
                   7523: # ----------------------------------------------------- Install signal handlers
                   7524: 
1.57      www      7525: 
1.1       albertel 7526: $SIG{CHLD} = \&REAPER;
                   7527: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   7528: $SIG{HUP}  = \&HUPSMAN;
1.57      www      7529: $SIG{USR1} = \&checkchildren;
1.144     foxr     7530: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     7531: 
1.148     foxr     7532: #  Read the host hashes:
1.368     albertel 7533: &Apache::lonnet::load_hosts_tab();
1.447     raeburn  7534: my %iphost = &Apache::lonnet::get_iphost(1);
1.106     foxr     7535: 
1.480     raeburn  7536: $dist=`$perlvar{'lonDaemons'}/distprobe`;
1.286     albertel 7537: 
1.471     raeburn  7538: my $arch = `uname -i`;
1.475     raeburn  7539: chomp($arch);
1.471     raeburn  7540: if ($arch eq 'unknown') {
                   7541:     $arch = `uname -m`;
1.475     raeburn  7542:     chomp($arch);
1.471     raeburn  7543: }
                   7544: 
1.555     raeburn  7545: unless (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
1.532     raeburn  7546:     &logthis('<font color="blue">No connectionrules table. Will fallback to loncapa.conf</font>');
                   7547: }
                   7548: 
1.106     foxr     7549: # --------------------------------------------------------------
                   7550: #   Accept connections.  When a connection comes in, it is validated
                   7551: #   and if good, a child process is created to process transactions
                   7552: #   along the connection.
                   7553: 
1.1       albertel 7554: while (1) {
1.165     albertel 7555:     &status('Starting accept');
1.106     foxr     7556:     $client = $server->accept() or next;
1.165     albertel 7557:     &status('Accepted '.$client.' off to spawn');
1.386     albertel 7558:     make_new_child($client);
1.165     albertel 7559:     &status('Finished spawning');
1.1       albertel 7560: }
                   7561: 
1.212     foxr     7562: sub make_new_child {
                   7563:     my $pid;
                   7564: #    my $cipher;     # Now global
                   7565:     my $sigset;
1.178     foxr     7566: 
1.212     foxr     7567:     $client = shift;
                   7568:     &status('Starting new child '.$client);
                   7569:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   7570: 	     ")</font>");    
                   7571:     # block signal for fork
                   7572:     $sigset = POSIX::SigSet->new(SIGINT);
                   7573:     sigprocmask(SIG_BLOCK, $sigset)
                   7574:         or die "Can't block SIGINT for fork: $!\n";
1.178     foxr     7575: 
1.212     foxr     7576:     die "fork: $!" unless defined ($pid = fork);
1.178     foxr     7577: 
1.212     foxr     7578:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   7579: 	                               # connection liveness.
1.178     foxr     7580: 
1.212     foxr     7581:     #
                   7582:     #  Figure out who we're talking to so we can record the peer in 
                   7583:     #  the pid hash.
                   7584:     #
                   7585:     my $caller = getpeername($client);
                   7586:     my ($port,$iaddr);
                   7587:     if (defined($caller) && length($caller) > 0) {
                   7588: 	($port,$iaddr)=unpack_sockaddr_in($caller);
                   7589:     } else {
                   7590: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
                   7591:     }
                   7592:     if (defined($iaddr)) {
                   7593: 	$clientip  = inet_ntoa($iaddr);
                   7594: 	Debug("Connected with $clientip");
                   7595:     } else {
                   7596: 	&logthis("Unable to determine clientip");
                   7597: 	$clientip='Unavailable';
                   7598:     }
                   7599:     
                   7600:     if ($pid) {
                   7601:         # Parent records the child's birth and returns.
                   7602:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7603:             or die "Can't unblock SIGINT for fork: $!\n";
                   7604:         $children{$pid} = $clientip;
                   7605:         &status('Started child '.$pid);
1.462     foxr     7606: 	close($client);
1.212     foxr     7607:         return;
                   7608:     } else {
                   7609:         # Child can *not* return from this subroutine.
                   7610:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                   7611:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   7612:                                 #don't get intercepted
                   7613:         $SIG{USR1}= \&logstatus;
                   7614:         $SIG{ALRM}= \&timeout;
1.468     foxr     7615: 	#
                   7616: 	# Block sigpipe as it gets thrownon socket disconnect and we want to 
                   7617: 	# deal with that as a read faiure instead.
                   7618: 	#
                   7619: 	my $blockset = POSIX::SigSet->new(SIGPIPE);
                   7620: 	sigprocmask(SIG_BLOCK, $blockset);
                   7621: 
1.212     foxr     7622:         $lastlog='Forked ';
                   7623:         $status='Forked';
1.178     foxr     7624: 
1.212     foxr     7625:         # unblock signals
                   7626:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7627:             or die "Can't unblock SIGINT for fork: $!\n";
1.178     foxr     7628: 
1.212     foxr     7629: #        my $tmpsnum=0;            # Now global
                   7630: #---------------------------------------------------- kerberos 5 initialization
                   7631:         &Authen::Krb5::init_context();
1.511     raeburn  7632: 
                   7633:         my $no_ets;
1.559     raeburn  7634:         if ($dist =~ /^(?:centos|rhes|scientific|oracle)(\d+)$/) {
1.511     raeburn  7635:             if ($1 >= 7) {
                   7636:                 $no_ets = 1;
                   7637:             }
                   7638:         } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
                   7639:             if (($1 eq '9.3') || ($1 >= 12.2)) {
                   7640:                 $no_ets = 1; 
                   7641:             }
1.514     raeburn  7642:         } elsif ($dist =~ /^sles(\d+)$/) {
                   7643:             if ($1 > 11) {
                   7644:                 $no_ets = 1;
                   7645:             }
1.511     raeburn  7646:         } elsif ($dist =~ /^fedora(\d+)$/) {
                   7647:             if ($1 < 7) {
                   7648:                 $no_ets = 1;
                   7649:             }
                   7650:         }
                   7651:         unless ($no_ets) {
1.286     albertel 7652: 	    &Authen::Krb5::init_ets();
                   7653: 	}
1.209     albertel 7654: 
1.212     foxr     7655: 	&status('Accepted connection');
                   7656: # =============================================================================
                   7657:             # do something with the connection
                   7658: # -----------------------------------------------------------------------------
                   7659: 	# see if we know client and 'check' for spoof IP by ineffective challenge
1.178     foxr     7660: 
1.278     albertel 7661: 	my $outsideip=$clientip;
                   7662: 	if ($clientip eq '127.0.0.1') {
1.368     albertel 7663: 	    $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
1.278     albertel 7664: 	}
1.412     foxr     7665: 	&ReadManagerTable();
1.368     albertel 7666: 	my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
1.278     albertel 7667: 	my $ismanager=($managers{$outsideip}    ne undef);
1.432     raeburn  7668: 	$clientname  = "[unknown]";
1.212     foxr     7669: 	if($clientrec) {	# Establish client type.
                   7670: 	    $ConnectionType = "client";
1.368     albertel 7671: 	    $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
1.212     foxr     7672: 	    if($ismanager) {
                   7673: 		$ConnectionType = "both";
                   7674: 	    }
                   7675: 	} else {
                   7676: 	    $ConnectionType = "manager";
1.278     albertel 7677: 	    $clientname = $managers{$outsideip};
1.212     foxr     7678: 	}
1.556     raeburn  7679: 	my $clientok;
1.178     foxr     7680: 
1.212     foxr     7681: 	if ($clientrec || $ismanager) {
                   7682: 	    &status("Waiting for init from $clientip $clientname");
                   7683: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   7684: 		     $clientip.
                   7685: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   7686: 	    &status("Connecting $clientip  ($clientname))"); 
                   7687: 	    my $remotereq=<$client>;
                   7688: 	    chomp($remotereq);
                   7689: 	    Debug("Got init: $remotereq");
1.337     albertel 7690: 
1.212     foxr     7691: 	    if ($remotereq =~ /^init/) {
                   7692: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   7693: 		#
                   7694: 		#  If the remote is attempting a local init... give that a try:
                   7695: 		#
1.432     raeburn  7696: 		(my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
1.492     droeschl 7697:         # For LON-CAPA 2.9, the  client session will have sent its LON-CAPA
                   7698:         # version when initiating the connection. For LON-CAPA 2.8 and older,
                   7699:         # the version is retrieved from the global %loncaparevs in lonnet.pm.            
1.494     droeschl 7700:         # $clientversion contains path to keyfile if $inittype eq 'local'
                   7701:         # it's overridden below in this case
1.492     droeschl 7702:         $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
1.209     albertel 7703: 
1.212     foxr     7704: 		# If the connection type is ssl, but I didn't get my
                   7705: 		# certificate files yet, then I'll drop  back to 
                   7706: 		# insecure (if allowed).
1.532     raeburn  7707: 
                   7708:                 if ($inittype eq "ssl") {
                   7709:                     my $context;
                   7710:                     if ($clientsamedom) {
                   7711:                         $context = 'dom';
                   7712:                         if ($secureconf{'connfrom'}{'dom'} eq 'no') {
                   7713:                             $inittype = "";
                   7714:                         }
                   7715:                     } elsif ($clientsameinst) {
                   7716:                         $context = 'intdom';
                   7717:                         if ($secureconf{'connfrom'}{'intdom'} eq 'no') {
                   7718:                             $inittype = "";
                   7719:                         }
                   7720:                     } else {
                   7721:                         $context = 'other';
                   7722:                         if ($secureconf{'connfrom'}{'other'} eq 'no') {
                   7723:                             $inittype = "";
                   7724:                         }
                   7725:                     }
                   7726:                     if ($inittype eq '') {
                   7727:                         &logthis("<font color=\"blue\"> Domain config set "
                   7728:                                 ."to no ssl for $clientname (context: $context)"
                   7729:                                 ." -- trying insecure auth</font>");
                   7730:                     }
                   7731:                 }
                   7732: 
1.212     foxr     7733: 		if($inittype eq "ssl") {
                   7734: 		    my ($ca, $cert) = lonssl::CertificateFile;
                   7735: 		    my $kfile       = lonssl::KeyFile;
                   7736: 		    if((!$ca)   || 
                   7737: 		       (!$cert) || 
                   7738: 		       (!$kfile)) {
                   7739: 			$inittype = ""; # This forces insecure attempt.
                   7740: 			&logthis("<font color=\"blue\"> Certificates not "
                   7741: 				 ."installed -- trying insecure auth</font>");
1.224     foxr     7742: 		    } else {	# SSL certificates are in place so
1.212     foxr     7743: 		    }		# Leave the inittype alone.
                   7744: 		}
                   7745: 
                   7746: 		if($inittype eq "local") {
1.432     raeburn  7747:                     $clientversion = $perlvar{'lonVersion'};
1.212     foxr     7748: 		    my $key = LocalConnection($client, $remotereq);
                   7749: 		    if($key) {
                   7750: 			Debug("Got local key $key");
                   7751: 			$clientok     = 1;
                   7752: 			my $cipherkey = pack("H32", $key);
                   7753: 			$cipher       = new IDEA($cipherkey);
                   7754: 			print $client "ok:local\n";
1.442     www      7755: 			&logthis('<font color="green">'
1.212     foxr     7756: 				 . "Successful local authentication </font>");
                   7757: 			$keymode = "local"
1.178     foxr     7758: 		    } else {
1.212     foxr     7759: 			Debug("Failed to get local key");
                   7760: 			$clientok = 0;
                   7761: 			shutdown($client, 3);
                   7762: 			close $client;
1.178     foxr     7763: 		    }
1.212     foxr     7764: 		} elsif ($inittype eq "ssl") {
1.532     raeburn  7765: 		    my $key = SSLConnection($client,$clientname);
1.212     foxr     7766: 		    if ($key) {
                   7767: 			$clientok = 1;
                   7768: 			my $cipherkey = pack("H32", $key);
                   7769: 			$cipher       = new IDEA($cipherkey);
                   7770: 			&logthis('<font color="green">'
                   7771: 				 ."Successfull ssl authentication with $clientname </font>");
                   7772: 			$keymode = "ssl";
                   7773: 	     
1.178     foxr     7774: 		    } else {
1.212     foxr     7775: 			$clientok = 0;
                   7776: 			close $client;
1.178     foxr     7777: 		    }
1.212     foxr     7778: 	   
                   7779: 		} else {
                   7780: 		    my $ok = InsecureConnection($client);
                   7781: 		    if($ok) {
                   7782: 			$clientok = 1;
                   7783: 			&logthis('<font color="green">'
                   7784: 				 ."Successful insecure authentication with $clientname </font>");
                   7785: 			print $client "ok\n";
                   7786: 			$keymode = "insecure";
1.178     foxr     7787: 		    } else {
1.212     foxr     7788: 			&logthis('<font color="yellow">'
                   7789: 				  ."Attempted insecure connection disallowed </font>");
                   7790: 			close $client;
                   7791: 			$clientok = 0;
1.178     foxr     7792: 		    }
                   7793: 		}
1.212     foxr     7794: 	    } else {
                   7795: 		&logthis(
                   7796: 			 "<font color='blue'>WARNING: "
                   7797: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   7798: 		&status('No init '.$clientip);
                   7799: 	    }
                   7800: 	} else {
                   7801: 	    &logthis(
                   7802: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
                   7803: 	    &status('Hung up on '.$clientip);
                   7804: 	}
                   7805:  
                   7806: 	if ($clientok) {
                   7807: # ---------------- New known client connecting, could mean machine online again
1.368     albertel 7808: 	    if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip 
1.367     albertel 7809: 		&& $clientip ne '127.0.0.1') {
1.375     albertel 7810: 		&Apache::lonnet::reconlonc($clientname);
1.212     foxr     7811: 	    }
                   7812: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
                   7813: 	    &status('Will listen to '.$clientname);
                   7814: # ------------------------------------------------------------ Process requests
                   7815: 	    my $keep_going = 1;
                   7816: 	    my $user_input;
1.556     raeburn  7817: 
1.212     foxr     7818: 	    while(($user_input = get_request) && $keep_going) {
                   7819: 		alarm(120);
                   7820: 		Debug("Main: Got $user_input\n");
                   7821: 		$keep_going = &process_request($user_input);
1.178     foxr     7822: 		alarm(0);
1.212     foxr     7823: 		&status('Listening to '.$clientname." ($keymode)");	   
1.161     foxr     7824: 	    }
1.212     foxr     7825: 
1.59      www      7826: # --------------------------------------------- client unknown or fishy, refuse
1.212     foxr     7827: 	}  else {
1.161     foxr     7828: 	    print $client "refused\n";
                   7829: 	    $client->close();
1.190     albertel 7830: 	    &logthis("<font color='blue'>WARNING: "
1.161     foxr     7831: 		     ."Rejected client $clientip, closing connection</font>");
                   7832: 	}
1.525     raeburn  7833:     }
1.161     foxr     7834:     
1.1       albertel 7835: # =============================================================================
1.161     foxr     7836:     
1.190     albertel 7837:     &logthis("<font color='red'>CRITICAL: "
1.161     foxr     7838: 	     ."Disconnect from $clientip ($clientname)</font>");    
                   7839:     
                   7840:     
                   7841:     # this exit is VERY important, otherwise the child will become
                   7842:     # a producer of more and more children, forking yourself into
                   7843:     # process death.
                   7844:     exit;
1.106     foxr     7845:     
1.78      foxr     7846: }
1.532     raeburn  7847: 
                   7848: #
                   7849: #  Used to determine if a particular client is from the same domain
1.556     raeburn  7850: #  as the current server, or from the same internet domain, and
                   7851: #  also if the client can host sessions for the domain's users.
                   7852: #  A hash is populated with keys set to commands sent by the client
                   7853: #  which may not be executed for this domain.
1.532     raeburn  7854: #
                   7855: #  Optional input -- the client to check for domain and internet domain.
                   7856: #  If not specified, defaults to the package variable: $clientname
                   7857: #
                   7858: #  If called in array context will not set package variables, but will
                   7859: #  instead return an array of two values - (a) true if client is in the
1.556     raeburn  7860: #  same domain as the server, and (b) true if client is in the same 
                   7861: #  internet domain.
1.532     raeburn  7862: #
                   7863: #  If called in scalar context, sets package variables for current client:
                   7864: #
1.556     raeburn  7865: #  $clienthomedom    - LonCAPA domain of homeID for client.
                   7866: #  $clientsamedom    - LonCAPA domain same for this host and client.
                   7867: #  $clientintdom     - LonCAPA "internet domain" for client.
                   7868: #  $clientsameinst   - LonCAPA "internet domain" same for this host & client.
                   7869: #  $clientremoteok   - If current domain permits hosting on this client: 1
                   7870: #  %clientprohibited - Commands prohibited for domain's users for this client.
                   7871: #
                   7872: #  if the host and client have the same "internet domain", then the value
                   7873: #  of $clientremoteok is not used, and no commands are prohibited.
1.532     raeburn  7874: #
                   7875: #  returns 1 to indicate package variables have been set for current client.
                   7876: #
                   7877: 
                   7878: sub set_client_info {
                   7879:     my ($lonhost) = @_;
                   7880:     $lonhost ||= $clientname;
                   7881:     my $clienthost = &Apache::lonnet::hostname($lonhost);
                   7882:     my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
                   7883:     my $homedom = &Apache::lonnet::host_domain($clientserverhomeID);
                   7884:     my $samedom = 0;
1.557     raeburn  7885:     if ($perlvar{'lonDefDomain'} eq $homedom) {
1.532     raeburn  7886:         $samedom = 1;
                   7887:     }
                   7888:     my $intdom = &Apache::lonnet::internet_dom($clientserverhomeID);
                   7889:     my $sameinst = 0;
                   7890:     if ($intdom ne '') {
                   7891:         my $internet_names = &Apache::lonnet::get_internet_names($currenthostid);
                   7892:         if (ref($internet_names) eq 'ARRAY') {
                   7893:             if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   7894:                 $sameinst = 1;
                   7895:             }
                   7896:         }
                   7897:     }
                   7898:     if (wantarray) {
                   7899:         return ($samedom,$sameinst);
                   7900:     } else {
                   7901:         $clienthomedom = $homedom;
                   7902:         $clientsamedom = $samedom;
                   7903:         $clientintdom = $intdom;
                   7904:         $clientsameinst = $sameinst;
1.556     raeburn  7905:         if ($clientsameinst) {
                   7906:             undef($clientremoteok);
                   7907:             undef(%clientprohibited);
                   7908:         } else {
                   7909:             $clientremoteok = &get_remote_hostable($currentdomainid);
                   7910:             %clientprohibited = &get_prohibited($currentdomainid);
                   7911:         }
1.532     raeburn  7912:         return 1;
                   7913:     }
                   7914: }
                   7915: 
1.261     foxr     7916: #
                   7917: #   Determine if a user is an author for the indicated domain.
                   7918: #
                   7919: # Parameters:
                   7920: #    domain          - domain to check in .
                   7921: #    user            - Name of user to check.
                   7922: #
                   7923: # Return:
                   7924: #     1             - User is an author for domain.
                   7925: #     0             - User is not an author for domain.
                   7926: sub is_author {
                   7927:     my ($domain, $user) = @_;
                   7928: 
                   7929:     &Debug("is_author: $user @ $domain");
                   7930: 
                   7931:     my $hashref = &tie_user_hash($domain, $user, "roles",
                   7932: 				 &GDBM_READER());
                   7933: 
                   7934:     #  Author role should show up as a key /domain/_au
1.78      foxr     7935: 
1.321     albertel 7936:     my $value;
1.487     foxr     7937:     if ($hashref) {
1.78      foxr     7938: 
1.487     foxr     7939: 	my $key    = "/$domain/_au";
                   7940: 	if (defined($hashref)) {
                   7941: 	    $value = $hashref->{$key};
                   7942: 	    if(!untie_user_hash($hashref)) {
                   7943: 		return 'error: ' .  ($!+0)." untie (GDBM) Failed";
                   7944: 	    }
                   7945: 	}
                   7946: 	
                   7947: 	if(defined($value)) {
                   7948: 	    &Debug("$user @ $domain is an author");
                   7949: 	}
                   7950:     } else {
                   7951: 	return 'error: '.($!+0)." tie (GDBM) Failed";
1.261     foxr     7952:     }
                   7953: 
                   7954:     return defined($value);
                   7955: }
1.78      foxr     7956: #
                   7957: #   Checks to see if the input roleput request was to set
1.482     www      7958: # an author role.  If so, creates construction space 
1.78      foxr     7959: # Parameters:
                   7960: #    request   - The request sent to the rolesput subchunk.
                   7961: #                We're looking for  /domain/_au
                   7962: #    domain    - The domain in which the user is having roles doctored.
                   7963: #    user      - Name of the user for which the role is being put.
                   7964: #    authtype  - The authentication type associated with the user.
                   7965: #
1.289     albertel 7966: sub manage_permissions {
1.192     foxr     7967:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     7968:     # See if the request is of the form /$domain/_au
1.289     albertel 7969:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.484     raeburn  7970:         my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
1.482     www      7971:         unless (-e $path) {        
                   7972:            mkdir($path);
                   7973:         }
                   7974:         unless (-e $path.'/'.$user) {
                   7975:            mkdir($path.'/'.$user);
                   7976:         }
1.78      foxr     7977:     }
                   7978: }
1.222     foxr     7979: 
                   7980: 
                   7981: #
                   7982: #  Return the full path of a user password file, whether it exists or not.
                   7983: # Parameters:
                   7984: #   domain     - Domain in which the password file lives.
                   7985: #   user       - name of the user.
                   7986: # Returns:
                   7987: #    Full passwd path:
                   7988: #
                   7989: sub password_path {
                   7990:     my ($domain, $user) = @_;
1.264     albertel 7991:     return &propath($domain, $user).'/passwd';
1.222     foxr     7992: }
                   7993: 
                   7994: #   Password Filename
                   7995: #   Returns the path to a passwd file given domain and user... only if
                   7996: #  it exists.
                   7997: # Parameters:
                   7998: #   domain    - Domain in which to search.
                   7999: #   user      - username.
                   8000: # Returns:
                   8001: #   - If the password file exists returns its path.
                   8002: #   - If the password file does not exist, returns undefined.
                   8003: #
                   8004: sub password_filename {
                   8005:     my ($domain, $user) = @_;
                   8006: 
                   8007:     Debug ("PasswordFilename called: dom = $domain user = $user");
                   8008: 
                   8009:     my $path  = &password_path($domain, $user);
                   8010:     Debug("PasswordFilename got path: $path");
                   8011:     if(-e $path) {
                   8012: 	return $path;
                   8013:     } else {
                   8014: 	return undef;
                   8015:     }
                   8016: }
                   8017: 
                   8018: #
                   8019: #   Rewrite the contents of the user's passwd file.
                   8020: #  Parameters:
                   8021: #    domain    - domain of the user.
                   8022: #    name      - User's name.
                   8023: #    contents  - New contents of the file.
1.533     raeburn  8024: #    saveold   - (optional). If true save old file in a passwd.bak file.
1.222     foxr     8025: # Returns:
                   8026: #   0    - Failed.
                   8027: #   1    - Success.
                   8028: #
                   8029: sub rewrite_password_file {
1.533     raeburn  8030:     my ($domain, $user, $contents, $saveold) = @_;
1.222     foxr     8031: 
                   8032:     my $file = &password_filename($domain, $user);
                   8033:     if (defined $file) {
1.533     raeburn  8034:         if ($saveold) {
                   8035:             my $bakfile = $file.'.bak';
                   8036:             if (CopyFile($file,$bakfile)) {
                   8037:                 chmod(0400,$bakfile);
                   8038:                 &logthis("Old password saved in passwd.bak for internally authenticated user: $user:$domain");
                   8039:             } else {
                   8040:                 &logthis("Failed to save old password in passwd.bak for internally authenticated user: $user:$domain");
                   8041:             }
                   8042:         }
1.222     foxr     8043: 	my $pf = IO::File->new(">$file");
                   8044: 	if($pf) {
                   8045: 	    print $pf "$contents\n";
                   8046: 	    return 1;
                   8047: 	} else {
                   8048: 	    return 0;
                   8049: 	}
                   8050:     } else {
                   8051: 	return 0;
                   8052:     }
                   8053: 
                   8054: }
                   8055: 
1.78      foxr     8056: #
1.222     foxr     8057: #   get_auth_type - Determines the authorization type of a user in a domain.
1.78      foxr     8058: 
                   8059: #     Returns the authorization type or nouser if there is no such user.
                   8060: #
1.436     raeburn  8061: sub get_auth_type {
1.192     foxr     8062:     my ($domain, $user)  = @_;
1.78      foxr     8063: 
1.222     foxr     8064:     Debug("get_auth_type( $domain, $user ) \n");
1.78      foxr     8065:     my $proname    = &propath($domain, $user); 
                   8066:     my $passwdfile = "$proname/passwd";
                   8067:     if( -e $passwdfile ) {
                   8068: 	my $pf = IO::File->new($passwdfile);
                   8069: 	my $realpassword = <$pf>;
                   8070: 	chomp($realpassword);
1.79      foxr     8071: 	Debug("Password info = $realpassword\n");
1.78      foxr     8072: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     8073: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.259     raeburn  8074: 	return "$authtype:$contentpwd";     
1.224     foxr     8075:     } else {
1.79      foxr     8076: 	Debug("Returning nouser");
1.78      foxr     8077: 	return "nouser";
                   8078:     }
1.1       albertel 8079: }
                   8080: 
1.220     foxr     8081: #
                   8082: #  Validate a user given their domain, name and password.  This utility
                   8083: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
                   8084: #  to validate the login credentials of a user.
                   8085: # Parameters:
                   8086: #    $domain    - The domain being logged into (this is required due to
                   8087: #                 the capability for multihomed systems.
                   8088: #    $user      - The name of the user being validated.
                   8089: #    $password  - The user's propoposed password.
                   8090: #
                   8091: # Returns:
                   8092: #     1        - The domain,user,pasword triplet corresponds to a valid
                   8093: #                user.
                   8094: #     0        - The domain,user,password triplet is not a valid user.
                   8095: #
                   8096: sub validate_user {
1.396     raeburn  8097:     my ($domain, $user, $password, $checkdefauth) = @_;
1.220     foxr     8098: 
                   8099:     # Why negative ~pi you may well ask?  Well this function is about
                   8100:     # authentication, and therefore very important to get right.
                   8101:     # I've initialized the flag that determines whether or not I've 
                   8102:     # validated correctly to a value it's not supposed to get.
                   8103:     # At the end of this function. I'll ensure that it's not still that
                   8104:     # value so we don't just wind up returning some accidental value
                   8105:     # as a result of executing an unforseen code path that
1.249     foxr     8106:     # did not set $validated.  At the end of valid execution paths,
                   8107:     # validated shoule be 1 for success or 0 for failuer.
1.220     foxr     8108: 
                   8109:     my $validated = -3.14159;
                   8110: 
                   8111:     #  How we authenticate is determined by the type of authentication
                   8112:     #  the user has been assigned.  If the authentication type is
                   8113:     #  "nouser", the user does not exist so we will return 0.
                   8114: 
1.222     foxr     8115:     my $contents = &get_auth_type($domain, $user);
1.220     foxr     8116:     my ($howpwd, $contentpwd) = split(/:/, $contents);
                   8117: 
                   8118:     my $null = pack("C",0);	# Used by kerberos auth types.
                   8119: 
1.395     raeburn  8120:     if ($howpwd eq 'nouser') {
1.396     raeburn  8121:         if ($checkdefauth) {
                   8122:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8123:             if ($domdefaults{'auth_def'} eq 'localauth') {
                   8124:                 $howpwd = $domdefaults{'auth_def'};
                   8125:                 $contentpwd = $domdefaults{'auth_arg_def'};
                   8126:             } elsif ((($domdefaults{'auth_def'} eq 'krb4') || 
                   8127:                       ($domdefaults{'auth_def'} eq 'krb5')) &&
                   8128:                      ($domdefaults{'auth_arg_def'} ne '')) {
                   8129:                 $howpwd = $domdefaults{'auth_def'};
                   8130:                 $contentpwd = $domdefaults{'auth_arg_def'}; 
                   8131:             }
1.395     raeburn  8132:         }
1.533     raeburn  8133:     }
1.220     foxr     8134:     if ($howpwd ne 'nouser') {
                   8135: 	if($howpwd eq "internal") { # Encrypted is in local password file.
1.518     raeburn  8136:             if (length($contentpwd) == 13) {
                   8137:                 $validated = (crypt($password,$contentpwd) eq $contentpwd);
                   8138:                 if ($validated) {
1.533     raeburn  8139:                     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8140:                     if ($domdefaults{'intauth_switch'}) {
                   8141:                         my $ncpass = &hash_passwd($domain,$password);
                   8142:                         my $saveold;
                   8143:                         if ($domdefaults{'intauth_switch'} == 2) {
                   8144:                             $saveold = 1;
                   8145:                         }
                   8146:                         if (&rewrite_password_file($domain,$user,"$howpwd:$ncpass",$saveold)) {
                   8147:                             &update_passwd_history($user,$domain,$howpwd,'conversion');
                   8148:                             &logthis("Validated password hashed with bcrypt for $user:$domain");
                   8149:                         }
1.518     raeburn  8150:                     }
                   8151:                 }
                   8152:             } else {
1.533     raeburn  8153:                 $validated = &check_internal_passwd($password,$contentpwd,$domain,$user);
1.518     raeburn  8154:             }
1.220     foxr     8155: 	}
                   8156: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
                   8157: 	    $contentpwd = (getpwnam($user))[1];
                   8158: 	    if($contentpwd) {
                   8159: 		if($contentpwd eq 'x') { # Shadow password file...
                   8160: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
                   8161: 		    open PWAUTH,  "|$pwauth_path" or
                   8162: 			die "Cannot invoke authentication";
                   8163: 		    print PWAUTH "$user\n$password\n";
                   8164: 		    close PWAUTH;
                   8165: 		    $validated = ! $?;
                   8166: 
                   8167: 		} else { 	         # Passwords in /etc/passwd. 
                   8168: 		    $validated = (crypt($password,
                   8169: 					$contentpwd) eq $contentpwd);
                   8170: 		}
                   8171: 	    } else {
                   8172: 		$validated = 0;
                   8173: 	    }
1.439     raeburn  8174: 	} elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
                   8175:             my $checkwithkrb5 = 0;
                   8176:             if ($dist =~/^fedora(\d+)$/) {
                   8177:                 if ($1 > 11) {
                   8178:                     $checkwithkrb5 = 1;
                   8179:                 }
                   8180:             } elsif ($dist =~ /^suse([\d.]+)$/) {
                   8181:                 if ($1 > 11.1) {
                   8182:                     $checkwithkrb5 = 1; 
                   8183:                 }
                   8184:             }
                   8185:             if ($checkwithkrb5) {
                   8186:                 $validated = &krb5_authen($password,$null,$user,$contentpwd);
                   8187:             } else {
                   8188:                 $validated = &krb4_authen($password,$null,$user,$contentpwd);
                   8189:             }
1.224     foxr     8190: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.439     raeburn  8191:             $validated = &krb5_authen($password,$null,$user,$contentpwd);
1.224     foxr     8192: 	} elsif ($howpwd eq "localauth") { 
1.220     foxr     8193: 	    #  Authenticate via installation specific authentcation method:
                   8194: 	    $validated = &localauth::localauth($user, 
                   8195: 					       $password, 
1.353     albertel 8196: 					       $contentpwd,
                   8197: 					       $domain);
1.358     albertel 8198: 	    if ($validated < 0) {
1.357     albertel 8199: 		&logthis("localauth for $contentpwd $user:$domain returned a $validated");
                   8200: 		$validated = 0;
                   8201: 	    }
1.224     foxr     8202: 	} else {			# Unrecognized auth is also bad.
1.220     foxr     8203: 	    $validated = 0;
                   8204: 	}
                   8205:     } else {
                   8206: 	$validated = 0;
                   8207:     }
                   8208:     #
                   8209:     #  $validated has the correct stat of the authentication:
                   8210:     #
                   8211: 
                   8212:     unless ($validated != -3.14159) {
1.249     foxr     8213: 	#  I >really really< want to know if this happens.
                   8214: 	#  since it indicates that user authentication is badly
                   8215: 	#  broken in some code path.
                   8216:         #
                   8217: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220     foxr     8218:     }
                   8219:     return $validated;
                   8220: }
                   8221: 
1.518     raeburn  8222: sub check_internal_passwd {
1.533     raeburn  8223:     my ($plainpass,$stored,$domain,$user) = @_;
1.518     raeburn  8224:     my (undef,$method,@rest) = split(/!/,$stored);
1.533     raeburn  8225:     if ($method eq 'bcrypt') {
1.518     raeburn  8226:         my $result = &hash_passwd($domain,$plainpass,@rest);
                   8227:         if ($result ne $stored) {
                   8228:             return 0;
                   8229:         }
1.533     raeburn  8230:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8231:         if ($domdefaults{'intauth_check'}) {
                   8232:             # Upgrade to a larger number of rounds if necessary
                   8233:             my $defaultcost = $domdefaults{'intauth_cost'};
                   8234:             if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   8235:                 $defaultcost = 10;
                   8236:             }
                   8237:             if (int($rest[0])<int($defaultcost)) {
                   8238:                 if ($domdefaults{'intauth_check'} == 1) { 
                   8239:                     my $ncpass = &hash_passwd($domain,$plainpass);
                   8240:                     if (&rewrite_password_file($domain,$user,"internal:$ncpass")) {
                   8241:                         &update_passwd_history($user,$domain,'internal','update cost');
                   8242:                         &logthis("Validated password hashed with bcrypt for $user:$domain");
                   8243:                     }
                   8244:                     return 1;
                   8245:                 } elsif ($domdefaults{'intauth_check'} == 2) {
                   8246:                     return 0;
                   8247:                 }
                   8248:             }
                   8249:         } else {
                   8250:             return 1;
1.518     raeburn  8251:         }
                   8252:     }
                   8253:     return 0;
                   8254: }
                   8255: 
                   8256: sub get_last_authchg {
                   8257:     my ($domain,$user) = @_;
                   8258:     my $lastmod;
                   8259:     my $logname = &propath($domain,$user).'/passwd.log';
                   8260:     if (-e "$logname") {
                   8261:         $lastmod = (stat("$logname"))[9];
                   8262:     }
                   8263:     return $lastmod;
                   8264: }
                   8265: 
1.439     raeburn  8266: sub krb4_authen {
                   8267:     my ($password,$null,$user,$contentpwd) = @_;
                   8268:     my $validated = 0;
                   8269:     if (!($password =~ /$null/) ) {  # Null password not allowed.
                   8270:         eval {
                   8271:             require Authen::Krb4;
                   8272:         };
                   8273:         if (!$@) {
                   8274:             my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
                   8275:                                                        "",
                   8276:                                                        $contentpwd,,
                   8277:                                                        'krbtgt',
                   8278:                                                        $contentpwd,
                   8279:                                                        1,
                   8280:                                                        $password);
                   8281:             if(!$k4error) {
                   8282:                 $validated = 1;
                   8283:             } else {
                   8284:                 $validated = 0;
                   8285:                 &logthis('krb4: '.$user.', '.$contentpwd.', '.
                   8286:                           &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   8287:             }
                   8288:         } else {
                   8289:             $validated = krb5_authen($password,$null,$user,$contentpwd);
                   8290:         }
                   8291:     }
                   8292:     return $validated;
                   8293: }
                   8294: 
                   8295: sub krb5_authen {
                   8296:     my ($password,$null,$user,$contentpwd) = @_;
                   8297:     my $validated = 0;
                   8298:     if(!($password =~ /$null/)) { # Null password not allowed.
                   8299:         my $krbclient = &Authen::Krb5::parse_name($user.'@'
                   8300:                                                   .$contentpwd);
                   8301:         my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
                   8302:         my $krbserver  = &Authen::Krb5::parse_name($krbservice);
                   8303:         my $credentials= &Authen::Krb5::cc_default();
                   8304:         $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
                   8305:                                                             .$contentpwd));
                   8306:         my $krbreturn;
                   8307:         if (exists(&Authen::Krb5::get_init_creds_password)) {
                   8308:             $krbreturn =
                   8309:                 &Authen::Krb5::get_init_creds_password($krbclient,$password,
                   8310:                                                           $krbservice);
                   8311:             $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
                   8312:         } else {
                   8313:             $krbreturn  =
                   8314:                 &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
                   8315:                                                          $password,$credentials);
                   8316:             $validated = ($krbreturn == 1);
                   8317:         }
                   8318:         if (!$validated) {
                   8319:             &logthis('krb5: '.$user.', '.$contentpwd.', '.
                   8320:                      &Authen::Krb5::error());
                   8321:         }
                   8322:     }
                   8323:     return $validated;
                   8324: }
1.220     foxr     8325: 
1.84      albertel 8326: sub addline {
                   8327:     my ($fname,$hostid,$ip,$newline)=@_;
                   8328:     my $contents;
                   8329:     my $found=0;
1.355     albertel 8330:     my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
1.134     albertel 8331:     my $sh;
1.84      albertel 8332:     if ($sh=IO::File->new("$fname.subscription")) {
                   8333: 	while (my $subline=<$sh>) {
                   8334: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   8335: 	}
                   8336: 	$sh->close();
                   8337:     }
                   8338:     $sh=IO::File->new(">$fname.subscription");
                   8339:     if ($contents) { print $sh $contents; }
                   8340:     if ($newline) { print $sh $newline; }
                   8341:     $sh->close();
                   8342:     return $found;
1.86      www      8343: }
                   8344: 
1.234     foxr     8345: sub get_chat {
1.324     raeburn  8346:     my ($cdom,$cname,$udom,$uname,$group)=@_;
1.310     albertel 8347: 
1.87      www      8348:     my @entries=();
1.324     raeburn  8349:     my $namespace = 'nohist_chatroom';
                   8350:     my $namespace_inroom = 'nohist_inchatroom';
1.335     albertel 8351:     if ($group ne '') {
1.324     raeburn  8352:         $namespace .= '_'.$group;
                   8353:         $namespace_inroom .= '_'.$group;
                   8354:     }
                   8355:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8356: 				 &GDBM_READER());
                   8357:     if ($hashref) {
                   8358: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.311     albertel 8359: 	&untie_user_hash($hashref);
1.123     www      8360:     }
1.124     www      8361:     my @participants=();
1.134     albertel 8362:     my $cutoff=time-60;
1.324     raeburn  8363:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
1.310     albertel 8364: 			      &GDBM_WRCREAT());
                   8365:     if ($hashref) {
                   8366:         $hashref->{$uname.':'.$udom}=time;
                   8367:         foreach my $user (sort(keys(%$hashref))) {
                   8368: 	    if ($hashref->{$user}>$cutoff) {
                   8369: 		push(@participants, 'active_participant:'.$user);
1.123     www      8370:             }
                   8371:         }
1.311     albertel 8372:         &untie_user_hash($hashref);
1.86      www      8373:     }
1.124     www      8374:     return (@participants,@entries);
1.86      www      8375: }
                   8376: 
1.234     foxr     8377: sub chat_add {
1.324     raeburn  8378:     my ($cdom,$cname,$newchat,$group)=@_;
1.88      albertel 8379:     my @entries=();
1.142     www      8380:     my $time=time;
1.324     raeburn  8381:     my $namespace = 'nohist_chatroom';
                   8382:     my $logfile = 'chatroom.log';
1.335     albertel 8383:     if ($group ne '') {
1.324     raeburn  8384:         $namespace .= '_'.$group;
                   8385:         $logfile = 'chatroom_'.$group.'.log';
                   8386:     }
                   8387:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8388: 				 &GDBM_WRCREAT());
                   8389:     if ($hashref) {
                   8390: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.88      albertel 8391: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   8392: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   8393: 	my $newid=$time.'_000000';
                   8394: 	if ($thentime==$time) {
                   8395: 	    $idnum=~s/^0+//;
                   8396: 	    $idnum++;
                   8397: 	    $idnum=substr('000000'.$idnum,-6,6);
                   8398: 	    $newid=$time.'_'.$idnum;
                   8399: 	}
1.310     albertel 8400: 	$hashref->{$newid}=$newchat;
1.88      albertel 8401: 	my $expired=$time-3600;
1.310     albertel 8402: 	foreach my $comment (keys(%$hashref)) {
                   8403: 	    my ($thistime) = ($comment=~/(\d+)\_/);
1.88      albertel 8404: 	    if ($thistime<$expired) {
1.310     albertel 8405: 		delete $hashref->{$comment};
1.88      albertel 8406: 	    }
                   8407: 	}
1.310     albertel 8408: 	{
                   8409: 	    my $proname=&propath($cdom,$cname);
1.324     raeburn  8410: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
1.310     albertel 8411: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
                   8412: 	    }
                   8413: 	    close(CHATLOG);
1.142     www      8414: 	}
1.311     albertel 8415: 	&untie_user_hash($hashref);
1.86      www      8416:     }
1.84      albertel 8417: }
                   8418: 
                   8419: sub unsub {
                   8420:     my ($fname,$clientip)=@_;
                   8421:     my $result;
1.188     foxr     8422:     my $unsubs = 0;		# Number of successful unsubscribes:
                   8423: 
                   8424: 
                   8425:     # An old way subscriptions were handled was to have a 
                   8426:     # subscription marker file:
                   8427: 
                   8428:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     8429:     if (unlink("$fname.$clientname")) {
1.188     foxr     8430: 	$unsubs++;		# Successful unsub via marker file.
                   8431:     } 
                   8432: 
                   8433:     # The more modern way to do it is to have a subscription list
                   8434:     # file:
                   8435: 
1.84      albertel 8436:     if (-e "$fname.subscription") {
1.161     foxr     8437: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     8438: 	if ($found) { 
                   8439: 	    $unsubs++;
                   8440: 	}
                   8441:     } 
                   8442: 
                   8443:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   8444:     #  resource we can return ok:
                   8445: 
                   8446:     if($unsubs) {
                   8447: 	$result = "ok\n";
1.84      albertel 8448:     } else {
1.188     foxr     8449: 	$result = "not_subscribed\n";
1.84      albertel 8450:     }
1.188     foxr     8451: 
1.84      albertel 8452:     return $result;
                   8453: }
                   8454: 
1.101     www      8455: sub currentversion {
                   8456:     my $fname=shift;
                   8457:     my $version=-1;
                   8458:     my $ulsdir='';
                   8459:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   8460:        $ulsdir=$1;
                   8461:     }
1.114     albertel 8462:     my ($fnamere1,$fnamere2);
                   8463:     # remove version if already specified
1.101     www      8464:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 8465:     # get the bits that go before and after the version number
                   8466:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   8467: 	$fnamere1=$1;
                   8468: 	$fnamere2='.'.$2;
                   8469:     }
1.101     www      8470:     if (-e $fname) { $version=1; }
                   8471:     if (-e $ulsdir) {
1.134     albertel 8472: 	if(-d $ulsdir) {
                   8473: 	    if (opendir(LSDIR,$ulsdir)) {
                   8474: 		my $ulsfn;
                   8475: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      8476: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 8477: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   8478: 		    unless (-l $thisfile) {
1.160     www      8479: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 8480: 			    if ($1>$version) { $version=$1; }
                   8481: 			}
                   8482: 		    }
                   8483: 		}
                   8484: 		closedir(LSDIR);
                   8485: 		$version++;
                   8486: 	    }
                   8487: 	}
                   8488:     }
                   8489:     return $version;
1.101     www      8490: }
                   8491: 
                   8492: sub thisversion {
                   8493:     my $fname=shift;
                   8494:     my $version=-1;
                   8495:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   8496: 	$version=$1;
                   8497:     }
                   8498:     return $version;
                   8499: }
                   8500: 
1.84      albertel 8501: sub subscribe {
                   8502:     my ($userinput,$clientip)=@_;
                   8503:     my $result;
1.293     albertel 8504:     my ($cmd,$fname)=split(/:/,$userinput,2);
1.84      albertel 8505:     my $ownership=&ishome($fname);
                   8506:     if ($ownership eq 'owner') {
1.101     www      8507: # explitly asking for the current version?
                   8508:         unless (-e $fname) {
                   8509:             my $currentversion=&currentversion($fname);
                   8510: 	    if (&thisversion($fname)==$currentversion) {
                   8511:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   8512: 		    my $root=$1;
                   8513:                     my $extension=$2;
                   8514:                     symlink($root.'.'.$extension,
                   8515:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      8516:                     unless ($extension=~/\.meta$/) {
                   8517:                        symlink($root.'.'.$extension.'.meta',
                   8518:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   8519: 		    }
1.101     www      8520:                 }
                   8521:             }
                   8522:         }
1.84      albertel 8523: 	if (-e $fname) {
                   8524: 	    if (-d $fname) {
                   8525: 		$result="directory\n";
                   8526: 	    } else {
1.161     foxr     8527: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 8528: 		my $now=time;
1.161     foxr     8529: 		my $found=&addline($fname,$clientname,$clientip,
                   8530: 				   "$clientname:$clientip:$now\n");
1.84      albertel 8531: 		if ($found) { $result="$fname\n"; }
                   8532: 		# if they were subscribed to only meta data, delete that
                   8533:                 # subscription, when you subscribe to a file you also get
                   8534:                 # the metadata
                   8535: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   8536: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
1.476     raeburn  8537:                 my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
                   8538:                 $protocol = 'http' if ($protocol ne 'https');
                   8539: 		$fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
1.84      albertel 8540: 		$result="$fname\n";
                   8541: 	    }
                   8542: 	} else {
                   8543: 	    $result="not_found\n";
                   8544: 	}
                   8545:     } else {
                   8546: 	$result="rejected\n";
                   8547:     }
                   8548:     return $result;
                   8549: }
1.287     foxr     8550: #  Change the passwd of a unix user.  The caller must have
                   8551: #  first verified that the user is a loncapa user.
                   8552: #
                   8553: # Parameters:
                   8554: #    user      - Unix user name to change.
                   8555: #    pass      - New password for the user.
                   8556: # Returns:
                   8557: #    ok    - if success
                   8558: #    other - Some meaningfule error message string.
                   8559: # NOTE:
                   8560: #    invokes a setuid script to change the passwd.
                   8561: sub change_unix_password {
                   8562:     my ($user, $pass) = @_;
                   8563: 
                   8564:     &Debug("change_unix_password");
                   8565:     my $execdir=$perlvar{'lonDaemons'};
                   8566:     &Debug("Opening lcpasswd pipeline");
                   8567:     my $pf = IO::File->new("|$execdir/lcpasswd > "
                   8568: 			   ."$perlvar{'lonDaemons'}"
                   8569: 			   ."/logs/lcpasswd.log");
                   8570:     print $pf "$user\n$pass\n$pass\n";
                   8571:     close $pf;
                   8572:     my $err = $?;
                   8573:     return ($err < @passwderrors) ? $passwderrors[$err] : 
                   8574: 	"pwchange_falure - unknown error";
                   8575: 
                   8576:     
                   8577: }
                   8578: 
1.91      albertel 8579: 
                   8580: sub make_passwd_file {
1.518     raeburn  8581:     my ($uname,$udom,$umode,$npass,$passfilename,$action)=@_;
1.390     raeburn  8582:     my $result="ok";
1.91      albertel 8583:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   8584: 	{
                   8585: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8586: 	    if ($pf) {
                   8587: 		print $pf "$umode:$npass\n";
1.518     raeburn  8588:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     8589: 	    } else {
                   8590: 		$result = "pass_file_failed_error";
                   8591: 	    }
1.91      albertel 8592: 	}
                   8593:     } elsif ($umode eq 'internal') {
1.518     raeburn  8594:         my $ncpass = &hash_passwd($udom,$npass);
1.91      albertel 8595: 	{
                   8596: 	    &Debug("Creating internal auth");
                   8597: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8598: 	    if($pf) {
1.518     raeburn  8599: 		print $pf "internal:$ncpass\n";
                   8600:                 &update_passwd_history($uname,$udom,$umode,$action); 
1.261     foxr     8601: 	    } else {
                   8602: 		$result = "pass_file_failed_error";
                   8603: 	    }
1.91      albertel 8604: 	}
                   8605:     } elsif ($umode eq 'localauth') {
                   8606: 	{
                   8607: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8608: 	    if($pf) {
                   8609: 		print $pf "localauth:$npass\n";
1.524     raeburn  8610:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     8611: 	    } else {
                   8612: 		$result = "pass_file_failed_error";
                   8613: 	    }
1.91      albertel 8614: 	}
                   8615:     } elsif ($umode eq 'unix') {
1.502     raeburn  8616: 	&logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
                   8617: 	$result="no_new_unix_accounts";
1.91      albertel 8618:     } elsif ($umode eq 'none') {
                   8619: 	{
1.223     foxr     8620: 	    my $pf = IO::File->new("> $passfilename");
1.261     foxr     8621: 	    if($pf) {
                   8622: 		print $pf "none:\n";
                   8623: 	    } else {
                   8624: 		$result = "pass_file_failed_error";
                   8625: 	    }
1.91      albertel 8626: 	}
1.543     raeburn  8627:     } elsif ($umode eq 'lti') {
                   8628:         my $pf = IO::File->new(">$passfilename");
                   8629:         if($pf) {
                   8630:             print $pf "lti:\n";
                   8631:             &update_passwd_history($uname,$udom,$umode,$action);
                   8632:         } else {
                   8633:             $result = "pass_file_failed_error";
                   8634:         }
1.91      albertel 8635:     } else {
1.390     raeburn  8636: 	$result="auth_mode_error";
1.91      albertel 8637:     }
                   8638:     return $result;
1.121     albertel 8639: }
                   8640: 
1.265     albertel 8641: sub convert_photo {
                   8642:     my ($start,$dest)=@_;
                   8643:     system("convert $start $dest");
                   8644: }
                   8645: 
1.121     albertel 8646: sub sethost {
                   8647:     my ($remotereq) = @_;
                   8648:     my (undef,$hostid)=split(/:/,$remotereq);
1.322     albertel 8649:     # ignore sethost if we are already correct
                   8650:     if ($hostid eq $currenthostid) {
                   8651: 	return 'ok';
                   8652:     }
                   8653: 
1.121     albertel 8654:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
1.368     albertel 8655:     if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'}) 
                   8656: 	eq &Apache::lonnet::get_host_ip($hostid)) {
1.200     matthew  8657: 	$currenthostid  =$hostid;
1.369     albertel 8658: 	$currentdomainid=&Apache::lonnet::host_domain($hostid);
1.556     raeburn  8659:         &set_client_info();
1.443     www      8660: #	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
1.121     albertel 8661:     } else {
                   8662: 	&logthis("Requested host id $hostid not an alias of ".
                   8663: 		 $perlvar{'lonHostID'}." refusing connection");
                   8664: 	return 'unable_to_set';
                   8665:     }
                   8666:     return 'ok';
                   8667: }
                   8668: 
                   8669: sub version {
                   8670:     my ($userinput)=@_;
                   8671:     $remoteVERSION=(split(/:/,$userinput))[1];
                   8672:     return "version:$VERSION";
1.127     albertel 8673: }
1.178     foxr     8674: 
1.447     raeburn  8675: sub get_usersession_config {
                   8676:     my ($dom,$name) = @_;
                   8677:     my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8678:     if (defined($cached)) {
                   8679:         return $usersessionconf;
                   8680:     } else {
                   8681:         my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
1.525     raeburn  8682:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
                   8683:         return $domconfig{'usersessions'};
1.447     raeburn  8684:     }
                   8685:     return;
                   8686: }
1.200     matthew  8687: 
1.534     raeburn  8688: sub get_usersearch_config {
                   8689:     my ($dom,$name) = @_;
                   8690:     my ($usersearchconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8691:     if (defined($cached)) {
                   8692:         return $usersearchconf;
                   8693:     } else {
                   8694:         my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$dom);
                   8695:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'directorysrch'},600);
                   8696:         return $domconfig{'directorysrch'};
                   8697:     }
                   8698:     return;
                   8699: }
                   8700: 
1.525     raeburn  8701: sub get_prohibited {
                   8702:     my ($dom) = @_;
                   8703:     my $name = 'trust';
                   8704:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8705:     unless (defined($cached)) {
                   8706:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$dom);
                   8707:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'trust'},3600);
                   8708:         $trustconfig = $domconfig{'trust'};
                   8709:     }
                   8710:     my %prohibited;
                   8711:     if (ref($trustconfig)) {
                   8712:         foreach my $prefix (keys(%{$trustconfig})) {
                   8713:             if (ref($trustconfig->{$prefix}) eq 'HASH') {
                   8714:                 my $reject;
                   8715:                 if (ref($trustconfig->{$prefix}->{'exc'}) eq 'ARRAY') {
                   8716:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'exc'}})) {
                   8717:                         $reject = 1;
                   8718:                     }
                   8719:                 }
                   8720:                 if (ref($trustconfig->{$prefix}->{'inc'}) eq 'ARRAY') {
                   8721:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'inc'}})) {
                   8722:                         $reject = 0;
                   8723:                     } else {
                   8724:                         $reject = 1;
                   8725:                     }
                   8726:                 }
                   8727:                 if ($reject) {
                   8728:                     $prohibited{$prefix} = 1;
                   8729:                 }
                   8730:             }
                   8731:         }
                   8732:     }
                   8733:     return %prohibited;
                   8734: }
1.450     raeburn  8735: 
1.556     raeburn  8736: sub get_remote_hostable {
                   8737:     my ($dom) = @_;
                   8738:     my $result;
                   8739:     if ($clientintdom) {
                   8740:         $result = 1;
                   8741:         my $remsessconf = &get_usersession_config($dom,'remotesession');
                   8742:         if (ref($remsessconf) eq 'HASH') {
                   8743:             if (ref($remsessconf->{'remote'}) eq 'HASH') {
                   8744:                 if (ref($remsessconf->{'remote'}->{'excludedomain'}) eq 'ARRAY') {
                   8745:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'excludedomain'}})) {
                   8746:                         $result = 0;
                   8747:                     }
                   8748:                 }
                   8749:                 if (ref($remsessconf->{'remote'}->{'includedomain'}) eq 'ARRAY') {
                   8750:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'includedomain'}})) {
                   8751:                         $result = 1;
                   8752:                     } else {
                   8753:                         $result = 0;
                   8754:                     }
                   8755:                 }
                   8756:             }
                   8757:         }
                   8758:     }
                   8759:     return $result;
                   8760: }
                   8761: 
1.471     raeburn  8762: sub distro_and_arch {
                   8763:     return $dist.':'.$arch;
                   8764: }
                   8765: 
1.61      harris41 8766: # ----------------------------------- POD (plain old documentation, CPAN style)
                   8767: 
                   8768: =head1 NAME
                   8769: 
                   8770: lond - "LON Daemon" Server (port "LOND" 5663)
                   8771: 
                   8772: =head1 SYNOPSIS
                   8773: 
1.74      harris41 8774: Usage: B<lond>
                   8775: 
                   8776: Should only be run as user=www.  This is a command-line script which
                   8777: is invoked by B<loncron>.  There is no expectation that a typical user
                   8778: will manually start B<lond> from the command-line.  (In other words,
                   8779: DO NOT START B<lond> YOURSELF.)
1.61      harris41 8780: 
                   8781: =head1 DESCRIPTION
                   8782: 
1.74      harris41 8783: There are two characteristics associated with the running of B<lond>,
                   8784: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   8785: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   8786: subscriptions, etc).  These are described in two large
                   8787: sections below.
                   8788: 
                   8789: B<PROCESS MANAGEMENT>
                   8790: 
1.61      harris41 8791: Preforker - server who forks first. Runs as a daemon. HUPs.
                   8792: Uses IDEA encryption
                   8793: 
1.74      harris41 8794: B<lond> forks off children processes that correspond to the other servers
                   8795: in the network.  Management of these processes can be done at the
                   8796: parent process level or the child process level.
                   8797: 
                   8798: B<logs/lond.log> is the location of log messages.
                   8799: 
                   8800: The process management is now explained in terms of linux shell commands,
                   8801: subroutines internal to this code, and signal assignments:
                   8802: 
                   8803: =over 4
                   8804: 
                   8805: =item *
                   8806: 
                   8807: PID is stored in B<logs/lond.pid>
                   8808: 
                   8809: This is the process id number of the parent B<lond> process.
                   8810: 
                   8811: =item *
                   8812: 
                   8813: SIGTERM and SIGINT
                   8814: 
                   8815: Parent signal assignment:
                   8816:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   8817: 
                   8818: Child signal assignment:
                   8819:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   8820: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   8821:  to restart a new child.)
                   8822: 
                   8823: Command-line invocations:
                   8824:  B<kill> B<-s> SIGTERM I<PID>
                   8825:  B<kill> B<-s> SIGINT I<PID>
                   8826: 
                   8827: Subroutine B<HUNTSMAN>:
                   8828:  This is only invoked for the B<lond> parent I<PID>.
                   8829: This kills all the children, and then the parent.
                   8830: The B<lonc.pid> file is cleared.
                   8831: 
                   8832: =item *
                   8833: 
                   8834: SIGHUP
                   8835: 
                   8836: Current bug:
                   8837:  This signal can only be processed the first time
                   8838: on the parent process.  Subsequent SIGHUP signals
                   8839: have no effect.
                   8840: 
                   8841: Parent signal assignment:
                   8842:  $SIG{HUP}  = \&HUPSMAN;
                   8843: 
                   8844: Child signal assignment:
                   8845:  none (nothing happens)
                   8846: 
                   8847: Command-line invocations:
                   8848:  B<kill> B<-s> SIGHUP I<PID>
                   8849: 
                   8850: Subroutine B<HUPSMAN>:
                   8851:  This is only invoked for the B<lond> parent I<PID>,
                   8852: This kills all the children, and then the parent.
                   8853: The B<lond.pid> file is cleared.
                   8854: 
                   8855: =item *
                   8856: 
                   8857: SIGUSR1
                   8858: 
                   8859: Parent signal assignment:
                   8860:  $SIG{USR1} = \&USRMAN;
                   8861: 
                   8862: Child signal assignment:
                   8863:  $SIG{USR1}= \&logstatus;
                   8864: 
                   8865: Command-line invocations:
                   8866:  B<kill> B<-s> SIGUSR1 I<PID>
                   8867: 
                   8868: Subroutine B<USRMAN>:
                   8869:  When invoked for the B<lond> parent I<PID>,
                   8870: SIGUSR1 is sent to all the children, and the status of
                   8871: each connection is logged.
1.144     foxr     8872: 
                   8873: =item *
                   8874: 
                   8875: SIGUSR2
                   8876: 
                   8877: Parent Signal assignment:
                   8878:     $SIG{USR2} = \&UpdateHosts
                   8879: 
                   8880: Child signal assignment:
                   8881:     NONE
                   8882: 
1.74      harris41 8883: 
                   8884: =item *
                   8885: 
                   8886: SIGCHLD
                   8887: 
                   8888: Parent signal assignment:
                   8889:  $SIG{CHLD} = \&REAPER;
                   8890: 
                   8891: Child signal assignment:
                   8892:  none
                   8893: 
                   8894: Command-line invocations:
                   8895:  B<kill> B<-s> SIGCHLD I<PID>
                   8896: 
                   8897: Subroutine B<REAPER>:
                   8898:  This is only invoked for the B<lond> parent I<PID>.
                   8899: Information pertaining to the child is removed.
                   8900: The socket port is cleaned up.
                   8901: 
                   8902: =back
                   8903: 
                   8904: B<SERVER-SIDE ACTIVITIES>
                   8905: 
                   8906: Server-side information can be accepted in an encrypted or non-encrypted
                   8907: method.
                   8908: 
                   8909: =over 4
                   8910: 
                   8911: =item ping
                   8912: 
                   8913: Query a client in the hosts.tab table; "Are you there?"
                   8914: 
                   8915: =item pong
                   8916: 
                   8917: Respond to a ping query.
                   8918: 
                   8919: =item ekey
                   8920: 
                   8921: Read in encrypted key, make cipher.  Respond with a buildkey.
                   8922: 
                   8923: =item load
                   8924: 
                   8925: Respond with CPU load based on a computation upon /proc/loadavg.
                   8926: 
                   8927: =item currentauth
                   8928: 
                   8929: Reply with current authentication information (only over an
                   8930: encrypted channel).
                   8931: 
                   8932: =item auth
                   8933: 
                   8934: Only over an encrypted channel, reply as to whether a user's
                   8935: authentication information can be validated.
                   8936: 
                   8937: =item passwd
                   8938: 
                   8939: Allow for a password to be set.
                   8940: 
                   8941: =item makeuser
                   8942: 
                   8943: Make a user.
                   8944: 
1.517     raeburn  8945: =item changeuserauth
1.74      harris41 8946: 
                   8947: Allow for authentication mechanism and password to be changed.
                   8948: 
                   8949: =item home
1.61      harris41 8950: 
1.74      harris41 8951: Respond to a question "are you the home for a given user?"
                   8952: 
                   8953: =item update
                   8954: 
                   8955: Update contents of a subscribed resource.
                   8956: 
                   8957: =item unsubscribe
                   8958: 
                   8959: The server is unsubscribing from a resource.
                   8960: 
                   8961: =item subscribe
                   8962: 
                   8963: The server is subscribing to a resource.
                   8964: 
                   8965: =item log
                   8966: 
                   8967: Place in B<logs/lond.log>
                   8968: 
                   8969: =item put
                   8970: 
                   8971: stores hash in namespace
                   8972: 
1.496     raeburn  8973: =item rolesput
1.74      harris41 8974: 
                   8975: put a role into a user's environment
                   8976: 
                   8977: =item get
                   8978: 
                   8979: returns hash with keys from array
                   8980: reference filled in from namespace
                   8981: 
                   8982: =item eget
                   8983: 
                   8984: returns hash with keys from array
                   8985: reference filled in from namesp (encrypts the return communication)
                   8986: 
                   8987: =item rolesget
                   8988: 
                   8989: get a role from a user's environment
                   8990: 
                   8991: =item del
                   8992: 
                   8993: deletes keys out of array from namespace
                   8994: 
                   8995: =item keys
                   8996: 
                   8997: returns namespace keys
                   8998: 
                   8999: =item dump
                   9000: 
                   9001: dumps the complete (or key matching regexp) namespace into a hash
                   9002: 
                   9003: =item store
                   9004: 
                   9005: stores hash permanently
                   9006: for this url; hashref needs to be given and should be a \%hashname; the
                   9007: remaining args aren't required and if they aren't passed or are '' they will
                   9008: be derived from the ENV
                   9009: 
                   9010: =item restore
                   9011: 
                   9012: returns a hash for a given url
                   9013: 
                   9014: =item querysend
                   9015: 
                   9016: Tells client about the lonsql process that has been launched in response
                   9017: to a sent query.
                   9018: 
                   9019: =item queryreply
                   9020: 
                   9021: Accept information from lonsql and make appropriate storage in temporary
                   9022: file space.
                   9023: 
                   9024: =item idput
                   9025: 
                   9026: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   9027: for each student, defined perhaps by the institutional Registrar.)
                   9028: 
                   9029: =item idget
                   9030: 
                   9031: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   9032: for each student, defined perhaps by the institutional Registrar.)
                   9033: 
1.517     raeburn  9034: =item iddel
                   9035: 
                   9036: Deletes one or more ids in a domain's id database.
                   9037: 
1.74      harris41 9038: =item tmpput
                   9039: 
                   9040: Accept and store information in temporary space.
                   9041: 
                   9042: =item tmpget
                   9043: 
                   9044: Send along temporarily stored information.
                   9045: 
                   9046: =item ls
                   9047: 
                   9048: List part of a user's directory.
                   9049: 
1.135     foxr     9050: =item pushtable
                   9051: 
                   9052: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   9053: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   9054: must be restored manually in case of a problem with the new table file.
                   9055: pushtable requires that the request be encrypted and validated via
                   9056: ValidateManager.  The form of the command is:
                   9057: enc:pushtable tablename <tablecontents> \n
                   9058: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   9059: cleartext newline.
                   9060: 
1.74      harris41 9061: =item Hanging up (exit or init)
                   9062: 
                   9063: What to do when a client tells the server that they (the client)
                   9064: are leaving the network.
                   9065: 
                   9066: =item unknown command
                   9067: 
                   9068: If B<lond> is sent an unknown command (not in the list above),
                   9069: it replys to the client "unknown_cmd".
1.135     foxr     9070: 
1.74      harris41 9071: 
                   9072: =item UNKNOWN CLIENT
                   9073: 
                   9074: If the anti-spoofing algorithm cannot verify the client,
                   9075: the client is rejected (with a "refused" message sent
                   9076: to the client, and the connection is closed.
                   9077: 
                   9078: =back
1.61      harris41 9079: 
                   9080: =head1 PREREQUISITES
                   9081: 
                   9082: IO::Socket
                   9083: IO::File
                   9084: Apache::File
                   9085: POSIX
                   9086: Crypt::IDEA
                   9087: GDBM_File
                   9088: Authen::Krb4
1.91      albertel 9089: Authen::Krb5
1.61      harris41 9090: 
                   9091: =head1 COREQUISITES
                   9092: 
1.490     droeschl 9093: none
                   9094: 
1.61      harris41 9095: =head1 OSNAMES
                   9096: 
                   9097: linux
                   9098: 
                   9099: =head1 SCRIPT CATEGORIES
                   9100: 
                   9101: Server/Process
                   9102: 
                   9103: =cut
1.409     foxr     9104: 
                   9105: 
                   9106: =pod
                   9107: 
                   9108: =head1 LOG MESSAGES
                   9109: 
                   9110: The messages below can be emitted in the lond log.  This log is located
                   9111: in ~httpd/perl/logs/lond.log  Many log messages have HTML encapsulation
                   9112: to provide coloring if examined from inside a web page. Some do not.
                   9113: Where color is used, the colors are; Red for sometihhng to get excited
                   9114: about and to follow up on. Yellow for something to keep an eye on to
                   9115: be sure it does not get worse, Green,and Blue for informational items.
                   9116: 
                   9117: In the discussions below, sometimes reference is made to ~httpd
                   9118: when describing file locations.  There isn't really an httpd 
                   9119: user, however there is an httpd directory that gets installed in the
                   9120: place that user home directories go.  On linux, this is usually
                   9121: (always?) /home/httpd.
                   9122: 
                   9123: 
                   9124: Some messages are colorless.  These are usually (not always)
                   9125: Green/Blue color level messages.
                   9126: 
                   9127: =over 2
                   9128: 
                   9129: =item (Red)  LocalConnection rejecting non local: <ip> ne 127.0.0.1
                   9130: 
                   9131: A local connection negotiation was attempted by
                   9132: a host whose IP address was not 127.0.0.1.
                   9133: The socket is closed and the child will exit.
                   9134: lond has three ways to establish an encyrption
                   9135: key with a client:
                   9136: 
                   9137: =over 2
                   9138: 
                   9139: =item local 
                   9140: 
                   9141: The key is written and read from a file.
                   9142: This is only valid for connections from localhost.
                   9143: 
                   9144: =item insecure 
                   9145: 
                   9146: The key is generated by the server and
                   9147: transmitted to the client.
                   9148: 
                   9149: =item  ssl (secure)
                   9150: 
                   9151: An ssl connection is negotiated with the client,
                   9152: the key is generated by the server and sent to the 
                   9153: client across this ssl connection before the
                   9154: ssl connectionis terminated and clear text
                   9155: transmission resumes.
                   9156: 
                   9157: =back
                   9158: 
                   9159: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
                   9160: 
                   9161: The client is local but has not sent an initialization
                   9162: string that is the literal "init:local"  The connection
                   9163: is closed and the child exits.
                   9164: 
                   9165: =item Red CRITICAL Can't get key file <error>        
                   9166: 
                   9167: SSL key negotiation is being attempted but the call to
1.549     raeburn  9168: lonssl::KeyFile failed.  This usually means that the
1.409     foxr     9169: configuration file is not correctly defining or protecting
                   9170: the directories/files lonCertificateDirectory or
                   9171: lonnetPrivateKey
                   9172: <error> is a string that describes the reason that
                   9173: the key file could not be located.
                   9174: 
                   9175: =item (Red) CRITICAL  Can't get certificates <error>  
                   9176: 
                   9177: SSL key negotiation failed because we were not able to retrives our certificate
                   9178: or the CA's certificate in the call to lonssl::CertificateFile
                   9179: <error> is the textual reason this failed.  Usual reasons:
                   9180: 
                   9181: =over 2
1.490     droeschl 9182: 
1.409     foxr     9183: =item Apache config file for loncapa  incorrect:
1.490     droeschl 9184: 
1.409     foxr     9185: one of the variables 
                   9186: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
                   9187: undefined or incorrect
                   9188: 
                   9189: =item Permission error:
                   9190: 
                   9191: The directory pointed to by lonCertificateDirectory is not readable by lond
                   9192: 
                   9193: =item Permission error:
                   9194: 
                   9195: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
                   9196: 
                   9197: =item Installation error:                         
                   9198: 
                   9199: Either the certificate authority file or the certificate have not
                   9200: been installed in lonCertificateDirectory.
                   9201: 
                   9202: =item (Red) CRITICAL SSL Socket promotion failed:  <err> 
                   9203: 
                   9204: The promotion of the connection from plaintext to SSL failed
                   9205: <err> is the reason for the failure.  There are two
                   9206: system calls involved in the promotion (one of which failed), 
                   9207: a dup to produce
                   9208: a second fd on the raw socket over which the encrypted data
                   9209: will flow and IO::SOcket::SSL->new_from_fd which creates
                   9210: the SSL connection on the duped fd.
                   9211: 
                   9212: =item (Blue)   WARNING client did not respond to challenge 
                   9213: 
                   9214: This occurs on an insecure (non SSL) connection negotiation request.
                   9215: lond generates some number from the time, the PID and sends it to
                   9216: the client.  The client must respond by echoing this information back.
                   9217: If the client does not do so, that's a violation of the challenge
                   9218: protocols and the connection will be failed.
                   9219: 
                   9220: =item (Red) No manager table. Nobody can manage!!    
                   9221: 
                   9222: lond has the concept of privileged hosts that
                   9223: can perform remote management function such
                   9224: as update the hosts.tab.   The manager hosts
                   9225: are described in the 
                   9226: ~httpd/lonTabs/managers.tab file.
                   9227: this message is logged if this file is missing.
                   9228: 
                   9229: 
                   9230: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
                   9231: 
                   9232: Reports the successful parse and registration
                   9233: of a specific manager. 
                   9234: 
                   9235: =item Green existing host <clustername:dnsname>  
                   9236: 
                   9237: The manager host is already defined in the hosts.tab
                   9238: the information in that table, rather than the info in the
                   9239: manager table will be used to determine the manager's ip.
                   9240: 
                   9241: =item (Red) Unable to craete <filename>                 
                   9242: 
                   9243: lond has been asked to create new versions of an administrative
                   9244: file (by a manager).  When this is done, the new file is created
                   9245: in a temp file and then renamed into place so that there are always
                   9246: usable administrative files, even if the update fails.  This failure
                   9247: message means that the temp file could not be created.
                   9248: The update is abandoned, and the old file is available for use.
                   9249: 
                   9250: =item (Green) CopyFile from <oldname> to <newname> failed
                   9251: 
                   9252: In an update of administrative files, the copy of the existing file to a
                   9253: backup file failed.  The installation of the new file may still succeed,
                   9254: but there will not be a back up file to rever to (this should probably
                   9255: be yellow).
                   9256: 
                   9257: =item (Green) Pushfile: backed up <oldname> to <newname>
                   9258: 
                   9259: See above, the backup of the old administrative file succeeded.
                   9260: 
                   9261: =item (Red)  Pushfile: Unable to install <filename> <reason>
                   9262: 
                   9263: The new administrative file could not be installed.  In this case,
                   9264: the old administrative file is still in use.
                   9265: 
                   9266: =item (Green) Installed new < filename>.                      
                   9267: 
                   9268: The new administrative file was successfullly installed.                                               
                   9269: 
                   9270: =item (Red) Reinitializing lond pid=<pid>                    
                   9271: 
                   9272: The lonc child process <pid> will be sent a USR2 
                   9273: signal.
                   9274: 
                   9275: =item (Red) Reinitializing self                                    
                   9276: 
                   9277: We've been asked to re-read our administrative files,and
                   9278: are doing so.
                   9279: 
                   9280: =item (Yellow) error:Invalid process identifier <ident>  
                   9281: 
                   9282: A reinit command was received, but the target part of the 
                   9283: command was not valid.  It must be either
                   9284: 'lond' or 'lonc' but was <ident>
                   9285: 
                   9286: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
                   9287: 
                   9288: Checking to see if lond has been handed a valid edit
                   9289: command.  It is possible the edit command is not valid
                   9290: in that case there are no log messages to indicate that.
                   9291: 
                   9292: =item Result of password change for  <username> pwchange_success
                   9293: 
                   9294: The password for <username> was
                   9295: successfully changed.
                   9296: 
                   9297: =item Unable to open <user> passwd to change password
                   9298: 
                   9299: Could not rewrite the 
                   9300: internal password file for a user
                   9301: 
                   9302: =item Result of password change for <user> : <result>
1.490     droeschl 9303: 
1.409     foxr     9304: A unix password change for <user> was attempted 
                   9305: and the pipe returned <result>  
                   9306: 
                   9307: =item LWP GET: <message> for <fname> (<remoteurl>)
                   9308: 
                   9309: The lightweight process fetch for a resource failed
                   9310: with <message> the local filename that should
                   9311: have existed/been created was  <fname> the
                   9312: corresponding URI: <remoteurl>  This is emitted in several
                   9313: places.
                   9314: 
                   9315: =item Unable to move <transname> to <destname>     
                   9316: 
                   9317: From fetch_user_file_handler - the user file was replicated but could not
                   9318: be mv'd to its final location.
                   9319: 
                   9320: =item Looking for <domain> <username>              
                   9321: 
                   9322: From user_has_session_handler - This should be a Debug call instead
                   9323: it indicates lond is about to check whether the specified user has a 
                   9324: session active on the specified domain on the local host.
                   9325: 
                   9326: =item Client <ip> (<name>) hanging up: <input>     
                   9327: 
                   9328: lond has been asked to exit by its client.  The <ip> and <name> identify the
                   9329: client systemand <input> is the full exit command sent to the server.
                   9330: 
                   9331: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
1.490     droeschl 9332: 
1.409     foxr     9333: A lond child terminated.  NOte that this termination can also occur when the
                   9334: child receives the QUIT or DIE signals.  <pid> is the process id of the child,
                   9335: <hostname> the host lond is working for, and <message> the reason the child died
                   9336: to the best of our ability to get it (I would guess that any numeric value
                   9337: represents and errno value).  This is immediately followed by
                   9338: 
                   9339: =item  Famous last words: Catching exception - <log> 
                   9340: 
                   9341: Where log is some recent information about the state of the child.
                   9342: 
                   9343: =item Red CRITICAL: TIME OUT <pid>                     
                   9344: 
                   9345: Some timeout occured for server <pid>.  THis is normally a timeout on an LWP
                   9346: doing an HTTP::GET.
                   9347: 
                   9348: =item child <pid> died                              
                   9349: 
                   9350: The reaper caught a SIGCHILD for the lond child process <pid>
                   9351: This should be modified to also display the IP of the dying child
                   9352: $children{$pid}
                   9353: 
                   9354: =item Unknown child 0 died                           
                   9355: A child died but the wait for it returned a pid of zero which really should not
                   9356: ever happen. 
                   9357: 
                   9358: =item Child <which> - <pid> looks like we missed it's death 
                   9359: 
                   9360: When a sigchild is received, the reaper process checks all children to see if they are
                   9361: alive.  If children are dying quite quickly, the lack of signal queuing can mean
                   9362: that a signal hearalds the death of more than one child.  If so this message indicates
                   9363: which other one died. <which> is the ip of a dead child
                   9364: 
                   9365: =item Free socket: <shutdownretval>                
                   9366: 
                   9367: The HUNTSMAN sub was called due to a SIGINT in a child process.  The socket is being shutdown.
                   9368: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
                   9369: to return anything. This is followed by: 
                   9370: 
                   9371: =item Red CRITICAL: Shutting down                       
                   9372: 
                   9373: Just prior to exit.
                   9374: 
                   9375: =item Free socket: <shutdownretval>                 
                   9376: 
                   9377: The HUPSMAN sub was called due to a SIGHUP.  all children get killsed, and lond execs itself.
                   9378: This is followed by:
                   9379: 
                   9380: =item (Red) CRITICAL: Restarting                         
                   9381: 
                   9382: lond is about to exec itself to restart.
                   9383: 
                   9384: =item (Blue) Updating connections                        
                   9385: 
                   9386: (In response to a USR2).  All the children (except the one for localhost)
                   9387: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
                   9388: 
                   9389: =item (Blue) UpdateHosts killing child <pid> for ip <ip>   
                   9390: 
                   9391: Due to USR2 as above.
                   9392: 
                   9393: =item (Green) keeping child for ip <ip> (pid = <pid>)    
                   9394: 
                   9395: In response to USR2 as above, the child indicated is not being restarted because
                   9396: it's assumed that we'll always need a child for the localhost.
                   9397: 
                   9398: 
                   9399: =item Going to check on the children                
                   9400: 
                   9401: Parent is about to check on the health of the child processes.
                   9402: Note that this is in response to a USR1 sent to the parent lond.
                   9403: there may be one or more of the next two messages:
                   9404: 
                   9405: =item <pid> is dead                                 
                   9406: 
                   9407: A child that we have in our child hash as alive has evidently died.
                   9408: 
                   9409: =item  Child <pid> did not respond                   
                   9410: 
                   9411: In the health check the child <pid> did not update/produce a pid_.txt
                   9412: file when sent it's USR1 signal.  That process is killed with a 9 signal, as it's
                   9413: assumed to be hung in some un-fixable way.
                   9414: 
                   9415: =item Finished checking children                   
1.490     droeschl 9416: 
1.409     foxr     9417: Master processs's USR1 processing is cojmplete.
                   9418: 
                   9419: =item (Red) CRITICAL: ------- Starting ------            
                   9420: 
                   9421: (There are more '-'s on either side).  Lond has forked itself off to 
                   9422: form a new session and is about to start actual initialization.
                   9423: 
                   9424: =item (Green) Attempting to start child (<client>)       
                   9425: 
                   9426: Started a new child process for <client>.  Client is IO::Socket object
                   9427: connected to the child.  This was as a result of a TCP/IP connection from a client.
                   9428: 
                   9429: =item Unable to determine who caller was, getpeername returned nothing
1.490     droeschl 9430: 
1.409     foxr     9431: In child process initialization.  either getpeername returned undef or
                   9432: a zero sized object was returned.  Processing continues, but in my opinion,
                   9433: this should be cause for the child to exit.
                   9434: 
                   9435: =item Unable to determine clientip                  
                   9436: 
                   9437: In child process initialization.  The peer address from getpeername was not defined.
                   9438: The client address is stored as "Unavailable" and processing continues.
                   9439: 
                   9440: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
1.490     droeschl 9441: 
1.409     foxr     9442: In child initialization.  A good connectionw as received from <ip>.
                   9443: 
                   9444: =over 2
                   9445: 
                   9446: =item <name> 
                   9447: 
                   9448: is the name of the client from hosts.tab.
                   9449: 
                   9450: =item <type> 
                   9451: 
                   9452: Is the connection type which is either 
                   9453: 
                   9454: =over 2
                   9455: 
                   9456: =item manager 
                   9457: 
                   9458: The connection is from a manager node, not in hosts.tab
                   9459: 
                   9460: =item client  
                   9461: 
                   9462: the connection is from a non-manager in the hosts.tab
                   9463: 
                   9464: =item both
                   9465: 
                   9466: The connection is from a manager in the hosts.tab.
                   9467: 
                   9468: =back
                   9469: 
                   9470: =back
                   9471: 
                   9472: =item (Blue) Certificates not installed -- trying insecure auth
                   9473: 
                   9474: One of the certificate file, key file or
                   9475: certificate authority file could not be found for a client attempting
                   9476: SSL connection intiation.  COnnection will be attemptied in in-secure mode.
                   9477: (this would be a system with an up to date lond that has not gotten a 
                   9478: certificate from us).
                   9479: 
                   9480: =item (Green)  Successful local authentication            
                   9481: 
                   9482: A local connection successfully negotiated the encryption key. 
                   9483: In this case the IDEA key is in a file (that is hopefully well protected).
                   9484: 
                   9485: =item (Green) Successful ssl authentication with <client>  
                   9486: 
                   9487: The client (<client> is the peer's name in hosts.tab), has successfully
                   9488: negotiated an SSL connection with this child process.
                   9489: 
                   9490: =item (Green) Successful insecure authentication with <client>
1.490     droeschl 9491: 
1.409     foxr     9492: 
                   9493: The client has successfully negotiated an  insecure connection withthe child process.
                   9494: 
                   9495: =item (Yellow) Attempted insecure connection disallowed    
                   9496: 
                   9497: The client attempted and failed to successfully negotiate a successful insecure
                   9498: connection.  This can happen either because the variable londAllowInsecure is false
                   9499: or undefined, or becuse the child did not successfully echo back the challenge
                   9500: string.
                   9501: 
                   9502: 
                   9503: =back
                   9504: 
1.441     raeburn  9505: =back
                   9506: 
1.409     foxr     9507: 
                   9508: =cut

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